File
File
All the operations that you perform on a data such as searching, sorting, insertion,
deletion etc. can be performed by Java Collection Framework.
What is Collection ?
What is framework ?
Collection framework
Collection framework represents a unified architecture for storing and
manipulating group of object. It has:
Core Java
Iterator interface :
Core Java
List Of Interfaces and Classes :
Interface
Set
List
Deque
Map
Hash
Balanced
Resizable Array
Table
Tree
HashSet
TreeSet
ArrayList
ArrayDeque
HashMap
TreeMap
Linked List
LinkedList
LinkedList
LinkedHashMap
ArrayList :
not synchronized
Core Java
Array lists are created with an initial size. When this size is
exceeded, the collection is automatically enlarged. When objects
are removed, the array may be shrunk.
Core Java
Example,
List list = Collections.synchronizedList(new ArrayList(...));
Example Of ArrayList :
1) Creating ArrayList
ArrayList<String> stringList = new ArrayList<String>(); //Generic
ArrayList to Store only String objects
You can use indexOf() method of ArrayList in Java to find out index of a
particular object.
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not
contain the element.
Int index = stringList.indexOf("Item");//location of Item object in List
Returns the index of the last occurrence of the specified element in this list, or -1 if this list does
not contain the element.
Int index = stringList.lastIndexOf("Item");//location of Item object in
List
4) Checking ArrayList for an Item
Sometimes we need to check whether an element exists in ArrayList in Java
or not for this purpose we can use contains() method of Java. contains()
method takes type of object defined in ArrayList creation and returns
true if this list contains the specified element.
Core Java
contains(Object o)
Returns true if this list contains the specified element
5) Removing an Item from ArrayList
There are two ways to remove any elements from ArrayList in Java. You can
either remove an element based on its index or by providing object
itself.
Remove remove (int index) and remove (Object o) method is used to remove
any element from ArrayList in Java.
In below code first call will remove first element from ArrayList
while second call will remove first occurrence of item from
ArrayList in Java.
Many a times you need to create a copy of ArrayList for this purpose you
can use addAll(Collection c) method of ArrayList in Java to copy all
elements from on ArrayList to another ArrayList in Java.
ArrayList<String>copyOfStringList =newArrayList<String>();
copyOfStringList.addAll(stringList);
You can use set (int index, E element) method of java ArrayList to
replace any element from a particular index.
stringList.set(0,"Item2");
Java ArrayList provides you facility to get the array back from your
ArrayList.
Core Java
String[]itemArray =newString[stringList.size()];
String[]returnedArray = stringList.toArray(itemArray);
9) Converting from Array to ArrayList in Java
This is the simplest way of converting from array to arraylist.
String[] asset = {"equity", "stocks", "gold", "foreign exchange","fixed income", "futures",
"options"};
List assetList =Arrays.asList(asset);
Its worth to note following point while using Arrays.asList() method for
array to arraylist conversion
1) This method returns a List view of underlying array.
2) List returned by this method would be fixed size.
3) Most important point to note is when you change an element into this List corresponding
element in original array will also be changed.
4) Another important point is since List is fixed size, you can not add element into it. If you
try you will get exception.
5) This is the most efficient way of converting array to arraylist as per my
knowledge because it doesn't copy the content of underlying array to create list.
6) From Java 5 or JDK 1.5 onwards this method supports generic so you can
generate type safe ArrayList from array.
10) Array to ArrayList by using Collections.addAll method
This example of converting an array to arraylist is not that efficient as
the earlier method but its more flexible.
List assetList = new ArrayList();
String[] asset = {"equity", "stocks", "gold", "foriegn exchange", "fixed income", "futures",
"options"};
Collections.addAll(assetList, asset);
Important point about this method of array to ArrayList conversion is :
1) Its not as fast as Arrays.asList() but more flexible.
2) This method actually copies the content of the underlying array into
ArrayList provided.
3) Since you are creating copy of original array, you can add, modify and remove any element
without affecting original one.
4) If you want to provide individual element you can do so by specifying
Core Java
them individually as comma separated. Which is a very convenient way of
inserting some more elements into existing list for example,
Collections.addAll(assetList,"EquityDerivatives","Eqity Index
Arbitrage","Mutual Fund");
11) This is another great way of converting an array to arraylist.
We are essentially using Collection interface's addAll() method for
copying content from one list to another.
Since List returned by Arrays.asList is fixed-size its not much of use,
this way we can convert that into proper arraylist.
Arraylist newAssetList =newArraylist();
newAssetList.addAll(Arrays.asList(asset));
Also List allows duplicates but Set doesn't allow any duplicates, which means if you have duplicates
in your ArrayList they will be lost when you convert ArrayList to HashSet and that's the reason why
sometime size of ArrayList doesn't match with size of HashSet after conversion
Example,
HashSet companySet = new HashSet(Collection<? extends E> c);
Core Java
14) If we set ArrayList reference null in Java all the elements inside
ArrayList becomes eligible to garbage collection in java , provided there are no
more reference exists for those objects.
Difference between Arrays and ArrayList :
Arrays
ArrayList
An array is type specific i.e. one array can only store data of
only one data type where as arraylist can store multiple data in
the form of objects. So multiple objects of different data types
can be stored in arraylist.
Core Java
DISADVANTAGES OF USING ARRAYLIST
Not efficient for large quantity of data because when the arraylist has to
increase its size, its content is copied to a larger arraylist
which can be a slow process.
It can only holds Objects i.e. it cant hold normal data types values
such as int .
Vector vs ArrayList :
Common property of Vector and ArrayList in Java
1) Both Vector and ArrayList are derived from AbstractList and implements
List interface, which means both of them are ordered collection and allows
duplicates.
2) Another similarity between Vector vs ArrayList is that both are index
based Collection and you can use get(index) method to retrieve objects from
Vector and ArrayList.
Vector vs ArrayList in Java
1) First and most common difference between Vector vs ArrayList is that
Vector is synchronized and thread-safe while ArrayList is neither Synchronized nor
Core Java
thread-safe. Now, What does that mean? It means if multiple thread try to
access Vector same time they can do that without compromising Vector's
internal state. Same is not true in case of ArrayList as methods like
add(), remove() or get() is not synchronized.
2) Second major difference on Vector vs ArrayList is Speed, which is directly
related to previous difference. Since Vector is synchronized, its slow
and ArrayList is not synchronized its faster than Vector.
3) Third difference on Vector vs ArrayList is that Vector is a legacy class
and initially it was not part of Java Collection Framework.
These were some comparison on Vector vs ArrayList. In Summary use
ArrayList if you are using ArrayList in Single threaded environment and
use Vector if you need a thread-safe collection. ArrayList is anytime faster
than Vector in case thread-safety is not a concern.
What do you mean by Legacy class in JAVA?
Legacy classes are those that were built using Java 1.1 or Java 1.2
API. In general we cannot use this term for java classes. Say for
example when Java 1.0 was available Vector was used instead of
dynamic array and since there was no ArrayList class people were
forced to use Vector for this purpose.
When Java 1.2 was released ArrayList was much more advanced to
Vector but has all the features of Vector too. So people started
using ArrayList instead of Vector (this again depends on the
project requirement, both Vector and ArrayList have their own
advantages). And in this case Vector became legacy class.
But this is not constant since in future Sun may introduce a new
class that is much more advanced to ArrayList and Vector. And then
we call both ArrayList and Vector as legacy classes.
Example,
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Text 1");
list.add("Text 2");
list.add("Text 3");
System.out.println("#1 normal for loop");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
Core Java
System.out.println("#2 advance for loop");
for (String temp : list) {
System.out.println(temp);
}
System.out.println("#3 while loop");
int j = 0;
while (list.size() > j) {
System.out.println(list.get(j));
j++;
}
System.out.println("#4 iterator");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
Example ,
int i = 42; //int is of primitive type
i = 43; // OK
Mutable
Core Java
original content in str. What happens is that a new String object
"hello" is constructed. The toLowerCase() method returns the new
constructed String object's reference. Let's modify the above code:
class Program {
public static void main(String[] args) {
String str = "HELLO";
System.out.println(str);
String str1 = str.toLowerCase();
System.out.println(str1);
}
}
The output result is
HELLO
hello
The str1 references a new String object that contains "hello". The
String object's method never affects the data the String object
contains, excluding the constructor.
Core Java
append or trim or some other method call to modify your string object, you would
really be creating those many new objects of class String.
Now isnt that a performance issue?
Yes, it definitely is.
Then how do you make your string operations efficient?
By using StringBuffer or StringBuilder.
How would that help?
Well, since StringBuffer/StringBuilder objects are mutable, we can make
changes to the value stored in the object. What this effectively means is that string
operations such as append would be more efficient if performed using
StringBuffer/StringBuilder objects than String objects.
Finally, whats the difference between StringBuffer and StringBuilder?
StringBuffer and StringBuilder have the same methods with one difference and
thats of synchronization. StringBuffer is synchronized( which means it is
thread safe and hence you can use it when you implement threads for your
methods) whereas StringBuilder is not synchronized( which implies it isnt
thread safe).
So, if you arent going to use threading then use the StringBuilder class
as itll be more efficient than StringBuffer due to the absence of
synchronization.
Core Java
String s = Hello;
s = s + World;
system.out.println(s);
I agree itll give you Hello World, but fella. lets be different from the rest and
think about making the code more efficient.
Enter Scene 2.
StringBuilder sb = new StringBuilder(Hello);
sb.append( World);
system.out.println(sb);
well thats it!! Youll get your Hello World but in a more efficient way
Core Java
System.out.println(s);
s = s.concat( if the String object is IMMUTABLE);
System.out.println(s);
The output of the above code will be:
Lets test
Lets test if the String object is IMMUTABLE
Thats all people! The above piece of code proves that String is immutable and
hence the results of operations like concat etc. should be stored into a new object.
LinkedList :
Example,
public static void main(String[] args) {
System.out.println("Linked List Example!");
LinkedList <Integer>list = new LinkedList<Integer>();
int num1 = 11, num2 = 22, num3 = 33, num4 = 44;
int size;
Iterator iterator;
//Adding data in the list
list.add(num1);
list.add(num2);
list.add(num3);
Core Java
list.add(num4);
size = list.size();
System.out.print( "Linked list data: ");
//Create a iterator
iterator = list.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
//Check list empty or not
if (list.isEmpty()){
System.out.println("Linked list is empty");
}
else{
System.out.println( "Linked list size: " + size);
}
System.out.println("Adding data at 1st location: 55");
//Adding first
list.addFirst(55);
System.out.print("Now the list contain: ");
iterator = list.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
System.out.println("Now the size of list: " + list.size());
System.out.println("Adding data at last location: 66");
//Adding last or append
list.addLast(66);
System.out.print("Now the list contain: ");
iterator = list.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
System.out.println("Now the size of list: " + list.size());
System.out.println("Adding data at 3rd location: 55");
//Adding data at 3rd position
list.add(2,99);
System.out.print("Now the list contain: ");
Core Java
iterator = list.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
System.out.println("Now the size of list: " + list.size());
//Retrieve first data
System.out.println("First data: " + list.getFirst());
//Retrieve lst data
System.out.println("Last data: " + list.getLast());
//Retrieve specific data
System.out.println("Data at 4th position: " + list.get(3));
//Remove first
int first = list.removeFirst();
System.out.println("Data removed from 1st location: " + first);
System.out.print("Now the list contain: ");
iterator = list.iterator();
//After removing data
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
System.out.println("Now the size of list: " + list.size());
//Remove last
int last = list.removeLast();
System.out.println("Data removed from last location: " + last);
System.out.print("Now the list contain: ");
iterator = list.iterator();
//After removing data
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
System.out.println("Now the size of list: " + list.size());
//Remove 2nd data
int second = list.remove(1);
System.out.println("Data removed from 2nd location: " + second);
System.out.print("Now the list contain: ");
iterator = list.iterator();
//After removing data
Core Java
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
System.out.println("Now the size of list: " + list.size());
//Remove all
list.clear();
if (list.isEmpty()){
System.out.println("Linked list is empty");
}
else{
System.out.println( "Linked list size: " + size);
}
}
public class LinkedListTest {
public static void main(String[] args) {
List<String> ll = new LinkedList<String>();
ll.add("3");
ll.add("2");
ll.add(null);
ll.add("4");
ll.add("4");
ll.add(null);
ll.add(null);
ll.add(null);
}
}
Output :
3
2
null
4
4
null
null
null
Core Java
Doubly Linked List :
Each node contains two fields, called links, that are references to
the previous and to the next node in the sequence of nodes.
Core Java
ArrayList vs. LinkedList vs. Vector
Time Duration :
ArrayList add: 13265642
LinkedList add: 9550057
ArrayList get: 1543352
LinkedList get: 85085551
ArrayList remove: 199961301
LinkedList remove: 85768810
The difference of their performance is obvious. LinkedList is faster in add and
remove, but slower in get. LinkedList should be preferred if:
Core Java
List Interface :
List Interface is the subinterface of Collection. It contains methods to
insert and delete elements in index basis. It is a factory of
ListIterator interface.
ListIterator :
ListIterator Interface is used to traverse the element in backward and
forward direction
Core Java
2) But we get List Iterator object only from List interface, see here :
where as List Iterator, which allows you to traverse in either directions.
That is List Iterators traverse two directions. So it has another methods
hasPrevious() & previous() other than Iterator.
Methods in ListIterator
1.hasNext()
2.next()
3.previous()
4.hasPrevious()
5.remove()
6.nextIndex()
7.previousIndex()
ListIterator listite = List.listIterator();
i.e., we can't get List Iterator object from Set interface.
Sno
Iterator
List Iterator
Methods in Iterator :
Methods in ListIterator
hashNext()
next()
remove()
hasNext()
next()
previous()
hasPrevious()
remove()
nextIndex()
previousIndex()
Core Java
Example,
public class IteratorAndListIterator {
public static void main(String[] args) {
List<String> namesList = new ArrayList<String>();
namesList.add("A");
namesList.add("B");
namesList.add("C");
namesList.add("D");
namesList.add("E");
Iterator<String> iterator = namesList.iterator();
System.out.println("Using Iterator");
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
System.out.println();
System.out.println("Using List Iterator");
ListIterator<String> listIterator = namesList.listIterator();
while (listIterator.hasNext()) {
System.out.print(listIterator.nextIndex());
System.out.println(" " + listIterator.next());
}
element");
System.out.println();
System.out.println("Using ListIterator with Insertion of an
listIterator = namesList.listIterator();
while (listIterator.hasNext()) {
System.out.print(listIterator.nextIndex());
if (listIterator.nextIndex() == 2) {
listIterator.add("Q");
}
System.out.println(" " + listIterator.next());
}
System.out.println();
System.out.println("Using ListIterator with iteration in
reverse order");
listIterator = namesList.listIterator(6);
while (listIterator.hasPrevious()) {
System.out.print(listIterator.previousIndex());
System.out.println(" " + listIterator.previous());
}
}
}
Core Java
Output
Using Iterator
A
B
C
D
E
Using List Iterator
0A
1B
2C
3D
4E
Using ListIterator with Insertion of an element
0A
1B
2C
4D
5E
Using ListIterator with iteration in reverse order
5E
4D
3C
2Q
1B
0A
Set
LinkedList
HashSet (unordered)
ArrayList
LinkedHashSet (ordered)
TreeSet (sorted by natural order or
by provided comparator)
SET :
Core Java
HashSet :
Example,
class Simple{
public static void main(String args[]){
HashSet al=new HashSet();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output : Ajay
Vijay
Ravi
The HashSet class supports four constructors. The first form constructs a
default hash set:
1) HashSet( )
Core Java
The following constructor form initializes the hash set by using the
elements of c.
2) HashSet(Collection c)
The following constructor form initializes the capacity of the hash set
to capacity.
The capacity grows automatically as elements are added to the Hash.
3) HashSet(int capacity)
The fourth form initializes both the capacity and the fill ratio (also
called load capacity) of the hash set from its arguments:
4) HashSet(int capacity, float fillRatio)
Make it Synchronized Set :
Set s = Collections.synchronizedSet(new HashSet());
...
synchronized (s) {
Iterator i = s.iterator(); // Must be in the synchronized block
while (i.hasNext())
foo(i.next());
}
Make it Read-Only Colelction :
Syntax :
public static <T> Set<T> unmodifiableSet(Set<? extends T> s)
Collections.unmodifiableSet(new HashSet());
Example,
public static void main(String[] args) {
// TODO Auto-generated method stub
Set<String> set = new HashSet<String>();
set.add("O");
set.add("C");
set.add("A");
set.add("B");
/*Set<String> linkedSet = new LinkedHashSet<String>();
linkedSet.add("O");
linkedSet.add("C");
linkedSet.add("A");
linkedSet.add("B");
Core Java
for (String str : linkedSet) {
System.out.println(str);
}*/
for (String str : set) {
System.out.println(str);
}
}
Output : (default ascending order)
A
B
C
O
Using LinkedHashset it displays insertion order like
O
C
A
B
public static void main(String [] args) {
System.out.println( "Collection Example!\n" );
int size;
// Create a collection
HashSet <String>set = new HashSet <String>();
String str1 = "Yellow", str2 = "White", str3 = "Green", str4 = "Blue";
Iterator iterator;
//Adding data in the collection
set.add(str1);
set.add(str2);
set.add(str3);
set.add(str4);
System.out.print(" set data: ");
//Create a iterator
iterator = set.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
// Get size of a collection
size = set.size();
if (set.isEmpty()){
System.out.println(" set is empty");
}
else{
System.out.println( " set size: " + size);
Core Java
}
System.out.println();
// Remove specific data
set.remove(str2);
System.out.println("After removing [" + str2 + "]\n");
System.out.print("Now collection data: ");
iterator = set.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
size = set.size();
System.out.println(" set size: " + size + "\n");
//Collection empty
set.clear();
size = set.size();
if (set.isEmpty()){
System.out.println(" set is empty");
}
else{
System.out.println( " set size: " + size);
}
}
Readonly collections
public class ReadOnlyCollections {
public static void main(String args[]) {
// creating a list
List godList = Arrays
.asList(new String[] { "Donald", "Dennis", "Ken" });
Core Java
// the following statement allows to modify the above set as the
// reference is pointing to the original collection therefore it is not
// read-only
set.add("Alan");
LinkedHashSet :
Core Java
Use this class instead of HashSet when you care about the iteration
order.
HashSet vs LinkedHashSet :
The only difference is that the LinkedHashSet maintains the order of the
items added to the Set.
TreeSet :
SortedSet s = Collections.synchronizedSortedSet(new
TreeSet(...));
Core Java
Example,
public static void main(String[] args) {
System.out.println("Tree Set Example!\n");
TreeSet tree = new TreeSet();
tree.add(12);
tree.add(63);
// Output 12, 34, 45, 63
tree.add(34);
tree.add(45);
// here it test it's sorted, 63 is the last element. see output below
Iterator iterator = tree.iterator();
System.out.print("Tree set data: ");
//Displaying the Tree set data
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
System.out.println();
//Check empty or not
if (tree.isEmpty()) {
System.out.print("Tree Set is empty.");
} else {
System.out.println("Tree Set size: " + tree.size());
}
//Retrieve first data from tree set
System.out.println("First data: " + tree.first());
//Retrieve last data from tree set
System.out.println("Last data: " + tree.last());
if (tree.remove(45)) { // remove element by value
System.out.println("Data is removed from tree set");
} else {
System.out.println("Data doesn't exist!");
}
System.out.print("Now the tree set contain: ");
iterator = tree.iterator();
Core Java
HashSet vs TreeSet vs LinkedHashSet :
Core Java
HashSet vs TreeSet in Java
Now let's see couple of differences between HashSet vs TreeSet in Java.
This is enough to decide whether you should use HashSet or TreeSet in a
given scenario.
1) First major difference between HashSet and TreeSet is performance.
HashSet is faster than TreeSet and should be preferred choice if sorting
of element is not required.
2) Second difference between HashSet and TreeSet is that HashSet allows null
object but TreeSet doesn't allow null Object and throw NullPointerException, Why,
because TreeSet uses compareTo() method to compare keys and compareTo() will
throw java.lang.NullPointerException as shown in below example :
HashSet <String> hashSet =new HashSet<String>();
hashSet.add("Java");
hashSet.add(null);
TreeSet <String> treeSet =new TreeSet<String>();
treeSet.add("C++");
treeSet.add(null);//Java.lang.NullPointerException
Output:
Exceptionin thread"main"java.lang.NullPointerException
at java.util.TreeMap.put(TreeMap.java:541)
at java.util.TreeSet.add(TreeSet.java:238)
at test.CollectionTest.main(CollectionTest.java:27)
JavaResult:1
Core Java
Comparable Interface : (for sorting purpose)
It provide only single sorting sequence i.e. you can sort the elements
based on single data member only.
public int compareTo(Object obj) is used to compare the current object with the
specified object.
public void sort(List list) is used to sort the elements of List. List
elements must be of Comparable type.
Example ,
class Student implements Comparable{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
Core Java
public int compareTo(Object obj){
Student st=(Student)obj;
if(age==st.age)
return 0;
else if(age > st.age)
return 1;
else
return -1;
}}
Comparator interface :
It provides multiple sorting sequence i.e. you can sort the elements
based on any data member.
public int compare(Object obj1,Object obj2) compares the first object with
second object.
Example,
1) class AgeComparator implements Comparator{
public int Compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;
if(s1.age==s2.age)
return 0;
else if(s1.age>s2.age)
return 1;
else
return -1;
}
}
Core Java
2) class NameComparator implements Comparator{
public int Compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;
return s1.name.compareTo(s2.name);
}
}
3) class Simple{
public static void main(String args[]){
ArrayList al=new ArrayList();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));
System.out.println("Sorting by Name...");
Collections.sort(al,new NameComparator());
Iterator itr=al.iterator();
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
System.out.println("sorting by age...");
Collections.sort(al,new AgeComparator());
Iterator itr2=al.iterator();
while(itr2.hasNext()){
Student st=(Student)itr2.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}}}
Core Java
Comparator vs Comparable :
Parameter
Comparator
Sorting logic is in separate
Sorting logic must be in
class. Hence we can write
same class whose objects
different sorting based on
are being sorted. Hence
Sorting logic
different attributes of objects
this is called natural
to be sorted. E.g. Sorting using
ordering of objects
id, name etc.
Class whose objects to be sorted
Class whose objects to be do not need to implement this
sorted must implement thisinterface. Some other class can
interface. e.g Country
implement this interface.
Implementation class needs to implement E.g.-CountrySortByIdComparator
comparable to collection class can implement Comparator
of country object by id
interface to sort collection of
country object by id
int compareTo(Object o1)
This method compares this
object with o1 object and int compare(Object o1,Object o2)
returns a integer. Its
This method compares o1 and o2
value has following
objects. and returns a integer.
meaning
Its value has following meaning.
1.
positive
this
object
1. positive o1 is greater than
Sorting method
is greater than o1
o2
2. zero this object
2. zero o1 equals to o2
equals to o1
3. negative o1 is less than o1
3. negative this object
is less than o1
Collections.sort(List)
Collections.sort(List, Comparator)
Here objects will be
Here objects will be sorted on
Calling method
sorted on the basis of
the basis of Compare method in
CompareTo method
Comparator
Package
Sorting
Sequence
Comparable
Java.lang.Comparable
Accepts Single Sorting
Sequence
Java.util.Comparator
Accepts Multiple Sorting Sequence
Example,
package org.arpit.javapostsforlearning;
//If this.cuntryId < country.countryId:then compare method will return -1
//If this.countryId > country.countryId:then compare method will return 1
//If this.countryId==country.countryId:then compare method will return 0
public class Country implements Comparable{
int countryId;
String countryName;
public Country(int countryId, String countryName) {
super();
this.countryId = countryId;
this.countryName = countryName;
}
@Override
Core Java
public int compareTo(Object arg0) {
Country country=(Country) arg0;
return (this.countryId < country.countryId ) ? -1:
(this.countryId > country.countryId ) ? 1:0 ;
}
public int getCountryId() {
return countryId;
}
public void setCountryId(int countryId) {
this.countryId = countryId;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
}
ComparableMain :
package org.arpit.javapostsforlearning;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ComparableMain {
/**
* @author Arpit Mandliya
*/
public static void main(String[] args) {
Country indiaCountry=new Country(1, 'India');
Country chinaCountry=new Country(4, 'China');
Country nepalCountry=new Country(3, 'Nepal');
Country bhutanCountry=new Country(2, 'Bhutan');
List<Country> listOfCountries = new ArrayList<Country>();
listOfCountries.add(indiaCountry);
listOfCountries.add(chinaCountry);
listOfCountries.add(nepalCountry);
listOfCountries.add(bhutanCountry);
System.out.println('Before Sort : ');
for (int i = 0; i < listOfCountries.size(); i++) {
Country country=(Country)
listOfCountries.get(i);
System.out.println('Country Id:
'+country.getCountryId()+'||'+'Country name: '+country.getCountryName());
}
Collections.sort(listOfCountries);
Core Java
System.out.println('After Sort : ');
for (int i = 0; i < listOfCountries.size(); i++) {
Country country=(Country)
listOfCountries.get(i);
System.out.println('Country Id:
'+country.getCountryId()+'|| '+'Country name:
'+country.getCountryName());
}
}
}
Before Sort
Country Id:
Country Id:
Country Id:
Country Id:
After Sort
Country Id:
Country Id:
Country Id:
Country Id:
:
1||Country name: India
4||Country name: China
3||Country name: Nepal
2||Country name: Bhutan
:
1|| Country name: India
2|| Country name: Bhutan
3|| Country name: Nepal
4|| Country name: China
Comparator Example,
package org.arpit.javapostsforlearning;
public class Country{
int countryId;
String countryName;
public Country(int countryId, String countryName) {
super();
this.countryId = countryId;
this.countryName = countryName;
}
public int getCountryId() {
return countryId;
}
public void setCountryId(int countryId) {
this.countryId = countryId;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
}
Core Java
package org.arpit.javapostsforlearning;
import java.util.Comparator;
//If country1.getCountryId()<country2.getCountryId():then compare method
will return -1
//If country1.getCountryId()>country2.getCountryId():then compare method
will return 1
//If country1.getCountryId()==country2.getCountryId():then compare method
will return 0
public class CountrySortByIdComparator implements Comparator<Country>{
@Override
public int compare(Country country1, Country country2) {
return (country1.getCountryId() < country2.getCountryId() ) ? -1:
(country1.getCountryId() > country2.getCountryId() ) ? 1:0 ;
}
}
package org.arpit.javapostsforlearning;
import
import
import
import
java.util.ArrayList;
java.util.Collections;
java.util.Comparator;
java.util.List;
Core Java
Country country=(Country)
listOfCountries.get(i);
System.out.println('Country Id:
'+country.getCountryId()+'|| '+'Country name:
'+country.getCountryName());
}
//Sort by countryName
Collections.sort(listOfCountries,new
Comparator<Country>() {
@Override
public int compare(Country o1, Country
o2) {
return
o1.getCountryName().compareTo(o2.getCountryName());
}
});
System.out.println('After Sort by name: ');
for (int i = 0; i < listOfCountries.size(); i++) {
Country country=(Country)
listOfCountries.get(i);
System.out.println('Country Id:
'+country.getCountryId()+'|| '+'Country name:
'+country.getCountryName());
}
}
}
Before Sort by id :
Country Id: 1||Country name: India
Country Id: 4||Country name: China
Country Id: 3||Country name: Nepal
Country Id: 2||Country name: Bhutan
After Sort by id:
Country Id: 1|| Country name: India
Country Id: 2|| Country name: Bhutan
Country Id: 3|| Country name: Nepal
Country Id: 4|| Country name: China
After Sort by name:
Country Id: 2|| Country name: Bhutan
Country Id: 4|| Country name: China
Country Id: 1|| Country name: India
Country Id: 3|| Country name: Nepal
Core Java
Map :
A map contains values based on the key i.e. key and value pair.
The Map interface provides three (3) collection views, which allow a
map's contents to be viewed as a set of keys, collection of values, or set of
key-value mappings.
keySet set of keys
values collection of values
entrySet set of key-value mappings
Methods :
1. public Object put(object key,Object value)
2. public void putAll(Map map)
3. public Object remove(object key)
4. public Object get(Object key)
5. public boolean containsKey(Object key)
6. public boolean containsValue(Object value)
7. public Set keySet()
8. public Set entrySet()
Entry :
Methods :
1. public Object getKey()
2. public Object getValue()
Core Java
Why use Map.Entry .?
If you just need keys, use keySet(). If you just need values, use values().
If you're going to use keys and values in your subsequent code, then
you're best off using entrySet().
I frequently see people do this without entrySet(), and it usually looks
something like this:
1.for
2.
3.
4.
5.}
(Iterator
Foo key =
Bar value
// now do
it = map.keySet().iterator(); it.hasNext(); ) {
(Foo) it.next();
= (Bar) map.get(key);
something with key and value
This works, but it's making the JVM do extra work for no good reason. Every time you call
get() you're making the JVM spend time doing a hashcode lookup, or navigating a tree and
evaluating a comparator. These operations may be fast, or not, but why do
them if you don't have to? A Map.Entry gives you both key and value, together, in the
most efficient manner possible.
1.for
2.
3.
4.
5.
6.}
(Iterator
Map.Entry
Foo key =
Bar value
// now do
it = map.entrySet().iterator(); it.hasNext(); ) {
e = (Map.Entry) it.next();
(Foo) e.getKey();
= (Bar) e.getValue();
something with key and value
(Map.Entry<Foo,Bar> e : map.entrySet()) {
Foo key = e.getKey();
Bar value = e.getValue();
// now do something with key and value
Core Java
hashMap.put(2, "First");
hashMap.put(1, "First");
hashMap.put(null, null);
hashMap.put(null, "Second");
hashMap.put(3, null);
for (Integer key : hashMap.keySet()) {
System.out.println( key + " " + hashMap.get(key));
}
}
Output:
null Second
1 First
2 First
3 null
10 null
HashMap :
It maintains no order.
Core Java
}
The HashMap class uses a hashtable to implement the Map interface. This
allows the execution time of basic operations, such as get( ) and put( ),
to remain constant even for large sets.
The HashMap class supports four constructors. The first form constructs a
default hash map:
HashMap( )
The second form initializes the hash map by using the elements of m:
HashMap(Map m)
The third form initializes the capacity of the hash map to capacity:
HashMap(int capacity)
The fourth form initializes both the capacity and fill ratio of the hash
map by using its arguments:
HashMap(int capacity, float fillRatio)
LinkedHashMap :
Core Java
Tree Map :
It cannot have null key but can have multiple null values.
Example,
public static void main(String[] args) {
// Create a TreeMap and populate it with elements
TreeMap treeMap = new TreeMap();
treeMap.put("key_1","element_1");
treeMap.put("key_2","element_2");
treeMap.put("key_3","element_3");
// Get a set of all the entries (key - value pairs) contained in the TreeMap
Collection entrySet = treeMap.entrySet();
// Obtain an Iterator for the entries Set
Iterator it = entrySet.iterator();
// Iterate through TreeMap entries
System.out.println("TreeMap entries : ");
while(it.hasNext())
System.out.println(it.next());
}
TreeMap entries :
key_1=element_1
key_2=element_2
key_3=element_3
Core Java
HashTable :
It is synchronized
Syntax :
public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>,
Cloneable, Serializable
To successfully store and retrieve objects from a hashtable, the objects
used as keys must implement the hashCode method and the equals method.
This example creates a hashtable of numbers. It uses the names of the
numbers as keys:
Hashtable<String, Integer> numbers = new Hashtable<String, Integer>();
numbers.put("one", 1);
numbers.put("two", 2);
numbers.put("three", 3);
To retrieve a number, use the following code:
Integer n = numbers.get("two");
if (n != null) {
System.out.println("two = " + n);
}
HashMap vs HashTable :
HashMap
HashTable
It is not synchronized
It is synchronized
Core Java
HashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap :
There are 4 commonly used implementations of Map in Java SE
1) HashMap,
2) TreeMap,
3) Hashtable and
4) LinkedHashMap.
HashMap :
If key of the HashMap is self-defined objects, then equals() and
hashCode() contract need to be followed.
class TestDog {
String color;
TestDog(String c) {
color = c;
}
public String toString() {
return color + " dog";
Core Java
}
}
public class HashMapDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<TestDogSample, Integer> hashMap = new
HashMap<TestDogSample, Integer>();
TestDogSample d1 = new TestDogSample("red");
TestDogSample d2 = new TestDogSample("black");
TestDogSample d3 = new TestDogSample("white");
TestDogSample d4 = new TestDogSample("white");
hashMap.put(d1,
hashMap.put(d2,
hashMap.put(d3,
hashMap.put(d4,
10);
15);
5); // HashMap accepts duplicates key here
20);
// print size
System.out.println(hashMap.size());
// loop HashMap
for (Entry<TestDogSample, Integer> entry : hashMap.entrySet())
}
Output :
4
white dog
black dog
red dog
white dog
5
15
10
20
Note here, we add white dogs twice by mistake, but the HashMap takes
it. This does not make sense, because now we are confused how many white
dogs are really there.
The Dog class should be defined as follows:
class TestDogSample {
String color;
TestDogSample(String c) {
color = c;
Core Java
}
public String toString() {
return color + " dog";
}
// Override those two methods hashCode() equals() from Object Class
public int hashCode() {
return color.length();
}
public boolean equals(Object obj) {
return this.color == ((TestDogSample)obj).color;
}
}
public class TestHashMap {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<TestDogSample, Integer> hashMap = new
HashMap<TestDogSample, Integer>();
TestDogSample d1 = new TestDogSample("red");
TestDogSample d2 = new TestDogSample("black");
TestDogSample d3 = new TestDogSample("white");
TestDogSample d4 = new TestDogSample("white");
hashMap.put(d1,
hashMap.put(d2,
hashMap.put(d3,
duplicates key here
hashMap.put(d4,
10);
15);
5);
20);
// print size
System.out.println(hashMap.size());
// loop HashMap
for (Entry<TestDogSample, Integer> entry : hashMap.entrySet())
{
}
}
}
Now the output is:
3
red dog 10
Core Java
white dog 20
black dog 15
The reason is that HashMap doesnt allow two identical elements. By
default, the hashCode() and equals() methods implemented in Object class are
used. The default hashCode() method gives distinct integers for distinct objects,
and the equals() method only returns true when two references refer to the same
object
HashMap vs TreeMap :
HashMap
TreeMap
hashCode(), equals()
compareTo() implementation,
searching, unsorted
Does not support duplicate key
Unordered map
Core Java
What is fail-fast?
The concept of fail-fast comes with iterators. When an Iterator object is
created and iteration is going on, the HashMap elements cannot be
modified (like addition or deletion of elements cannot be done). This is
explained programmatically in ConcurrentModificationException.
Comparing two strings letter by letter in a for loop is a time taking process.
To make faster, the JVM converts each string into an integer number called hashcode.
Usage of hashcode numbers for comparison, searching of duplicate elements and identification is
faster.
Hashing
Hashing, in data structures, is done implicitly in the basic operations with add(), contains(),
remove() and size() etc.
HashMap vs HashSet:
Parameter
Interface
Duplicates
Performance
HashMap
This is core difference
among them. HashMap
implements Map
interface
It stores data in a
form of key->value
pair. So it uses
put(key,value) method
for storing data
HashMap allows
duplicate value but not
duplicate keys
It is faster than
HashSet
HashSet implement Set
interface
It uses add(value) method
for storing data
Core Java
HashCode Calculation
Value Inertion
null
Similarities :
1) Both HashMap and HashSet are hash based collection in Java.
2) Both HashMap and HashSet are not synchronized and can not be shared
between multiple threads.
3) Iterator returned by HashMap's keySet() and HashSet are fail-fast and
they throwConcurrentModificationException if they detect any structural change in
Collection.
4) Both HashMap and HashSet provided constant time performance for basic
operations like put(), get() etc.
5) Both HashSet and HashMap allows null values.
hashCode() vs equals() .?
The contract between hashCode and equals method,
if two objects are equal, that is obj1.equals(obj2) is true then, obj1.hashCode() and
obj2.hashCode() must return same integer.
Why do we need to override equals() and hashcode() .?
1) If 2 objects are same then they must return same value in hashcode()
and equals() method whenever invoked.
2) It is not necessary that 2 different objects must have different
hashcode values. It might be possible that they share common hash buckets
for example,
object1 amy
object2 may
both has different hashcode but may possible to share same hash buckets
Core Java
obj2
obj1
3) JVM assigns unique hashcode values to each object when they are
created in memory and if developers dont override the hashcode method
then there is no way the 2 objects returns same hashcode values
Example,
class employeetest {
private String name;
private int id;
public employeetest(String empname, Integer empid) {
this.name = empname;
this.id = empid;
}
public String toString() {
return name + " " + id;
}
/*public int hashCode() {
return this.name.length();
}*/
public boolean equals(Object obj) {
return this.name == ((employeetest)obj).name;
}
}
public class HashSetDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<employeetest> set = new HashSet<employeetest>();
set.add(new employeetest("Praveen", 12));
set.add(new employeetest("Praveen", 12));
for (employeetest empObj : set) {
System.out.println(empObj.toString());
Core Java
}
}
}
output :
Praveen 12
Praveen 12
Note: The same code has equals() method as commented and hashcode()
method as uncommented will get the same result like above
If both methods overrides here you will get the exact output and
duplicates are not allowed in collection here
class employeetest {
private String name;
private int id;
public employeetest(String empname, Integer empid) {
this.name = empname;
this.id = empid;
}
public String toString() {
return name + " " + id;
}
public int hashCode() {
return this.name.length();
}
Core Java
output :
Praveen 12
HashTable, HashMap and HashSet are the Collection classes in java.util
package that make use of hashing algorithm to store objects.
In all these Collection classes except HashSet, objects are stored as
key-value pairs.
For the storage and the retrieval of any user-defined objects it is a
good practice to override the following methods which is mentioned below,
hashCode()
equals()
These methods are available in the Object class and hence available to
all java classes. Using these two methods, an object can be stored or
retrieved from a Hashtable, HashMap or HashSet.
hashCode() method
equals() method
Core Java
Design Patterns :
Design patterns are programming language independent strategies for solving the
common object-oriented design problems.
By using the design patterns you can make your code more flexible,
reusable and maintainable.
They are well-proved and testified solutions since they have been
built upon the knowledge and experience of expert software
developers.
Core Java
Types of design patterns :
Basically, design patterns are categorized into two parts:
1) Core java (or JavaSE) Design Patterns.
Factory Pattern
Adapter Pattern
Chain Of Responsibility
Pattern
Abstract Factory
Pattern
Bridge Pattern
Command Pattern
Singleton Pattern
Composite Pattern
Interpreter Pattern
Prototype Pattern
Decorator Pattern
Iterator Pattern
Builder Pattern.
Facade Pattern
Mediator Pattern
Flyweight Pattern
Memento Pattern
Proxy Pattern
Observer Pattern
State Pattern
Strategy Pattern
Template Pattern
Visitor Pattern
Core Java
Creational design patterns :
These design patterns are used when a decision must be made at the
time of instantiation of a class (i.e. creating an object of a
class).
Core Java
UML for Factory Method Pattern :
We are going to create a Plan abstract class and concrete classes that
extends the Plan abstract class. A factory class GetPlanFactory is
defined as a next step.
GenerateBill class will use GetPlanFactory to get a Plan object. It will
pass information (DOMESTICPLAN / COMMERCIALPLAN / INSTITUTIONALPLAN) to
GetPalnFactory to get the type of object it needs.
Example Code ,
abstract class Plan{
protected double rate;
abstract void getRate();
public void calculateBill(int units){
System.out.println(units*rate);
}
}//end of Plan class
class
Core Java
public void getRate(){
rate=3.50;
}
}//end of DomesticPlan class.
class
Core Java
return null;
}
}//end of GetPlanFactory class.
Implementation Class :
class GenerateBill{
public static void main(String args[])throws IOException{
GetPlanFactory planFactory = new GetPlanFactory();
System.out.print("Enter the name of plan for which the bill will be
generated: ");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String planName=br.readLine();
System.out.print("Enter the number of units for bill will be
calculated: ");
int units=Integer.parseInt(br.readLine());
Plan p = planFactory.getPlan(planName);
//call getRate() method and calculateBill()method of DomesticPaln.
System.out.print("Bill amount for "+planName+" of
"+units+" units
is: ");
p.getRate();
p.calculateBill(units);
}
}//end of GenerateBill class.
Singleton Pattern says that just "define a class that has only one instance
and provides a global point of access to it".
Core Java
Saves memory because object is not created at each request. Only single
instance is reused again and again.
Private Static member: It gets memory only once because of static, it contains the
instance of the Singleton class.
Private constructor: It will prevent to instantiate the Singleton class from outside
the class.
Public Static factory method: This provides the global point of access
to the Singleton object and returns the instance to the caller.
Core Java
private A(){}
public static A getA(){
return obj;
}
public void doSomething(){
//write your code
}
}
Core Java
request time
}
}
}
return obj;
}
public void doSomething(){
//write your code
}
}
If singleton class is Serializable, you can serialize the singleton instance. Once it is
serialized, you can deserialize it but it will not return the singleton object.
Core Java
JDBCSingleton();
}
return jdbc;
}
// to get the connection from methods like insert, view etc.
private static Connection getConnection()throws
ClassNotFoundException, SQLException
{
Connection con=null;
Class.forName("com.mysql.jdbc.Driver");
con=
DriverManager.getConnection("jdbc:mysql://localhost:3306/ashwanirajput",
"root", "ashwani");
return con;
}
Core Java
//to insert the record into the database
public int insert(String name, String pass) throws SQLException
{
Connection c=null;
PreparedStatement ps=null;
int recordCounter=0;
try {
c=this.getConnection();
ps=c.prepareStatement("insert into
userdata(uname,upassword)values(?,?)");
ps.setString(1, name);
ps.setString(2, pass);
recordCounter=ps.executeUpdate();
} catch (Exception e) { e.printStackTrace(); } finally{
if (ps!=null){
ps.close();
}if(c!=null){
c.close();
}
}
return recordCounter;
}
//to view the data from the database
public
{
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Core Java
con=this.getConnection();
ps=con.prepareStatement("select * from userdata
where uname=?");
ps.setString(1, name);
rs=ps.executeQuery();
while (rs.next()) {
System.out.println("Name=
"+rs.getString(2)+"\t"+"Paasword= "+rs.getString(3));
}
} catch (Exception e) { System.out.println(e);}
finally{
if(rs!=null){
rs.close();
}if (ps!=null){
ps.close();
}if(con!=null){
con.close();
}
}
}
// to update the password for the given username
public int update(String name, String password) throws SQLException
{
Connection c=null;
PreparedStatement ps=null;
int recordCounter=0;
try {
c=this.getConnection();
ps=c.prepareStatement(" update userdata set
upassword=? where uname='"+name+"' ");
ps.setString(1, password);
recordCounter=ps.executeUpdate();
} catch (Exception e) {
if (ps!=null){
e.printStackTrace(); } finally{
Core Java
ps.close();
}if(c!=null){
c.close();
}
}
return recordCounter;
}
// to delete the data from the database
public int delete(int userid) throws SQLException{
Connection c=null;
PreparedStatement ps=null;
int recordCounter=0;
try {
c=this.getConnection();
uid='"+userid+"' ");
choice;
Core Java
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
do{
System.out.println("DATABASE OPERATIONS");
System.out.println(" --------------------- ");
System.out.println(" 1. Insertion ");
System.out.println(" 2. View
");
System.out.println(" 3. Delete
");
System.out.println(" 4. Update
");
System.out.println(" 5. Exit
");
System.out.print("\n");
System.out.print("Please enter the choice what you want to
perform in the database: ");
choice=Integer.parseInt(br.readLine());
switch(choice) {
case 1:{
System.out.print("Enter the username you want to
insert data into the database: ");
String username=br.readLine();
System.out.print("Enter the password you want to
insert data into the database: ");
String password=br.readLine();
try {
int i= jdbc.insert(username, password);
if (i>0) {
System.out.println((count++) + " Data has
been inserted successfully");
}else{
System.out.println("Data has not been
inserted ");
}
} catch (Exception e) {
System.out.println(e);
}
Core Java
System.out.println("Press Enter key to
continue...");
System.in.read();
}//End of case 1
break;
case 2:{
System.out.print("Enter the username : ");
String username=br.readLine();
try
{
jdbc.view(username);
} catch (Exception e) {
System.out.println(e);
}
you want to
int userid=Integer.parseInt(br.readLine());
try {
int i= jdbc.delete(userid);
if (i>0) {
System.out.println((count++) + " Data has
been deleted successfully");
}else{
System.out.println("Data has not been
deleted");
}
} catch (Exception e) {
System.out.println(e);
Core Java
}
System.out.println("Press Enter key to
continue...");
System.in.read();
}//End of case 3
break;
case 4:{
System.out.print("Enter the username,
you want to
update: ");
String username=br.readLine();
System.out.print("Enter the new password ");
String password=br.readLine();
try {
int i= jdbc.update(username, password);
if (i>0) {
been updated successfully");
} catch (Exception e) {
System.out.println(e);
}
System.out.println("Press Enter key to
continue...");
System.in.read();
}// end of case 4
break;
default:
return;
}
} while (choice!=4);
}
}
Core Java
Lazy initialization :
This method uses double-checked locking and it uses synchronized block
here.
public class SingletonDemo {
private static volatile SingletonDemo instance = null;
private SingletonDemo() {
Core Java
}
}
This method has a number of advantages:
private Singleton() {
// ...
}
Eager initialization
Lazy initialization
Static block initialization
Bill pugh solution
Using Enum
Adding readResolve()
Adding serial version id
Conclusion
Core Java
Eager initialization
This is a design pattern where an instance of a class is created much
before it is actually required. Mostly it is done on system start up. In
singleton pattern, it refers to create the singleton instance
irrespective of whether any other class actually asked for its instance
or not.
public class EagerSingleton {
private static volatile EagerSingleton instance = new
EagerSingleton();
// private constructor
private EagerSingleton() {
}
public static EagerSingleton getInstance() {
return instance;
}
}
Above method works fine, but has one drawback. Instance is created
irrespective of it is required in runtime or not. If this instance is not
big object and you can live with it being unused, this is best approach.
Lets solve above problem in next method.
Lazy initialization
In computer programming, lazy initialization is the tactic of delaying the
creation of an object, the calculation of a value, or some other
expensive process until the first time it is needed. In singleton pattern, it
restricts the creation of instance until requested first time. Lets see in code:
public final class LazySingleton {
private static volatile LazySingleton instance = null;
// private constructor
private LazySingleton() {
}
Core Java
On first invocation, above method will check if instance is already
created using instance variable. If there is no instance i.e. instance is
null, it will create an instance and will return its reference. If
instance is already created, it will simply return the reference of
instance.
But, this method also has its own drawbacks. Lets see how. Suppose there
are two threads T1 and T2. Both comes to create instance and execute
instance==null, now both threads have identified instance variable to
null thus assume they must create an instance. They sequentially goes to
synchronized block and create the instances. At the end, we have two
instances in our application.
This error can be solved using double-checked locking. This principle tells us
to recheck the instance variable again in synchronized block in given
below way:
public class EagerSingleton {
private static volatile EagerSingleton instance = null;
// private constructor
private EagerSingleton() {
}
Core Java
volatile solves one issue that is visibility issue . If you are writing to one variable that is
declared volatile then the value will be visible to other thread immediately. As we all
know we have different level of cache in os L1, L2, L3 and if we write to
a variable in one thread it is not guaranteed to be visible to other, so
if we use volatile it writes to direct memory and is visible to others.
But volatile does not solve the issue of atomicity i.e. int a; a++; is
not safe. AS there are three machine instructions associated to it.
Static block initialization
If you have little idea about class loading sequence, you can connect to
the fact that static blocks are executed during the loading of class and
even before the constructor is called. We can use this feature in our
singleton pattern also like this:
public class StaticBlockSingleton {
private static final StaticBlockSingleton INSTANCE;
static {
try {
Core Java
public class BillPughSingleton {
private BillPughSingleton() {
}
private static class LazyHolder {
private static final BillPughSingleton INSTANCE = new
BillPughSingleton();
}
As you can see, until we need an instance, the LazyHolder class will not
be initialized until required and you can still use other static members
of BillPughSingleton class. This is the solution, i will recommend to
use. I also use it in my all projects.
Using Enum
This type of implementation recommend the use of enum. Enum, as written
in java docs, provide implicit support for thread safety and only one
instance is guaranteed. This is also a good way to have singleton with
minimum effort.
public enum EnumSingleton {
INSTANCE;
public void someMethod(String param) {
// some class member
}
}
Adding readResolve()
So, till now you must have taken your decision that how you would like to
implement your singleton. Now lets see other problems that may arise even
in interviews also.
Lets say your application is distributed and it frequently serialize the
objects in file system, only to read them later when required. Please
note that, de-serialization always creates a new instance. Lets understand using an
example:
Our singleton class is:
public class DemoSingleton implements Serializable {
private volatile static DemoSingleton instance = null;
public static DemoSingleton getInstance() {
Core Java
if (instance == null) {
instance = new DemoSingleton();
}
return instance;
Lets serialize this class and de-serialize it after making some changes:
public class SerializationTest {
static DemoSingleton instanceOne = DemoSingleton.getInstance();
public static void main(String[] args) {
try {
// Serialize to a file
ObjectOutput out = new ObjectOutputStream(new
FileOutputStream(
"filename.ser"));
out.writeObject(instanceOne);
out.close();
instanceOne.setI(20);
// Serialize to a file
ObjectInput in = new ObjectInputStream(new
FileInputStream(
in.readObject();
"filename.ser"));
DemoSingleton instanceTwo = (DemoSingleton)
in.close();
System.out.println(instanceOne.getI());
System.out.println(instanceTwo.getI());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Output:
20
Core Java
10
Unfortunately, both variables have different value of variable i.
Clearly, there are two instances of our class. So, again we are in same
problem of multiple instances in application.
To solve this issue, we need to include readResolve() method in our
DemoSingleton class. This method will be invoked when you will
de-serialize the object. Inside this method, you must return the existing
instance to ensure single instance application wide.
public class DemoSingleton implements Serializable {
private volatile static DemoSingleton instance = null;
public static DemoSingleton getInstance() {
if (instance == null) {
instance = new DemoSingleton();
}
return instance;
}
protected Object readResolve() {
return instance;
}
private int i = 10;
public int getI() {
return i;
}
Now when you execute the class SerializationTest, it will give you
correct output.
20
20
Adding serial version id
So far so good. Till now, we have solved the problem of synchronization
and serialization both. Now, we are just one step behind our correct and
complete implementation. And missing part is serial version id.
This is required in condition when you class structure can change in
between you serialize the instance and go again to de-serialize it.
Changed structure of class will cause JVM to give exception while
de-serializing process.
Core Java
java.io.InvalidClassException: singleton.DemoSingleton; local class
incompatible: stream classdesc serialVersionUID = 5026910492258526905,
local class serialVersionUID = 3597984220566440782
at java.io.ObjectStreamClass.initNonProxy(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at singleton.SerializationTest.main(SerializationTest.java:24)
Core Java
Prototype Design Pattern :
The clients can get new objects without knowing which type of
object it will be.
Core Java
}
class PrototypeDemo implements Prototype {
public Integer empId;
public String empName;
public PrototypeDemo() {
// TODO Auto-generated constructor stub
}
public PrototypeDemo(Integer id, String name) {
this.empId = id;
this.empName = name;
}
public String showInfo() {
return empId + " " + empName;
}
@Override
public PrototypeDemo getCloneObj() {
// TODO Auto-generated method stub
return new PrototypeDemo(empId, empName);
}
}
Implementation Class,
public class PrototypeTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
PrototypeDemo prototype = new PrototypeDemo(12, "Praveen");
System.out.println(prototype.showInfo());
}
}
Output :
12 Praveen
12 Praveen
Core Java
Marker Interface (Tag Interface) :
Marker Interface
In java language programming, interfaces with no methods are known as
marker interfaces. Marker interfaces are Serializable, Clonable,
SingleThreadModel, Event listener. Marker Interfaces are implemented by
the classes or their super classes in order to add some functionality.
Example 1,
Suppose you want to persist (save) the state of an object then you have
to implement the Serializable interface otherwise the compiler will throw
an error. To make more clearly understand the concept of marker interface
you should go through one more example.
Example 2,
Suppose the interface Clonable is neither implemented by a class named
Myclass nor it's any super class, then a call to the method clone() on
Myclass's object will give an error. This means, to add this
functionality one should implement the Clonable interface. While the
Clonable is an empty interface but it provides an important
functionality.
Core Java
How to create our own Marker Interface :
Interfaces with no field or methods, in simple word we can say empty
interface, is called Marker or Tag Interface. Marker interface is used as
a tag to pass a message to java compiler so that it can add special
behavior to the class that implementing it. Clonable and Serializable are
example of Marker Interface. Now lets come to our main topic, how can I
create our own marker interface.
Cheque.java
public interface Cheque {
}
BankDraft.java
public interface BankDraft {
}
Payment.java
public class Payment implements BankDraft{
public void paymentByCheque() {
System.out.println("Payment By Cheque");
}
MainClass.java
public class MainClass {
public static void main(String[] args) {
Payment p = new Payment();
if (p instanceof Cheque) {
p.paymentByCheque();
}
if (p instanceof BankDraft) {
p.paymentByBankDraft ();
}
}
Output
Payment by Draft
Core Java
Description
In above example, we have created two empty interfaces Cheque and
BankDraft. And Payment class implemented BankDraft interface. In
MainClass class both interface behave as tag, output of MainClass depends
on what interface you have implemented in Payment class.
In above case,
public class Payment implements BankDraft
Thats why output is
Payment by Draft
If you have change as follows
public class Payment implements Cheque
Then new output will be
Payment by Cheque
Java - Serialization
Core Java
Advantages
Core Java
Serializing an Object:
The ObjectOutputStream class is used to serialize an Object.
following SerializeDemo program instantiates an Employee object
serializes it to a file.
The
and
Deserializing an Object:
The following DeserializeDemo program deserializes the Employee object
created in the SerializeDemo program. Study the program and try to
determine its output:
Core Java
public class DeserializeDemo
{
public static void main(String [] args)
{
Employee e = null;
try
{
FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}
This would produce the following result:
Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101
Here are following important points to be noted:
The value of the SSN field was 11122333 when the object was
serialized, but because the field is transient, this value was not
sent to the output stream. The SSN field of the deserialized
Employee object is 0.
Core Java
Why would we want to do this? (Serialization)
There are several reasons:
1) Communication:
If you have two machines that are running the same code, and they
need to communicate, an easy way is for one machine to build an
object with information that it would like to transmit, and then
serialize that object to the other machine. It's not the best
method for communication, but it gets the job done.
2) Persistence:
3) Deep Copy:
4) Caching:
If a class implements Serializable then all its subclasses will also be Serializable
Externalizable interface :
Core Java
Methods :
public void writeExternal(ObjectOutput out) throws IOException
public void readExternal(ObjectInput in) throws IOException
Example,
class Employee implements Serializable{
int id;
String name;
static String companyName="IBM";//it won't be serialized
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
Rule: In case of array or collection, all the objects of array or
collection must be serializable, if any object is not serialiizable then
serialization will be failed.
Externalizable
Core Java
process to application.
It is a Marker Interface which is
placed in java.io package
Example,
class EmployeeTest implements Externalizable {
public Integer id;
public String name;
public EmployeeTest() {
// TODO Auto-generated constructor stub
}
public EmployeeTest(Integer empid, String empname) {
this.id = empid;
this.name = empname;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(id);
out.writeObject(name);
}
@Override
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
id = in.readInt();
name = (String) in.readObject();
}
Core Java
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Exception Handling :
It provides the mechanism to handle the runtime errors so that normal flow
of the application can be maintained.
Example,
statement 1;
statement 2;
statement 3;
statement 4;
Core Java
statement 5;
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there is 10 statements in your program and there occurs an
exception at statement 5, rest of the code will not be executed i.e.
statement 6 to 10 will not run.
If we perform exception handling, rest of the exception will be executed.
That is why we use exception handling.
Hierarchy of Exception :
All exception classes are subtypes of the java.lang.Exception class. The
exception class is a subclass of the Throwable class. Other than the
exception class there is another subclass called Error which is derived
from the Throwable class.
Types of Exception :
There are mainly two types of exceptions: checked and unchecked where
error is considered as unchecked exception.
The sun microsystem says there are three types of exceptions:
Core Java
1. Checked Exception
2. Unchecked Exception
3. Error
What is the difference between checked and unchecked exceptions ?
1)Checked Exception
2)Unchecked Exception
3)Error
These are not exceptions at all, but problems that arise beyond the control
of the user or the programmer.
Errors are typically ignored in your code because you can rarely do
anything about an error.
For example, if a stack overflow occurs, an error will arise.
They are also ignored at the time of compilation.
Core Java
Stack Overflow in Java
The local automatic variable is created on this stack and method arguments are passed.
When a process starts, it get a default stack size which is fixed for each process.
Under abnormal condition, the stack limit exceeds. This is known as stack overflow.
The two most common reason for stack overflow are given below :
infinite recursion
1. Infinite Recursion
The most common reason of stack overflow is Infinite Recursion. The infinite loop of recursion going on due
to which stack's limit exceeds.
For example, take a look at given below code:
int f(){
g();
}
int g() {
f();
}
f() is calling g() and g() is calling f(). Due to this loop goes on infinitely. This cause stack overflow.
Core Java
System.out.println("Caught "+t);
t.printStackTrace();
}
System.out.println("After the error...");
}
}
Catching Exceptions:
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}
A catch statement involves declaring the type of exception you are trying
to catch. If an exception occurs in protected code, the catch block (or
blocks) that follows the try is checked. If the type of exception that
occurred is listed in a catch block, the exception is passed to the catch
block much as an argument is passed into a method parameter.
Multiple catch Blocks:
A try block can be followed by multiple catch blocks. The syntax for
multiple catch blocks looks like the following:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}
Core Java
The previous statements demonstrate three catch blocks, but you can have
any number of them after a single try. If an exception occurs in the
protected code, the exception is thrown to the first catch block in the
list. If the data type of the exception thrown matches ExceptionType1, it
gets caught there. If not, the exception passes down to the second catch
statement. This continues until the exception either is caught or falls
through all catches, in which case the current method stops execution and
the exception is thrown down to the previous method on the call stack.
The throws/throw Keywords:
always
executes,
whether
or
not
an
Core Java
finally block can be used to put "cleanup" code such as closing a file,
closing connection etc.
Rule: For each try block there can be zero or more catch blocks, but only one
finally block.
Note: The finally block will not be executed if program exits(either by
calling System.exit() or by causing a fatal error that causes the process
to abort).
A finally block appears at the end of the catch blocks and has the
following syntax:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}
Note:
Core Java
Example,
public class ExceptionTest {
public static void main(String[] args) {
try {
try {
int a = 12 / 0;
} catch (ArithmeticException ex) {
System.out.println("ArithmeticException");
}
try {
int a[] = new int[4];
a[5] = 10;
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("ArrayIndexOutOfBoundsException"
);
}
String str = null;
int length = str.length();
} catch (NullPointerException ex) {
System.out.println("NullPointerException");
} catch (ArrayStoreException ex) {
System.out.println("ArrayStoreException");
} catch (Exception ex) {
Core Java
System.out.println("Root Exception");
}
}
output :
ArithmeticException
ArrayIndexOutOfBoundsException
NullPointerException
Example,
public class NestedTryTest {
public static void main(String[] args) {
try {
try {
int a = 12 / 0;
int r[] = new int[4];
r[5] = 10;
} catch (ArithmeticException ex) {
System.out.println("ArithmeticException");
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("ArrayIndexOutOfBoundsException"
);
}
String str = null;
int length = str.length();
} catch (NullPointerException ex) {
System.out.println("NullPointerException");
} catch (ArrayStoreException ex) {
System.out.println("ArrayStoreException");
} catch (Exception ex) {
System.out.println("Root Exception");
}
}
}
Output :
ArithmeticException
NullPointerException
Example,
public class ExceptionTest {
public static void main(String[] args) {
try {
Core Java
try {
int a = 12 / 0;
} catch (ArithmeticException ex) {
System.out.println("ArithmeticException");
}
try {
Example,
public class ExceptionTest {
public static void main(String[] args) {
try {
try {
int a = 12 / 0;
} catch (ArithmeticException ex) {
System.out.println("ArithmeticException");
}
try {
int a[] = new int[4];
a[5] = 10; // exception handle at outside catch
} catch (ArithmeticException ex) {
System.out.println("ArrayIndexOutOfBoundsException");
}
String str = null;
int length = str.length();
} catch (NullPointerException ex) {
System.out.println("NullPointerException");
} catch (ArrayStoreException ex) {
System.out.println("ArrayStoreException");
}catch(ArrayIndexOutOfBoundsException ex) {
System.out.println("ArrayIndexOutOfBoundsException");
}catch (Exception ex) { // base class
System.out.println("Root Exception");
Core Java
}
Throw
Throws
You cannot throw multiple exception You can declare multiple exception
e.g. public void method()throws
IOException,SQLException.
throw is used within the method.
Example,
1) If the superclass method does not declare an exception
Rule 1: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception.
class Parent{
void msg(){System.out.println("parent");}
}
class Child extends Parent{
void msg()throws IOException{
Core Java
System.out.println("child");
}
public static void main(String args[]){
Parent p=new Child();
p.msg();
}
}
output : Compile Time Error
Rule 2: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but can declare unchecked exception.
class Parent{
void msg(){System.out.println("parent");}
}
class Child extends Parent{
void msg()throws ArithmeticException{
System.out.println("child");
}
public static void main(String args[]){
Parent p=new Child();
p.msg();
}
}
output :child
2) If the superclass method declares an exception
Rule 1: If the superclass method declares an exception, subclass overridden method can
declare same, subclass exception or no exception but cannot declare parent exception.
class Parent{
void msg()throws ArithmeticException{System.out.println("parent");}
}
class Child extends Parent{
void msg()throws Exception{System.out.println("child");}
public static void main(String args[]){
Parent p=new Child();
Core Java
try{
p.msg();
}catch(Exception e){}
}
}
output : Compile Time Error
Rule 2: Example in case subclass overridden method declares same exception
class Parent{
void msg()throws Exception{System.out.println("parent");}
}
class Child extends Parent{
void msg()throws Exception{System.out.println("child");}
public static void main(String args[]){
Parent p=new Child();
try{
p.msg();
}catch(Exception e){}
}
}
output : child
Rule 3: Example in case subclass overridden method declares subclass exception
class Parent{
void msg()throws Exception{System.out.println("parent");}
}
class Child extends Parent{
void msg()throws ArithmeticException{System.out.println("child");}
public static void main(String args[]){
Parent p=new Child();
try{
p.msg();
Core Java
}catch(Exception e){}
}
}
output : child
Rule 4: Example in case subclass overridden method declares no exception
class Parent{
void msg()throws Exception{System.out.println("parent");}
}
class Child extends Parent{
void msg(){System.out.println("child");}
public static void main(String args[]){
Parent p=new Child();
try{
p.msg();
}catch(Exception e){}
}
}
output : child
Core Java
Synchronization :
Synchronization is better in case we want only one thread can access the
shared resource at a time.
Types of Synchronization
1. Process Synchronization
2. Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and
inter-thread communication.
Mutual Exclusive
Synchronized method.
Synchronized block.
static synchronization.
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another
while sharing data. This can be done by three ways in java:
by synchronized method
by synchronized block
by static synchronization
Core Java
Understanding the problem without Synchronization
In this example, there is no synchronization, so output is inconsistent.
Example,
Class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{ User-defined Thread Class
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{ User-defined Thread Class
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class Use{
public static void main(String args[]){
Core Java
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
First Thread
Second Thread
t1.start();
t2.start();
}
}
Output :5
In-Consistent Output
100
10
200
15
300
20
400
25
500
Example,
Class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
Core Java
class MyThread1 extends Thread{ User-defined Thread Class
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{ User-defined Thread Class
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class Use{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj); First Thread
MyThread2 t2=new MyThread2(obj); Second Thread
t1.start();
t2.start();
}
}
Output:5
10
15
20
25
100
200
300
400
Consistent Output
Core Java
500
Same Example of synchronized method by using annonymous class
In this program, we have created the two threads by annonymous class, so
less coding is required.
Example,
Class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class Use{
public static void main(String args[]){
final Table obj = new Table();
Core Java
20
25
100
200
300
400
500
Synchronized block
Suppose you have 50 lines of code in your method, but you want to
synchronize only 5 lines, you can use synchronized block.
If you put all the codes of the method in the synchronized block,
it will work same as the synchronized method.
Syntax
synchronized (object reference expression) {
//code block
}
Example,
Class Table{
void printTable(int n){//synchronized method
synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
Core Java
}
class Use{
public static void main(String args[]){
final Table obj = new Table();
Static synchronization
If you make any static method as synchronized, the lock will be on the class not
on object.
Core Java
Example,
class Table{
synchronized static void printTable(int n){
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
}
}
}
public class Test {
public static void main(String[] args) {
Thread t1=new Thread(){
public void run(){
Table.printTable(1);
}
};
Thread t2=new Thread(){
public void run(){
Table.printTable(10);
}
};
Core Java
Thread t3=new Thread(){
public void run(){
Table.printTable(100);
}
};
Thread t4=new Thread(){
public void run(){
Table.printTable(1000);
}
};
t1.start();
t2.start();
t3.start();
t4.start();
}
}
DeadLock
Deadlock can occur in a situation when a thread is waiting for an object
lock, that is acquired by another thread and second thread is waiting for
an object lock that is acquired by first thread. Since, both threads are
waiting for each other to release the lock, the condition is called
deadlock.
Example,
public class DeadlockExample {
public static void main(String[] args) {
final String resource1 = "ratan jaiswal";
final String resource2 = "vimal jaiswal";
// t1 tries to lock resource1 then resource2
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
Core Java
System.out.println("Thread 1: locked resource 1");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};
// t2 tries to lock resource2 then resource1
Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
}
};
t1.start();
t2.start();
}
}
output :Thread 1: locked resource 1
Thread 2: locked resource 2
Core Java
It is implemented by following methods of Object class
wait()
notify()
notifyAll()
wait()
Causes current thread to release the lock and wait until either another thread
invokes the notify() or notifyAll() for this object, or a specified amount of time has
elapsed.
notify()
notifyAll()
Access modifiers specifies who can access them. There are four
access modifiers used in java.
The two levels are class level access modifiers and member level
access modifiers.
Core Java
If a class is public, then it CAN be accessed from ANYWHERE.
If a class has no modifer, then it CAN ONLY be accessed from
same package.
II) Member level access modifiers (java variables and java methods)
All the four public, private, protected and no modifer is allowed.
public and no modifier the same way as used in class level.
private members CAN ONLY access.
protected CAN be accessed from same package and a subclass
existing in any package can access.
For better understanding, member level access is formulated as a table:
Access Modifiers
public
protected
no access modifier
private
Same Class
Y
Y
Y
Y
Same Package
Y
Y
Y
N
Y
Y
N
N
Y
N
N
N
Core Java
FlightLog(SpecificFlight flight) // default access modifier
{
this.flight = flight;
}
}
When you do not write any constructor in your class then compiler generates
a default constructor with the same access modifier of the class.
For following example compiler will generate a default constructor with
public access modifier(same as class).
package flight.booking;
public class FlightLog // public access modifier
{
private SpecificFlight flight;
}
OOPS
Object-Oriented Programming (OOP) is a programming paradigm using "objects" to design
applications.
A Java class uses variables to define data fields and methods to define
actions.
Core Java
Encapsulation
Encapsulation means putting together all the variables (instance variables) and the
methods into a single unit called Class.
Core Java
Example,
private String name;
public String getName() {
return name;
}
public void setName(String name){
this.name=name;
}
Core Java
}
// We can add other method to get access to other properties
}
Inheritance
In general one line definition we can tell that deriving a new class
from an existing class, its called as Inheritance.
Java supports multiple inheritance (multiple parents, single child) only through
interfaces.
Only properties with access modifier public and protected can be accessed in child
class.
Example,
public class Android extends Mobile{
//Constructor to set properties/characteristics of object
Android(String man, String o,String m, int c){
super(man, o, m, c);
}
//Method to get access Model property of Object
public String getModel(){
return "This is Android Mobile- " + model;
}
}
public class Blackberry extends Mobile{
//Constructor to set properties/characteristics of object
Blackberry(String man, String o,String m, int c){
super(man, o, m, c);
}
public String getModel(){
return "This is Blackberry-"+ model;
Core Java
}
}
Polymorphism
Same method signature and same number of parameters but of different type
Example,
Example of Overloading
int add(int a,int b)
float add(float a,int b)
float add(int a ,float b)
void add(float a)
int add(int a)
void add(int a)
class Overloadsample {
public void print(String s){
System.out.println("First Method with only String- "+ s);
}
public void print (int i){
System.out.println("Second Method with only int- "+ i);
}
public void print (String s, int i){
System.out.println("Third Method with both- "+ s + "--" + i);
Core Java
}
}
public class PolymDemo {
public static void main(String[] args) {
Overloadsample obj = new Overloadsample();
obj.print(10);
obj.print("Amit");
obj.print("Hello", 100);
}
}
Example: Overloading
Class BookDetails{
String title;
String publisher;
float price;
setBook(String title){
}
setBook(String title, String publisher){
}
setBook(String title, String publisher,float price){
}
}
Example: Overriding
class BookDetails{
String title;
setBook(String title){ }
}
class ScienceBook extends BookDetails{
setBook(String title){}
//overriding
setBook(String title, String publisher,float price){ } //overloading
}
Core Java
//Creating Object of Sublcass and calling getModel Method
Blackberry b = new Blackberry("BlackB", "RIM", "Curve",20000);
System.out.println(b.getModel());
}
}
Abstraction
Car Example,
When you drive your car you do not have to be concerned with the
exact internal working of your car(unless you are a mechanic).
What you are concerned with is interacting with your car via its
interfaces like steering wheel, brake pedal, accelerator pedal etc.
Manage Abstraction
From the outside, the car is a single object. Once inside, you see
that the car consists of several subsystems: steering, brakes,
sound system, seat belts, heating, cellular phone, and so on.
The point is that you manage the complexity of the car (or any other complex
Core Java
system)through the use of hierarchical abstractions.
Abstract Class ( Incomplete Class)
By the way Java has concept of abstract classes, abstract method but a
variable can not be abstract in Java.
Vehicle Example,
Lets take an example of Java Abstract Class called Vehicle. When I am
creating a class called Vehicle, I know there should be methods like
Start() and Stop() but don't know start and stop mechanism of every vehicle
since they could have different start and stop mechanism e.g some can be
started by kick or some can be by pressing buttons.
Advantage of Abstraction is if there is new type of vehicle introduced we
might just need to add one class which extends Vehicle Abstract class and
implement specific methods. Interface of start and stop method would be
same.
Example,
public abstract class VehicleAbstract {
public abstract void start();
public void stop(){
System.out.println("Stopping Vehicle in abstract class");
}
}
class TwoWheeler extends VehicleAbstract{
Core Java
@Override
public void start() {
System.out.println("Starting Two Wheeler");
}
}
class FourWheeler extends VehicleAbstract{
@Override
public void start() {
System.out.println("Starting Four Wheeler");
}
}
public class VehicleTesting {
public static void main(String[] args) {
VehicleAbstract my2Wheeler = new TwoWheeler();
VehicleAbstract my4Wheeler = new FourWheeler();
my2Wheeler.start();
my2Wheeler.stop();
my4Wheeler.start();
my4Wheeler.stop();
}
}
What Is an Object?
real-world objects: your dog, your desk, your television set, your
bicycle.
Real-world objects share two characteristics: They all have state and behavior.
Dogs have state (name, color, breed, hungry) and behavior (barking,
fetching, wagging tail). Bicycles also have state (current gear, current
pedal cadence, current speed) and behavior (changing gear, changing pedal
cadence, applying brakes)
Core Java
Software Objects
Benefits of Objects
What is a Class ?
Example,
bicycle is an instance of the class of objects known as bicycles. A class is the
blueprint from which individual objects are created.
Core Java
What Is an Interface ?
Interfaces form a contract between the class and the outside world, and this
contract is enforced at build time by the compiler.
What is a Package ?
A package is a namespace that organizes a set of related classes and interfaces.
Example,
You might keep HTML pages in one folder, images in another, and
scripts or applications in yet another.
What is abstraction?
Ans) Abstraction is way of converting real world objects in terms of class. For example creating a class
Vehicle and injecting properties into it. E.g
What is Association?
Ans) Association is a relationship between two classes. In this relationship the object of one instance
perform an action on behalf of the other class. The typical behaviour can be invoking the method of other
class and using the member of the other class.
public class MyMainClass{
public void init(){
Core Java
new OtherClass.init();
}
}
What is Aggregation?
Ans) Aggregation has a relationship between two classes. In this relationship the object of one class is a
member of the other class. Aggregation always insists for a direction.
public class MyMainClass{
OtherClass otherClassObj = new OtherClass();
}
Inner Class
What is an inner class?
Ans) Inner class is a class defined inside other class and act like a member of the enclosing
class.
This fragment defines the class A which contains an static inner class B.
A static inner class behaves like any ``outer'' class. It may contain
methods and fields, and it may be instantiated like this:
Core Java
A.B object = new A.B ();
This statement creates an new instance of the inner class B. Given such
an instance, we can invoke the f method in the usual way:
object.f();
Note, it is not necessarily the case that an instance of the outer class
A exists even when we have created an instance of the inner class.
Similarly, instantiating the outer class A does not create any instances
of the inner class B.
The methods of a static inner class may access all the members (fields or methods) of the
inner class but they can access only static members (fields or methods) of the outer class.
Thus, f can access the field x, but it cannot access the field y.
Example,
class OuterTestCLass {
String str1 = "OuterCLass";
static String str2 = "OuterCLass1";
public static class StaticInnerClass {
int n = 10;
String str = "SampleInnerStaticVar";
void print() {
System.out.println(n + " " + str + + str2);
//System.out.println(str1); // only allows static member of outer class
OuterTestCLass outer = new OuterTestCLass();
outer.display();
}
}
public void display() {
System.out.println(str1);
}
/**
* @param args
*/
/*public static void main(String[] args) {
// TODO Auto-generated method stub
StaticInnerClassDemo outer = new StaticInnerClassDemo();
outer.display();
StaticInnerClass inner = new StaticInnerClass();
inner.print();
StaticInnerClassDemo.StaticInnerClass obj = new
StaticInnerClassDemo.StaticInnerClass();
obj.print();
}*/
Core Java
}
public class StaticInnerClassDemo {
public static void main(String[] args) {
/*StaticInnerClass in = new StaticInnerClass();// Throws an Error cause static
inner class cant have instance
in.print();*/
OuterTestCLass.StaticInnerClass inner = new OuterTestCLass.StaticInnerClass();
inner.print();
}
}
A non-static java inner class can have instances that belong to the outer class.
Member class
The member class can be declared as public, private, protected, final and abstract.
If you mention private inner class its visible only enclosing class not in outer world
Example,
class InnerClassDemoSample {
private String str = "Welcome Outer private Variable";
static int m = 100;
final int n = 25;
public void demo() {
System.out.println("Outer Class method");
InnerClass inner = new InnerClass();
inner.demoInner();
}
private class innerprivateclass {
Core Java
//
static int n = 10; // static variable is not allowed here inside the
non-static inner class
final int n = 10;
public void demoInner() {
System.out.println("outer Class var " + str);
System.out.println("Inner Class var " + strinner + " " + n);
System.out.println(InnerClassDemoSample.m);
System.out.println(new InnerClassDemoSample().n);
}
@Override
void sample() {
// TODO Auto-generated method stub
System.out.println("overriden abstarct inner class method");
}
}
/*public static void main(String[] args) {
InnerClassDemo in = new InnerClassDemo();
in.demo();
InnerClass inp = in.new InnerClass();
inp.demoInner();
}*/
}
class InnerClassDemo {
public static void main(String[] args) {
InnerClassDemoSample.InnerClass inp = new InnerClassDemoSample().new
InnerClass();
inp.demoInner();
inp.sample();
InnerClassDemoSample outer = new InnerClassDemoSample();
outer.demo();
}
You can declare an inner class within the body of a method. These classes are
known as local classes.
You can also declare an inner class within the body of a method without naming the
class. These classes are known as anonymous classes.
Local Class
The inner class declared inside the method is called method local inner class.
Method local class can only access global variables or method local variables if declared
as final
Core Java
class MethodLocal {
MethodLocal() {
System.out.println(k + i);
}
}
}
}
class LocalInnerClassDemo {
int m = 10; // it may have any modifier like private, public, final,
static like that
public void method() {
final String s = "testlocal";
String str1 = "teststatic";
abstract class LocalInnerabstractClass {
public abstract void sample();
public void localinnerabstractmethod() {
System.out.println(m);
System.out.println(s);
}
}
final class LocalInnerClass extends LocalInnerabstractClass {
String str = "localinnerclass";
public void localinnermethod() {
System.out.println(str);
System.out.println(m);
//
System.out.println(s + " " + str1); // local variable
also not allowed here only final variable allowed
}
@Override
public void sample() {
System.out.println("overriden local inner abstract mehod");
}
}
}
public class TestLocalInnerClassDemo {
public static void main(String[] args) {
LocalInnerClassDemo inner = new LocalInnerClassDemo();
inner.method();
}
}
Core Java
Anonymous inner class
The inner class shares a special relationship with the outer class i.e. the inner class has access to
all members of the outer class and still have its own type is the main advantages of Inner class.
Advantage of inner class is that they can be hidden from the other classes in the same
package and still have the access to all the members (private also) of the enclosing
class. So the outer class members which are going to be used by the inner class can be
made private and the inner class members can be hidden from the classes in the same
package. This increases the level of encapsulation.
The advantage of using static nested class is that to instantiate a static nested class you need not
create an instance of the enclosing class which reduces the number of objects the
application creates at runtime.
Inner classes are best used in the event handling mechanism and to implement the helper
classes.
Core Java
2. Inner classes get limited support of ide/tools as compared to the top level classes, so
working with the inner classes is sometimes annoying for the developer.
ENUM
Enum in Java is a keyword, a feature which is used to represent fixed
number of well known values in Java,
An enum type is a special data type that enables for a variable to be a
set of predefined constants. The variable must be equal to one of the
values that have been predefined for it.
How to represent enumerable value without Java enum
public class CurrencyDenom
public static final int
public static final int
public static final int
public static final int
}
{
PENNY = 1;
NICKLE = 5;
DIME = 10;
QUARTER = 25;
Core Java
What is Enum in Java
Java Enum is type like class and interface and can be used to define a
set of Enum constants.
Enum constants are implicitly static and final and you can not change there
value once created.
Core Java
private Currency(int value) {
this.value = value;
}
};
Constructor of enum in java must be private any other access modifier
will result in compilation error. Now to get the value associated with
each coin you can define a public getValue() method inside java enum like
any normal java class.
4) Enum constants are implicitly static and final and can not be changed once created. For
example below code of java enum will result in compilation error:
Currency.PENNY = Currency.DIME;
The final field EnumExamples.Currency.PENNY cannot be re assigned.
5) Enum in java can be used as an argument on switch statment and with
"case:" like int or char primitive type. This feature of java enum makes
them very useful for switch operations. Lets see an example of how to
use java enum inside switch statement:
Currency usCoin = Currency.DIME;
switch (usCoin) {
case PENNY:
System.out.println("Penny coin");
break;
case NICKLE:
System.out.println("Nickle coin");
break;
case DIME:
System.out.println("Dime coin");
break;
case QUARTER:
System.out.println("Quarter coin");
}
6) Since constants defined inside Enum in Java are final you can safely
compare them using "==" equality operator as shown in following example
of Java Enum:
Currency usCoin = Currency.DIME;
if(usCoin == Currency.DIME){
System.out.println("enum in java can be compared using ==");
}
By the way comparing objects using == operator is not recommended, Always
use equals() method or compareTo() method to compare Objects.
7) Java compiler automatically generates static values() method for every enum
in java. Values() method returns array of Enum constants in the same
order they have listed in Enum and you can use values() to iterate over
values of Enum in Java as shown in below example:
for(Currency coin: Currency.values()){
System.out.println("coin: " + coin);
}
Core Java
And it will print:
coin: PENNY
coin: NICKLE
coin: DIME
coin: QUARTER
Notice the order its exactly same with defined order in enums.
8) In Java Enum can override methods also. Lets see an example of
overriding toString() method inside Enum in Java to provide meaningful
description for enums constants.
public enum Currency {
........
@Override
public String toString() {
switch (this) {
case PENNY:
System.out.println("Penny: " + value);
break;
case NICKLE:
System.out.println("Nickle: " + value);
break;
case DIME:
System.out.println("Dime: " + value);
break;
case QUARTER:
System.out.println("Quarter: " + value);
}
return super.toString();
}
};
And here is how it looks like when displayed:
Currency usCoin = Currency.DIME;
System.out.println(usCoin);
output:
Dime: 10
10) You can not create instance of enums by using new operator in Java
because constructor of Enum in Java can only be private and Enums
constants can only be created inside Enums itself.
11) Instance of Enum in Java is created when any Enum constants are first
called or referenced in code.
12) Enum in Java can implement the interface and override any method like
normal class Its also worth noting that Enum in java implicitly implement both
Serializable and Comparable interface. Let's see and example of how to implement
interface using Java Enum:
public enum Currency implements Runnable{
PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
private int value;
............
Core Java
@Override
public void run() {
System.out.println("Enum in Java implement interfaces");
}
13) You can define abstract methods inside Enum in Java and can also
provide different implementation for different instances of enum in java.
Lets see an example of using abstract method inside enum in java
public enum Currency implements Runnable{
PENNY(1) {
@Override
public String color() {
return "copper";
}
}, NICKLE(5) {
@Override
public String color() {
return "bronze";
}
}, DIME(10) {
@Override
public String color() {
return "silver";
}
}, QUARTER(25) {
@Override
public String color() {
return "silver";
}
};
private int value;
public abstract String color();
private Currency(int value) {
this.value = value;
}
..............
}
In this example since every coin will have different color we made the
color() method abstract and let each instance of Enum to define
there
own color. You can get color of any coin by just calling color() method
as shown in below example of java enum:
System.out.println("Color: " + Currency.DIME.color());
Enum Java valueOf example
One of my reader pointed out that I have not mention about valueOf method
of enum in Java, which is used to convert String to enum in java. It could also
include valueOf() method of enum in java which is added by compiler in any enum
along with values() method. Enum valueOf() is a static method which takes a
Core Java
string argument and can be used to convert a String into enum. One think
though you would like to keep in mind is that valueOf(String) method of
enum will throw "Exception in thread "main"
java.lang.IllegalArgumentException: No enum const class" if you supply
any string other than enum values.
JVM is an interpreter
Core Java
Internal details of JVM will differ from platform to platform but still all understand
the Same Java Bytecode
The JVM prevent JAVA code from generating side effects outside of
the system.
Core Java
Core Java
Java Developer Kit contains tools needed to develop the Java programs, and JRE to run the
programs.
The tools include compiler (javac.exe), Java application launcher (java.exe), Appletviewer,
etc Compiler converts java code into byte code.
Java application launcher opens a JRE, loads the class, and invokes its main method.
You need JDK, if at all you want to write your own programs, and to compile.
JRE is targeted for execution of Java files i.e. JRE = JVM + Java Packages Classes(like util,
math, lang, awt,swing etc) + runtime libraries.
JDK is mainly targeted for java development. i.e. You can create a Java file (with the help of
Java packages), compile a Java file and run a java file.
Java Runtime Environment contains JVM, class libraries, and other supporting files.
It does not contain any development tools such as compiler, debugger, etc.
Actually JVM runs the program, and it uses the class libraries, and other supporting files provided in JRE.
If you want to run any java program, you need to have JRE installed in the system
But, note that JVM itself not a platform independent. It only helps Java to be executed
on the platform-independent way.
When JVM has to interpret the byte codes to machine language, then it has to use some native
or operating system specific language to interact with the system.
One has to be very clear on platform independent concept. Even there are many JVMs written
on Java, however they too have little bit of code specific to the operating systems.
As we all aware when we compile a Java file, output is not an exe but its a .class file.
.class file consists of Java byte codes which are understandable by JVM.
Java Virtual Machine interprets the byte code into the machine code depending upon the
underlying operating system and hardware combination.
It is responsible for all the things like garbage collection, array bounds checking, etc
Core Java
JIT is the part of the Java Virtual Machine (JVM) that is used to speed up the
execution time.
JIT compiles parts of the byte code that have similar functionality at the same time,
and hence reduces the amount of time needed for compilation.
Here the term compiler refers to a translator from the instruction set of a
Java virtual machine (JVM) to the instruction set of a specific CPU.
Core Java
Keyword which identifies the class related this. It means that this class is
not instance related but class related. It can be accessed without creating the
instance of Class.
Static because it be available for execution without an object instance. you may
know that you need an object instance to invoke any method. So you cannot begin
execution of a class without its object if the main method was not static.
Void : Return Type, It defined what this method can return. Which is void in this
case it means that this method will not return any thing.
void because, once the main method execution is over, the program
terminates. So there can be no data that can be returned by the Main method.
main:
Keep in mind that Java is case-sensitive. Thus, Main is different from main.
It is important to understand that the Java compiler will compile classes that do
not contain a main( ) method.
But the Java interpreter has no way to run these classes. So, if you had typed
Main instead of main, the compiler would still compile your program. However,
the Java interpreter would report an error because it would be unable to
find the main( ) method.
Core Java
String args[] :
may opt to enter parameters to the java program at command line. We can use
both String[] args or String args[]. The Java compiler would accept both forms.
Definition Of main method in Java .?
The main method in Java belongs to a class but not to an Object. Objects are created at The
main() in Java is the start point in your application, there is no way to start your application from
an instance specific method. That is why the static keyword make perfect sense with the main
method. In fact all the parts of the main method declaration make perfect sense when you think like
the 'jvm' and picture what the main method does (starts the application):
public, because this method must be accessible by the jvm (not written by you).
static, implying this method can be accessed without having an object (because it's
representation never changes), but here the logic is easy understood if you think like the
jvm again; "I don't have any objects to create (instantiate) objects, so I need a static method
to start the application as there simple isn't any logical way to get an instance specific
method up yet as I don't have anything up yet to create objects".
Void This method can't logically return anything because there is nothing up yet to return
anything to. It is the start point of the application. main I am the main method as without me
you won't have an application.
String[] args Send me data you may feel useful for my startup.
Core Java
Note : It shows error like The public type TestSample must be defined in its own file
*) for example, the following two class files are saved as TestPublic.java
class TestPublicDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("sample");
}
TestPublicDemo.class
sample.class
}
class sample {
Output :
sample
100
praveen
The main thread of an application will always start at the method with the signature
public static void main(String[] args)
and nothing else. For starting an application, JVM will understand the main method signature is
mentioned above and ignore all other main methods.
Core Java
class Super {
static String greeting() { return "Goodnight"; }
String name() { return "Richard"; }
}
class Sub extends Super {
static String greeting() { return "Hello"; }
String name() { return "Dick"; }
}
class Test {
public static void main(String[] args) {
Super s = new Sub();
System.out.println(s.greeting() + ", " + s.name());
}
}
Access modifiers
1. public
2. private
3. protected
4. default
Class Level
Example,
public class SampleTest {} public
class SampleTest {}
default
public final
Core Java
Inner Class Level
Example,
private class InnerPrivate {}
public class InnerPublic {}
protected class InnerProtected {}
class InnerDefault {}
final class InnerFinal {}
abstract class InnerAbstract {}
static class InnerStatic {}
static final class InnerStaticFinal {}
static abstract class InnerStaticAbsrtact {}
Field level Access modifiers :
public class StaticTest {
int i = 100;
static String str = "Praveen";
private String s1 = "private string";
public String s2 = "public string";
protected String s3 = "protected String";
final String s4 = "final String";
String s5 = "default String";
// Method level and block level only default, final modifiers allowed for
declaring fields
static {
// static block
static String str = "first"; // shows error
System.out.println("static block is executed");// first
}
{
}
// instance block
static String str = "instance string"; // shows error
System.out.println("instance block is executed");
// third
StaticTest() {
// constructor
static String str = "constructor string"; // shows error
System.out.println("constructor is executed"); //fourth
Core Java
}
static void display() { // Method level only default, final modifiers
allowed for declaring fields
static String s6 = "static method field"; // shows error
private String s7 = "private string";
// shows error
public String s8 = "public string"; // shows error
protected String s9 = "protected String"; // shows error
void print() {
final int count = 100;
System.out.println("same class default method" + this.i + " " +
super.hashCode());
}
public static void main(String[] args) { // shows error
static String c = "test string"; static is not allowed here
method();
}
}
static keyword
The static keyword is used in JAVA mainly for memory management. We may apply static
keyword with variables, methods, blocks and nested class. The static keyword belongs to
the class than instance of the class.
The static can be:
1.variable (also known as class variable)
2.method (also known as class method)
3.block
4.nested class
1) static variable
If you declare any variable as static, it is known static
variable.
The static variable can be used to refer the common property of all objects (that is not unique for each object)
e.g. company name of employees,college name of students etc.
The static variable gets memory only once in class area at the time of class
loading.
Core Java
Advantage of static variable
It makes your program memory efficient (i.e it saves
memory).
Suppose there are 500 students in my college, now all instance data members will get memory each
time when object is created.All student have its unique rollno and name so instance data member is
good.Here, college refers to the common property of all objects.If we make it static,this field will
get memory only once.
static property is shared to all objects.
class Student{
int rollno;
String name;
static String college="ITS";
s1.display();
s2.display();
}
}
Core Java
Output:111 Karan ITS
Counter(){
count++;
System.out.println(count);
}
Core Java
publicstaticvoidmain(Stringargs[]){
Counterc1=newCounter();
Counterc2=newCounter();
Counterc3=newCounter();
}}
Output:1
1
1
Counter(){
count++;
System.out.println(count);
}
publicstaticvoidmain(Stringargs[]){
Counterc1=newCounter();
Counterc2=newCounter();
Counterc3=newCounter();
}}
Output:1
2
3
Core Java
2) static method
If you apply static keyword with any method, it is known as static
method.
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.
class
of
changing
the
common
property
of
all
objects(static
field).
Student{
int
rollno;
String
name;
static
String
static
void
college
college
"ITS";
change(){
"BBDIT";
Student(int
r,
rollno
r;
name
n;
String
n){
void
display
(){System.out.println(rollno+"
public
static
void
main(String
args[]){
Student.change();
Student
s1
new
Student
(111,"Karan");
Student
s2
new
Student
(222,"Aryan");
Student
s3
new
Student
(333,"Sonoo");
s1.display();
s2.display();
"+name+"
"+college);}
Core Java
s3.display();
}
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
Class
to
get
cube
of
given
number
by
static
method
Calculate{
static
int
return
cube(int
x){
x*x*x;
public
int
static
void
main(String
args[]){
result=Calculate.cube(5);
System.out.println(result);
}
}
Output:125
A{
a=40;//non
public
static
static
void
main(String
System.out.println(a);
}
args[]){
Core Java
}
Output:Compile Time Error
Example,
class Example {
String str = "Kumar";
static int amount = 1000;
void demo() {
System.out.println("default method");
}
public void print() {
System.out.println("public method");
}
Core Java
System.out.println(str);
// Directly we can access (advantage)
System.out.println(new StaticTest().i); // can access indirectly
display(); // Directly we can access (advantage)
new StaticTest().print(); // can access indirectly
}
public static void main(String[] args) {
method();
}
}
Output :
static method
1000
default method
public method
Kumar
Praveen
100
same class static method
same class default method
3)static block
Is used to initialize the static data member.
It is executed before main method at the time of class loading.
A{
static{System.out.println("static
public
static
void
block
main(String
System.out.println("Hello
is
invoked");}
args[]){
main");
}
}
Output:static block is invoked
Hello main
Core Java
class
A{
static{
System.out.println("static
block
is
invoked");
System.exit(0);
}
}
Output:static block is invoked (if not JDK7)
Order Of Execution
public class OrderOfExecution {
static {
// static block
System.out.println("static block is executed");// first
}
{
}
// instance block
System.out.println("instance block is executed");
// third
//second
Output :
static block is executed
main block
instance block is executed
constructor is executed
StackOverflow error
Example,
public class OrderOfExecution {
static {
// static block
System.out.println("static block is executed");// first
new OrderOfExecution();
}
{
}
// instance block
System.out.println("instance block is executed");
new OrderOfExecution();
// third
Core Java
OrderOfExecution() {
// constructor
System.out.println("constructor is executed"); //fourth
}
public static void main(String[] args) { // main method
System.out.println("main block");
new OrderOfExecution();
//second
Output
instance block is executed
instance block is executed
instance block is executed
instance block is executed
instance block is executed
instance block is executed
instance block is executed
instance block is executed
instance block is executed
Exception in thread "main" java.lang.StackOverflowError
at sun.nio.cs.UTF_8.updatePositions(UTF_8.java:58)
at sun.nio.cs.UTF_8$Encoder.encodeArrayLoop(UTF_8.java:392)
at sun.nio.cs.UTF_8$Encoder.encodeLoop(UTF_8.java:447)
at java.nio.charset.CharsetEncoder.encode(CharsetEncoder.java:544)
at sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:252)
at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:106)
at java.io.OutputStreamWriter.write(OutputStreamWriter.java:190)
at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:111)
at java.io.PrintStream.write(PrintStream.java:476)
at java.io.PrintStream.print(PrintStream.java:619)
at java.io.PrintStream.println(PrintStream.java:756)
Java instance variables are given separate memory for storage. If there is a
need for a variable to be common to all the objects of a single java class, then the
static modifier should be used in the variable declaration.
Any java object that belongs to that class can modify its static variables.
Also, an instance is not a must to modify the static variable and it can be accessed
using the java class directly.
When the value of a constant is known at compile time it is declared final using
the static keyword.
Similar to static variables, java static methods are also common to classes and not
tied to a java instance.
Core Java
Good practice in java is that, static methods should be invoked with using the class
name though it can be invoked using an object.
ClassName.methodName(arguments) or objectName.methodName(arguments)
Java static methods cannot use the this and 'super' keyword.
For java classes, only an inner class can be declared using the static modifier.
For java a static inner class it does not mean that, all their members are static.
These are called nested static classes in java.
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
Final variable alone is not a constant it means just assign the value once it cant be re-assign
Core Java
Bike{
final
int
speedlimit=90;//final
void
run(){
variable
speedlimit=400;
}
public
Bike
static
void
obj=new
main(String
args[]){
Bike();
obj.run();
}
Output:Compile Time Error
2) final method
If you make any method as final, you cannot override it.
Bike{
final
void
run(){System.out.println("running");}
class
Honda
void
extends
Bike{
run(){System.out.println("running
public
static
Honda
honda=
void
new
honda.run();
}
}
Output:Compile Time Error
main(String
Honda();
safely
args[]){
with
100kmph");}
Core Java
3) final class
If you make any class as final, you cannot extend it.
class
class
Bike{}
Honda
void
extends
Bike{
run(){System.out.println("running
public
static
Honda
honda=
void
main(String
new
safely
with
100kmph");}
args[]){
Honda();
honda.run();
}
Output:Compile Time Error
Bike{
final
void
run(){System.out.println("running...");}
}
class
Honda
public
new
extends
static
Bike{
void
main(String
args[]){
Honda().run();
}
}
Output:running...
Core Java
of an employee. It can be initialized only in constructor.
Student{
id;
String
final
name;
String
PAN_CARD_NUMBER;
...
}
Bike{
final
int
speedlimit;//blank
final
variable
Bike(){
speedlimit=70;
System.out.println(speedlimit);
}
public
new
Static
void
main(String
args[]){
Bike();
}
}
Output:70
A{
static
static{
final
int
data=50;}
data;//static
blank
final
variable
Core Java
public
Static
void
main(String
args[]){
System.out.println(A.data);
}
}
Bike{
cube(final
int
n=n+2;//can't
be
n){
changed
as
is
final
n*n*n;
}
public
Bike
Static
void
b=new
main(String
args[]){
Bike();
b.cube(5);
}
}
Output:Compile Time Error
keyword
in
Java:
allows
JVM
multi-threading
final variable
environment without
class.
Core Java
Final and Immutable Class in Java
Final keyword helps to write immutable class. Immutable classes are the
one which can not be modified once it gets created and String is primary
example of immutable and final class which I have discussed in detail on
Why String is final or immutable in Java.
Immutable classes offer several benefits one of them is that they are
effectively read-only and can be safely shared in between multiple
threads without any synchronization overhead.
You can not make a class immutable without making it final and hence final
keyword is required to make a class immutable in java.
final variable in
Java.
Final method
7.
Final
8. Final
in Java.
class
can not be
overridden in Java.
is different than
class in Java.
finally
Java.
keyword
which is used on
Exception handling
9. Final should not be confused with finalize() method which is declared in object
class and called before an object is garbage collected by JVM.
10. All variable declared inside
11. Final and abstract
abstract in java.
java
keyword
and a final
class
can not be
12. Final methods are bonded during compile time also called static binding.
13. Final variables which is not initialized during declaration are called blank final
variable and must be initialized on all constructor either explicitly or by calling this().
Core Java
Failure to do so compiler will complain as "final variable (name) might not be
initialized".
14. Making a class, method or variable final in Java helps to improve performance
because JVM gets an opportunity to make assumption and optimization.
15. As per Java code
written in all Caps e.g.
convention
s = "mutable";
count = 20;
// cant re-assign
// cant re-assign
str.add("A");
str.add("B");
str.add("C");
str.add("D");
return str;
d = 23.3434;
// cant re-assign
and
Core Java
List<String> str = new FinalTest().getChangedList();
for (String s : str) {
System.out.println(s);
}
demo.addAll(str);
// cant re-assign
for(String s : demo) {
// cant re-assign
System.out.println(s);
}
}
Abstract class
A class that is declared as abstract is known as abstract class. It needs to be extended and
its method implemented. It cannot be instantiated.
abstract method
A method that is declared as abstract and does not have implementation is known as
abstract method.
Core Java
Core Java
class Test{
public static void main(String args[]){
Shape s=new Circle();
//In real scenario, Object is provided through factory method
s.draw();
}
}
Output:drawing circle
Core Java
void getDetails(){System.out.println("it has two wheels");}
abstract void run();
}
Rule: If you are extending any abstract class that have abstract method,
you must either provide the implementation of the method or make this
class abstract.
Core Java
}
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}
class Test{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}
Output:I am a
I am b
I am c
I am d
Example,
abstract class A {
static final String str = "Praveen";
final String s;
// private public protected default all r applicable
static final String s1;
abstract public void demo();
abstract protected void display();
abstract void cal();
public final void welcome() {
System.out.println("public final method in abstract class");
}
public void print() {
System.out.println("print method in abstract class");
}
public A() {
Core Java
}
{
field
@Override
public void demo() {
System.out.println("overriden from A + " + str); // static final
}
@Override
protected void display() {
System.out.println("i am display + " + s); // final field
}
@Override
void cal() {
System.out.println("i am cal + " + s1); // static final field
}
}
public class AbstractTest {
public static void main(String[] args) {
//
A a1 = new A();
// abstract class cant be instantiated
A a = new C("Testing");
a.cal();
a.demo();
a.display();
a.print();
a.welcome();
Core Java
}
Output :
abstract class static block
C class static block
abstract class instance block
abstract class constructor
C class instance block
extend class Constructor with Argument Testing
i am cal + static blank field initialization
overriden from A + Praveen
i am display + blank final field initialization
print method in abstract class
public final method in abstract class
Core Java
public A() {
s = "blank final field initialization";
System.out.println("abstract class constructor"); 4
}
{
System.out.println("abstract class instance block"); 3
}
static {
s1 = "static blank field initialization";
System.out.println("abstract class static block"); 1
}
public void AA() {
System.out.println("interface AA method");
}
}
class C extends A {
public C() {
super();
System.out.println("C class constructor");
}
public C(String s) {
System.out.println("extend class Constructor with Argument " + s); 6
}
static {
System.out.println("C class static block"); 2
}
{
}
field
@Override
public void demo() {
System.out.println("overriden from A + " + str); // static final
}
@Override
protected void display() {
System.out.println("i am display + " + s); // final field
}
@Override
void cal() {
System.out.println("i am cal + " + s1); // static final field
}
@Override
public void BB() {
System.out.println("Interface BB method");
}
@Override
public void CC() {
Core Java
}
System.out.println("Interface CC method");
A a1 = new A();
// Object is created for "C" Class but the reference type is pointed to A
// So reference variable a is access only A and D type scope data members only
Object Slicing
A a = new C("Testing"); // Object Slicing happens here
a.cal();
a.demo();
a.display();
a.print();
a.welcome();
a.DD();
// shows error DD() is not comes under A type Scope
Object Slicing
// reference variable d access only D type scope data members only
D d = new C();
d.DD();
// shows error DD() is not comes under D type scope
d.cal();
// shows error DD() is not comes under D type scope
d.demo();
// shows error DD() is not comes under D type scope
d.AA();
d.BB();
d.CC();
System.out.println(D.sample);
System.out.println(D.test);
Object Slicing
// reference variable c access all A & D & C data members
C c = new C();
c.AA();
c.DD();
c.demo();
}
}
Output :
abstract class static block
C class static block
abstract class instance block
Core Java
abstract class constructor
C class instance block
extend class Constructor with Argument Testing
i am cal + static blank field initialization
overriden from A + Praveen
i am display + blank final field initialization
print method in abstract class
public final method in abstract class
abstract class instance block
abstract class constructor
C class instance block
C class constructor
interface AA method
Interface BB method
Interface CC method
interface blank field
interface blank static final field
abstract class instance block
abstract class constructor
C class instance block
C class constructor
interface AA method
C class method
overriden from A + Praveen
We Can define abstract keyword in class without declaring abstract method
Example,
abstract class E {
public void AAA() {
System.out.println("AAA method in E");
}
public void BBB() {
System.out.println("BBB method in E");
}
}
Note :
Interface
Core Java
The java compiler adds public and abstract keywords before the interface
method and public, static and final keywords before data
members.
In other words, Interface fields are public, static and final by default, and methods are public
and abstract
Core Java
Understanding relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends
another interface but a class implements an interface.
Core Java
inheritance.
interface Printable{
void print();
}
interface Showable{
void show();
}
Core Java
Q) Multiple inheritance is not supported in case of class but it is supported in case of
interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported
in case of class. But it is supported in case of interface because there is no ambiguity
as implementation is provided by the implementation class. For example:
interface Printable{
void print();
same method
interface Showable{
void print();
same method
Core Java
}
Nested Interface
The nested interfaces are used to group related interfaces so that they can be easy
to maintain.
The nested interface must be referred by the outer interface or class. It can't be
accessed directly.
Core Java
Nested interface must be public if it is declared inside the interface but it
can have any access modifier if declared within the class.
Nested interfaces are declared static implicitly.
Core Java
message.msg();
}
}
Output:hello nested interface
As you can see in the above example, we are accessing the Message interface by its outer
interface Showable because it cannot be accessed directly. It is just like almirah inside the
room, we cannot access the almirah directly because we must enter the room first. In
collection framework, sun microsystem has provided a nested interface Entry.
Entry is the subinterface of Map i.e. accessed by Map.Entry.
Internal code generated by the java compiler for nested interface Message
The java compiler internally creates public and static interface as displayed
below:.
public static interface Showable$Message
{
public abstract void msg();
}
Core Java
Output:hello nested interface
void demo();
void display();
void print();
interface BB extends AA {
void cal();
void printValue();
// Nested Class
interface CC {
String str = "must be initialized";
void sample();
void print();
class Start {
// by default compiler treat as static class
public void start() {
System.out.println("i am start method inside interface");
}
}
// Nested Interfaces
interface DD {
void sample();
public interface EE { // public and no-modifier only allowed nested
interface inside interface by default compiler treat as public static interface
void color();
}
}
class YYY extends CC.Start implements DD, DD.EE {
String str = "Praveen";
static String s = "Kumar";
@Override
Core Java
public void sample() {
System.out.println("I am sample from DD type");
}
@Override
public void color() {
System.out.println("I am white color");
}
static interface FF {
// private, public, protected, no-modifier, static
all are applicable nested interface inside class
void logo();
}
static interface GG {
}
}
class XXX extends YYY implements BB, CC, YYY.FF{
public void demo() {
System.out.println("i am demo");
}
public void display() {
System.out.println("i am display");
}
//
//
//
Core Java
public class InterfaceTest {
public static void main(String[] args) {
System.out.println("It Comes under AA type Scope");
AA a = new XXX();
a.demo();
a.display();
a.print();
System.out.println("It Comes under BB type Scope");
BB b = new XXX();
b.cal();
b.demo();
b.display();
b.print();
b.printValue();
System.out.println("It Comes under XXX type Scope");
XXX x = new XXX();
x.cal();
x.demo();
x.display();
x.print();
x.printValue();
x.welcome();
x.logo();
System.out.println("It Comes under CC type Scope");
CC c = new XXX();
c.sample();
c.print();
System.out.println(CC.str);
System.out.println("It Comes under DD type Scope");
DD d = new YYY();
d.sample();
System.out.println("It Comes under DD.EE type Scope");
DD.EE e = new YYY();
// Nested Interfaces instantiation
e.color();
System.out.println("It Comes under YYY type Scope");
YYY y = new XXX();
y.color();
y.sample();
System.out.println("It Comes under DD type Scope");
DD d1 = new XXX();
d1.sample();
System.out.println("It Comes under DD.EE type Scope");
DD.EE e1 = new XXX();
e1.color();
System.out.println("It Comes under YYY.FF type Scope");
YYY.FF f = new XXX();
f.logo();
System.out.println("It Comes under CC.Start type Scope");
Core Java
CC.Start s = new XXX();
s.start();
}
Output
It Comes under AA type Scope
i am demo
i am display
I am print
It Comes under BB type Scope
i am cal
i am demo
i am display
I am print
i am printValue
It Comes under XXX type Scope
i am cal
i am demo
i am display
I am print
i am printValue
I am welcome
I am nested interface logo
It Comes under CC type Scope
I am sample
I am print
must be initialized
It Comes under DD type Scope
I am sample from DD type
It Comes under DD.EE type Scope
I am white color
It Comes under YYY type Scope
I am white color
I am sample
It Comes under DD type Scope
I am sample
It Comes under DD.EE type Scope
I am white color
It Comes under YYY.FF type Scope
I am nested interface logo
It Comes under CC.Start type Scope
i am start method inside interface
Core Java
*/
*/
Core Java
In the Figure class above, we have an abstract method called getArea(), and because the Figure class
contains an abstract method the entire Figure class itself must be declared abstract. The Figure base
Core Java
class has two classes which derive from it called Circle and Rectangle. Both the Circle and Rectangle
classes provide definitions for the getArea method, as you can see in the code above.
But the real question is why did we declare the getArea method to be abstract in the Figure class? Well,
what does the getArea method do? It returns the area of a specific shape. But, because the Figure class
isnt a specific shape (like a Circle or a Rectangle), theres really no definition we can give the getArea
method inside the Figure class. Thats why we declare the method and the Figure class to be abstract.
Any classes that derive from the Figure class basically has 2 options:
1. The derived class must provide a definition for the getArea method OR
2. The derived class must be declared abstract itself.
It must have the phrase "implements Interface_Name" at the beginning of the class definition.
It must implement all of the method headings listed in the interface definition.
Now, if a class were to implement this interface, this is what it would look like:
Core Java
Now that we know the basics of interfaces and abstract classes, lets get to the heart of the question and
explore the differences between the two. Here are the three major differences:
With an interface on the other hand, the relationship between the interface itself and the class
implementing the interface is not necessarily strong. For example, if we have a class called "House", that
class could also implement an interface called "AirConditioning". Having air conditioning not really an
essential part of a House (although some may argue that point), and the relationship is not as strong as,
say, the relationship between a TownHouse class and the "House" class or the relationship between an
Apartment class that derives from a House class.
Because a TownHouse is a type of House, that relationship is very strong, and would be more
appropriately defined through inheritance instead of interfaces.
So, we can summarize this first point by saying that an abstract class would be more appropriate when
there is a strong relationship between the abstract class and the classes that will derive from it. Again,
this is because an abstract class is very closely linked to inheritance, which implies a strong relationship.
But, with interfaces there need not be a strong relationship between the interface and the classes that
Core Java
implement the interface.
An abstract class is good if you think you will plan on using inheritance since it
provides a common base class implementation to derived classes.
An abstract class is also good if you want to be able to declare non-public members. In
an interface, all methods must be public.
If you think you will need to add methods in the future, then an abstract class is a
better choice. Because if you add new method headings to an interface, then all of the
classes that already implement that interface will have to be changed to implement the
new methods. That can be quite a hassle.
Interfaces are a good choice when you think that the API will not change for a while.
Interfaces are also good when you want to have something similar to multiple
inheritance, since you can implement multiple interfaces.
Access Modifiers
There are two types of modifiers in java: access modifier and non-access modifier. The
access modifiers specifies accessibility (scope) of a data member, method, constructor or class.
There are 4 types of access modifiers:
1.private
2.default
3.protected
Core Java
4.public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile,
transient etc. Here, we will learn access modifiers.
1) private
The private access modifier is accessible only within
class.
Core Java
}
}
2) default
If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package.
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
3) protected
The protected access modifier is accessible within package and outside the package but
Core Java
through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
4) public
The public access modifier is accessible everywhere. It has the widest scope among all
other modiers.
package pack;
public class A{
Core Java
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Private
Default
Protected
Public
Visibility
priority
Low
Next to
private
Next to
default
high
outside
package
Core Java
Simple obj=new Simple();
obj.msg();
}
}
The default modifier is more restrictive than protected. That is why there is compile time
error.
Core Java
}
void fourth() {
System.out.println("I am fourth");
}
public static void main(String[] args) {
QQQ q = new OveridingTest();
q.first();
q.second();
q.third();
q.fourth(); // this method is not comes under the scope of QQQ type
QQQ q1 = new QQQ();
q1.first();
q1.second();
q1.third();
q1.fourth(); // Obviously its not possible cant access subclass
method by using super class object references
}
Output
I am first from subclass
I am second from subclass
I am third from subclass
I am first
I am second
I am third
Difference Package
package com.core.basics;
import com.core.demo.OveridingTest;
class HHH extends OveridingTest {
void demo() {
System.out.println("I am demo from HHH");
}
public void display() {
System.out.println("I am display from HHH");
}
protected void print() {
System.out.println("I am print from HHH");
}
// The method HHH.fourth() does not override the inherited method
// from OveridingTest since it is private to a different package
void fourth() {
System.out.println("I am fourth from outside package overriden");
Core Java
}
public void first() {
System.out.println("I am first from outside package overriden");
}
public void second() {
System.out.println("I am second from outside package overriden");
}
Output
I
I
I
I
I
I
I
am
am
am
am
am
am
am
Simple Example
package com.core.demo;
class Animal {
void eat() {
System.out.println("eating");
}
Core Java
}
class Dog extends Animal {
void eat() {
System.out.println("eating fruits");
}
void run() {
System.out.println("Dog runs Fast");
}
}
class BabyDog extends Dog {
void eat() {
System.out.println("drinking milk");
}
void run() {
System.out.println("BabyDog runs slow");
}
void size() {
System.out.println("small");
}
}
public class TestOveride {
public static void main(String[] args) {
Animal a1, a2, a3;
a1 = new Animal();
a2 = new Dog();
a3 = new BabyDog();
a1.eat();
a2.eat();
a3.eat();
// Object Slicing
// Object Slicing
// Object Slicing
Dog d;
d = new BabyDog();
// Object Slicing
d.eat();
d.run();
// Overridden method will be called
}
Output
eating
eating fruits
drinking milk
drinking milk
BabyDog runs slow
Runtime Polymorphism
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
Core Java
overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass.
The determination of the method to be called is based on the object being referred to by the
reference variable.
Let's first understand the upcasting before Runtime Polymorphism.
Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:
class A{}
class B extends A{}
A a=new B();//upcasting
Core Java
Output: running safely with 60km.
Core Java
Animal a1,a2,a3;
a1=new Animal();
a2=new Dog();
a3=new BabyDog();
a1.eat();
a2.eat();
a3.eat();
}
}
Output: eating
eating fruits
drinking Milk
Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is invoked.
Core Java
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand
the behaviour of the method because its name differs. So, we perform method overloading to
figure out the program quickly.
In java, Methood Overloading is not possible by changing the return type of the
method.
}
}
Output:30
40
Core Java
double arguments.
class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(double a,double b){System.out.println(a+b);}
}
1. }
Output:21.0
40
}
}
int result=obj.sum(20,20); //Here how can java determine which sum() method should be called
Core Java
System.out.println(a);
}
As displayed in the above diagram, byte can be promoted to short, int, long, float or
double. The short datatype can be promoted to int,long,float or double. The char datatype
can be promoted to int,long,float or double and so on.
Core Java
Example of Method Overloading with TypePromotion
class Calculation{
void sum(int a,long b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}
}
}
Output:40
60
Core Java
public static void main(String args[]){
Calculation obj=new Calculation();
obj.sum(20,20);//now ambiguity
}
}
Output:Compile Time Error
Simple Example,
public class MethodOverloading {
public void sum() {
System.out.println("with out args");
}
public void sum(int a) {
System.out.println("with one arg");
}
public void sum(long a) {
System.out.println("with long arg");
}
public int sum(double a) {
return 10;
}
public void sum(int a, long b) {
System.out.println("2 args");
}
public void sum(long a, int b) {
System.out.println("2 args");
}
public static void main(String[] args) {
MethodOverloading obj = new MethodOverloading();
System.out.println(obj.sum(12.2323));
obj.sum(10, 10); // The method sum(int, long) is ambiguous for the
type MethodOverloading
obj.sum(10);
obj.sum();
}
}
Output
Core Java
10
with one arg
with out args
String Handling
Generally string is a sequence of characters. But in java, string is an object. String class is
used to create string object.
1) String literal
String literal is created by double quote. For
Example:
String s="Hello";
Each time you create a string literal, the JVM checks the string constant pool first.
If the string already exists in the pool, a reference to the pooled instance returns.
If the string does not exist in the pool, a new String object instantiates, then is
placed in the pool. For example:
String s1="Welcome";
String s2="Welcome";//no new object will be created
Core Java
In the above example only one object will be created. First time JVM will find no string
object with the name "Welcome" in string constant pool, so it will create a new object.
Second time it will find the string with the name "Welcome" in string constant pool,so it will
not create new object whether will return the reference to the same instance.
Note: String objects are stored in a special memory area known as string constant
pool inside the Heap memory.
2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new String object in normal(nonpool) Heap memory and
the literal "Welcome" will be placed in the string constant pool. The variable s will refer to
the object in Heap(nonpool).
Core Java
Immutable String:
In java, strings are immutable (unmodifiable) objects. For
example
class Simple{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}
Output:Sachin
As you can see in the above figure that two objects will be created but no reference variable
refers to "Sachin Tendulkar".But if we explicitly assign it to the reference variable, it will
refer to "Sachin Tendulkar" object.For example:
Core Java
class Simple{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Output:Sachin Tendulkar
We can compare two given on the basis of content and reference. It is used in authentication
(equals() method), sorting (compareTo() method) etc.
There are three ways to compare String objects:
1.By equals() method
2.By = = operator
3.By compareTo() method
1) By equals() method:
equals() method compares the original content of the string. It compares values of
Core Java
string for equality. String class provides two methods:
class Simple{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
Output:true
true
false
//<b><i>Example of equalsIgnoreCase(String) method</i></b>
class Simple{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s3));//true
}
}
Output:false
true
Core Java
2) By == operator:
The = = operator compares references not
values.
//<b><i>Example of == operator</i></b>
class Simple{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
3) By compareTo() method:
compareTo() method compares values and returns an int which tells if the values
compare less than, equal, or greater than.
Suppose s1 and s2 are two string variables.If:
s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value
//<b><i>Example of compareTo() method:</i></b>
class Simple{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
Core Java
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
Output:0
1
-1
class Simple{
public static void main(String args[]){
Core Java
and its append method.String concatenation operator produces a new string by appending
the second operand onto the end of the first operand.The string concatenation operator can
concat not only string but primitive values also.For Example:
class Simple{
public static void main(String args[]){
String s=50+30+"Sachin"+40+40;
System.out.println(s);//80Sachin4040
}
}
Output:80Sachin4040
Note:If either operand is a string, the resulting operation will be string concatenation. If
both operands are numbers, the operator will perform an addition.
2) By concat() method
concat() method concatenates the specified string to the end of current
string.
Syntax:public String concat(String another){}
//<b><i>Example of concat(String) method</i></b>
class Simple{
public static void main(String args[]){
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar
}
}
Output:Sachin Tendulkar
Core Java
Substring in Java
A part of string is called substring. In other words, substring is a subset of another string.
In case of substring startIndex starts from 0 and endIndex starts from 1 or
startIndex is inclusive and endIndex is exclusive.
You can get substring from the given String object by one of the two methods:
1.public String substring(int startIndex): This method returns new String object
containing the substring of the given string from specified startIndex (inclusive).
2.public String substring(int startIndex,int endIndex): This method returns new
String object containing the substring of the given string from specified startIndex to
endIndex.
In case of string:
startIndex:starts from index
0(inclusive).
endIndex:starts from index
1(exclusive).
class Simple{
public static void main(String args[]){
Core Java
}
}
Output:Tendulkar
Sachin
Description
2)public boolean
equalsIgnoreCase(String another)
ignoring case.
5)public int
compareToIgnoreCase(String str)
differences.
beginIndex)
string.
beginIndex,int endIndex)
string.
prefix)
prefix.
Core Java
14)public int length()
15)public String intern()
First seven methods have already been discussed.Now Let's take the example of other
methods:
class Simple{
public static void main(String args[]){
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)
}
}
Output:SACHIN
sachin
Sachin
trim() method
//<b><i>Example of trim() method</i></b>
class Simple{
public static void main(String args[]){
Core Java
Sachin
class Simple{
public static void main(String args[]){
String s="Sachin";
System.out.println(s.startsWith("Sa"));//true
System.out.println(s.startsWith("n"));//false
}
}
Output:true
false
charAt() method
//<b><i>Example of charAt() method</i></b>
class Simple{
public static void main(String args[]){
String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
}
}
Output:S
h
length() method
//<b><i>Example of length() method</i></b>
Core Java
class Simple{
public static void main(String args[]){
String s="Sachin";
System.out.println(s.length());//6
}
}
Output:6
intern() method
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this String
object as determined by the equals(Object) method, then the string from the pool is returned.
Otherwise, this String object is added to the pool and a reference to this String object is
returned.
//<b><i>Example of length() method</i></b>
class Simple{
public static void main(String args[]){
StringBuffer class:
The StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class
is same as String except it is mutable i.e. it can be changed.
Core Java
Note: StringBuffer class is thread-safe i.e. multiple threads
cannot access it simultaneously .So it is safe and will result in an
order.
Commonly used Constructors of StringBuffer class:
1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified string.
3. StringBuffer(int capacity): creates an empty string buffer with the specified
capacity as length.
2. public synchronized StringBuffer insert(int offset, String s): is used to insert the
specified string with this string at the specified position. The insert() method is
overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
8. public char charAt(int index): is used to return the character at the specified
position.
9. public int length(): is used to return the length of the string i.e. total number of
characters.
10.
Core Java
3.
4. StringBuffer sb=new StringBuffer("Hello ");
5. sb.append("Java");//now original string is changed
6.
7. System.out.println(sb);//prints Hello Java
8. }
9. }
3.
4. StringBuffer sb=new StringBuffer("Hello ");
5. sb.insert(1,"Java");//now original string is changed
6.
7. System.out.println(sb);//prints HJavaello
8. }
9. }
Core Java
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello");
5. sb.replace(1,3,"Java");
6.
7. System.out.println(sb);//prints HJavalo
8. }
9. }
3.
4. StringBuffer sb=new StringBuffer("Hello");
5. sb.delete(1,3);
6.
7. System.out.println(sb);//prints Hlo
8. }
9. }
3.
4. StringBuffer sb=new StringBuffer("Hello");
5. sb.reverse();
6.
7. System.out.println(sb);//prints olleH
8. }
Core Java
9. }
3.
4. StringBuffer sb=new StringBuffer();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
9.
10.
11.
12.
13.
3.
4. StringBuffer sb=new StringBuffer();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
Core Java
9.
10.
11.
12.
13.
sb.ensureCapacity(10);//now no change
14.
System.out.println(sb.capacity());//now 34
15.
16.
sb.ensureCapacity(50);//now (34*2)+2
17.
System.out.println(sb.capacity());//now 70
18.
19.
20.
StringBuilder class:
The StringBuilder class is used to create mutable (modifiable) string. The StringBuilder class
is same as StringBuffer class except that it is non-synchronized. It is available since JDK1.5.
2. public StringBuilder insert(int offset, String s): is used to insert the specified string
with this string at the specified position. The insert() method is overloaded like
insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int,
double) etc.
4. public StringBuilder delete(int startIndex, int endIndex): is used to delete the string
Core Java
from specified startIndex and endIndex.
8. public char charAt(int index): is used to return the character at the specified
position.
9. public int length(): is used to return the length of the string i.e. total number of
characters.
10.
3.
4. StringBuilder sb=new StringBuilder("Hello ");
5. sb.append("Java");//now original string is changed
6.
7. System.out.println(sb);//prints Hello Java
8. }
9. }
3.
4. StringBuilder sb=new StringBuilder("Hello ");
Core Java
5. sb.insert(1,"Java");//now original string is changed
6.
7. System.out.println(sb);//prints HJavaello
8. }
9. }
3.
4. StringBuilder sb=new StringBuilder("Hello");
5. sb.replace(1,3,"Java");
6.
7. System.out.println(sb);//prints HJavalo
8. }
9. }
3.
4. StringBuilder sb=new StringBuilder("Hello");
5. sb.delete(1,3);
6.
7. System.out.println(sb);//prints Hlo
8. }
9. }
Core Java
1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder("Hello");
5. sb.reverse();
6.
7. System.out.println(sb);//prints olleH
8. }
9. }
3.
4. StringBuilder sb=new StringBuilder();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
9.
10.
11.
12.
13.
Core Java
3.
4. StringBuilder sb=new StringBuilder();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
9.
10.
11.
12.
13.
sb.ensureCapacity(10);//now no change
14.
System.out.println(sb.capacity());//now 34
15.
16.
sb.ensureCapacity(50);//now (34*2)+2
17.
System.out.println(sb.capacity());//now 70
18.
19.
20.
3.
4. public Employee(String pancardNumber){
5. this.pancardNumber=pancardNumber;
6. }
7.
8. public String getPancardNumber(){
9. return pancardNumber;
Core Java
10.
11.
12.
Core Java
public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");
Core Java
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output: 101 Raj lucknow
102 Vijay ghaziabad
StringTokenizer in Java
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way
to break string.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.
Description
StringTokenizer(String
str)
StringTokenizer(String
boolean
hasMoreTokens()
String nextToken()
String nextToken(String
delim)
boolean
hasMoreElements()
Description
Core Java
Object nextElement()
int countTokens()
Core Java
Generics in Java
The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.
Before generics, we can store any type of objects in collection i.e. non-generic. Now generics,
forces the java programmer to store specific type of objects.
Core Java
2. class Simple{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("rahul");
6. list.add("jai");
7. //list.add(32);//compile time error
8.
9. String s=list.get(1);//type casting is not required
10.
11.
12.
Iterator<String> itr=list.iterator();
13.
while(itr.hasNext()){
14.
System.out.println(itr.next());
15.
16.
17.
8.
9. //Now use Map.Entry for Set and Iterator
10.
Set<Map.Entry<Integer,String>> set=map.entrySet();
11.
12.
Iterator<Map.Entry<Integer,String>> itr=set.iterator();
13.
while(itr.hasNext()){
14.
Core Java
15.
System.out.println(e.getKey()+" "+e.getValue());
16.
17.
18.
}}
Output:1 vijay
2 ankit
4 umesh
Generic class
A class that can refer to any type is known as generic class. Here, we are using T type
parameter to create the generic class of specific type.
Lets see the simple example to create and use the generic class.
Creating generic class:
1. class MyGen<T>{
2. T obj;
3. void add(T obj){this.obj=obj;}
4. T get(){return obj;}
5. }
The T type indicates that it can refer to any type (like String, Integer, Employee etc.). The type
you specify for the class, will be used to store and retrieve the data.
Using generic class:
Lets see the code to use the generic class.
1. class UseGen{
2. public static void main(String args[]){
3. MyGen<Integer> m=new MyGen<Integer>();
4. m.add(2);
5. //m.add("vivek");//Compile time error
6. System.out.println(m.get());
7. }}
Output:2
Core Java
1.T - Type
2.E - Element
3.K - Key
4.N - Number
5.V - Value
6.S,U,V etc. - 2nd, 3rd, 4th types
Generic Method
Like generic class, we can create generic method that can accept any type of argument.
Lets see a simple example of java generic method to print array elements. We are using here
E to denote the element.
1. public class GenericMethodDemo{
2.
3.
4.
5.
System.out.println(element );
6.
7.
System.out.println();
8.
9.
10.
11.
12.
13.
14.
printArray( intArray );
15.
16.
17.
printArray( charArray );
18.
19.
}
}
Core Java
20
30
40
50
Printing Character Array
J
A
V
A
T
P
O
I
N
T
Simple Example
// Generic Class
class MyGen<T> {
T obj;
void add(T obj) {
this.obj = obj;
}
T get() {
return obj;
}
}
public class GenericTest {
// Generic Method
public static <E> void display(E[] elements) {
for (E e : elements) {
System.out.println(e);
}
}
// Generic Method
public static <E> void removeDuplicates(List<E> list) {
// REmove duplicate
Set<E> set = new HashSet<E>(list);
List<E> lis = new ArrayList<E>(set);
for (E element : lis) {
Core Java
}
System.out.println(element);
}
public static void main(String[] args) {
// Type safety: The method add(Object) belongs to the raw type List.
// References to generic type List<E> should be parameterized
List li = new ArrayList();
li.add("A");
li.add('B');
li.add(32);
li.add(12.23);
for (Object obj : li) {
System.out.println(obj);
}
List<String> list = new ArrayList<String>();
// list.add(1); // Compile Time Checking and shows error
list.add("A");
list.add("B");
list.add("B");
for (String str : list) {
System.out.println(str);
}
Integer[] intArray = {12, 23, 34};
String[] strArray = {"A", "G", "E"};
display(intArray);
removeDuplicates(list);
MyGen<String> a = new MyGen<String>();
a.add("Welcome");
System.out.println(a.get());
}
}
Output
A
B
32
12.23
A
B
B
12
23
34
A
B
Core Java
Welcome
Static Import:
The static import feature of Java 5 facilitate the java programmer to access any
static member of a class directly.
}
}
Output:Hello
Java
The import allows the java programmer to access classes of a package without
package qualification whereas the static import feature allows to access the static
members of a class without the class qualification.
The import provides accessibility to classes and interface whereas static import
provides accessibility to static members of the class.
Core Java
Enum
An enum is a data type which contains fixed set of constants. It can be used for days
of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and
SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The enum constants are
static and final implicitly. It is available from Java 5. Enums can be thought of as classes
that have fixed set of constants.
3.
4. public enum Season { WINTER, SPRING, SUMMER, FALL }
5.
6. public static void main(String[] args) {
7. for (Season s : Season.values())
8. System.out.println(s);
9.
10.
}}
11.
Output:WINTER
SPRING
SUMMER
FALL
Core Java
The values() method returns an array containing all the values of the enum.
5.
6.
super(s, i);
}
7.
8.
9.
10.
11.
return (EnumExample1$Season[])$VALUES.clone();
}
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
static
25.
26.
27.
28.
Core Java
29.
30.
31.
32.
});
33.
34.
35.
Defining enum:
The enum can be defined within or outside the class because it is
similar to a class.
3.
4. class EnumExample2{
5. public static void main(String[] args) {
6.
7. Season s=Season.WINTER;
8. System.out.println(s);
9.
10.
}}
11.
Output:WINTER
3.
4. public static void main(String[] args) {
5. Season s=Season.WINTER;//enum type is required to access WINTER
6. System.out.println(s);
7.
8. }}
Core Java
9.
Output:WINTER
4.
5. private int value;
6. private Season(int value){
7. this.value=value;
8. }
9. }
10.
11.
12.
System.out.println(s+" "+s.value);
13.
14.
}}
15.
Output:WINTER 5
SPRING 10
SUMMER 15
FALL 20
Core Java
6. }
7. }
8.
3.
4.
5.
6.
7.
return (Season[])$VALUES.clone();
}
8.
9.
10.
11.
12.
13.
14.
15.
16.
super(s, i);
17.
value = j;
18.
19.
20.
21.
22.
23.
24.
25.
static
26.
27.
28.
Core Java
29.
30.
WINTER, SUMMER
31.
});
32.
33.
}
}
3.
4. public static void main(String args[]){
5.
6. Day day=Day.MONDAY;
7.
8. switch(day){
9. case SUNDAY:
10.
System.out.println("sunday");
11.
break;
12.
case MONDAY:
13.
System.out.println("monday");
14.
break;
15.
default:
16.
System.out.println("other day");
Core Java
17.
18.
19.
}}
20.
int a=50;
5.
6.
7.
Integer a3=5;//Boxing
8.
9.
System.out.println(a2+" "+a3);
10.
11.
12.
Output:50 5
1.
2. class UnboxingExample1{
Core Java
4.
5.
int a=i;
6.
7.
System.out.println(a);
8. }
9. }
10.
Output:50
1.
2. class UnboxingExample1{
5.
6.
if(i<100){
7.
System.out.println(i);
8.
//unboxing internally
9. }
10.
11.
Output:50
Assertion (Java 4)
J2SE 5 Features
The important features of J2SE 5 are generics and assertions. Others are auto-boxing, enum,
var-args, static import, for-each loop (enhanced for loop etc.
Core Java
Varargs (Java 5)
Enum (Java 5)
Annotation (Java 5)
Generics (Java 5)
JavaSE 6 Features
The important feature of JavaSE 6 is premain method (also known as instrumentation).
JavaSE 7 Features
The important features of JavaSE 7 are try with resource, catching multiple exceptions etc.
Advantage of Varargs:
Core Java
Syntax of varargs:
The varargs uses ellipsis i.e. three dots after the data type. Syntax is as
follows:
return_type method_name(data_type... variableName){}
display();//zero argument
display("my","name","is","varargs");//four arguments
}
}
Core Java
}
display();//zero argument
display("hello");//one argument
display("my","name","is","varargs");//four arguments
}
}
Core Java
static void display(int num, String... values){
System.out.println("number is "+num);
for(String s:values){
System.out.println(s);
}
}
display(500,"hello");//one argument
display(1000,"my","name","is","varargs");//four arguments
}
}
Output:number is 500
hello
number is 1000
my
name
is
varargs
Example
public class VarArgsTest {
//Array of String in varargs
public static void retrive(String... str) {
Core Java
public static void main(String[] args) {
String [] str = {"A", "B", "C"};
List<String> li = new ArrayList<String>();
li.add("A");
li.add("B");
li.add("C");
retrive(str);
getData(li);
//handle exception
}finally{
Since JDK 7, a new try-with-resources approach is introduced. When a try block is end, it will close
or release your opened file automatically.
try(open file or resource here){
//...
}
Core Java
Core Java
2. JDK 7
In JDK7, finally is no longer required. The file will be closed automatically after try block.
package com.mkyong.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Example2 {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new
FileReader("C:\\testing.txt")))
{
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Core Java
case "Wednesday":
case "Thursday":
typeOfDay = "Midweek";
break;
case "Friday":
typeOfDay = "End of work week";
break;
case "Saturday":
case "Sunday":
typeOfDay = "Weekend";
break;
default:
throw new IllegalArgumentException("Invalid day of the
week: " + dayOfWeekArg);
}
return typeOfDay;
}
The switch statement compares the String object in its expression with the expressions
associated with each case label as if it were using the String.equals method; consequently,
the comparison of String objects in switch statements is case sensitive. The Java compiler
generates generally more efficient bytecode from switch statements that use String objects
than from chained if-then-else statement
With Java 7:
String color = "red";
switch (color) {
case "red":
Core Java
System.out.println("Color is Red");
break;
case "green":
System.out.println("Color is Green");
break;
default:
System.out.println("Color not found");
}
The switch statement when used with a String uses the equals() method to compare the
given expression to each value in the case statement and is therefore case-sensitive and will
throw a NullPointerException if the expression is null. It is a small but useful feature which not
only helps us write more readable code but the compiler will likely generate more efficient
bytecode as compared to the if-then-else statement.
1.If in a try block we need to handle multiple exceptions then we need to write exception
handler for each type of exception.
2.We can combine the multiple exceptions in catch block using Pipe (|)
Operator.
catch (IOException|SQLException ex) {
System.out.println("Exception thrown");
throw ex;
}
above single catch block can handle IO as well as SQL exceptions. So it is better to
use Pipe Operator to handle multiple exceptions instead of writing individual catch block for
each exception.
Core Java
Binary Literals in Java Java 7 Feature
As you all know that we can write integral types (byte, short, int, and long)
in Binary and Hexadecimal formats but from Java 7 onwards we can write
these numbers in binary format also.
Using this feature will remove this transformation and chances of error will
be less in this conversion.
Also code using bitwise operations will be more readable with this feature.
package com.journaldev.util;
public class Java7Literals {
public static void main(String[] args) {
int i=0b0111;
byte b=(byte) 0b0111;
long l=(long) 0B0111L;
System.out.println("i="+i);
System.out.println("b="+b);
System.out.println("l="+l);
}
}
Output of the above program is:i=7
b=7
l=7
x=7
Core Java
underscores between digits of any numeric literal like int, byte, short, float, long,
double. Using underscores in numeric literals will allow you to divide them in
groups for better readability.
Lets see underscores in numeric literals in action:
public class UnderscoreNumericLiterals {
public static void main(String[] args) {
long ccNumber = 1234_5678_9012_3456L;
long ssn = 999_99_9999L;
float pi = 3.14_15F;
long hexadecimalBytes = 0xFF_EC_DE_5E;
long hexadecimalWords = 0xCAFE_BABE;
long maxOfLong = 0x7fff_ffff_ffff_ffffL;
byte byteInBinary = 0b0010_0101;
long longInBinary = 0b11010010_01101001_10010100_10010010;
int add = 12_3 + 3_2_1;
System.out.println("ccNumber="+ccNumber);
System.out.println("ssn="+ssn);
System.out.println("pi="+pi);
System.out.println("hexadecimalBytes="+hexadecimalBytes);
System.out.println("hexadecimalWords="+hexadecimalWords);
System.out.println("maxOfLong="+maxOfLong);
System.out.println("byteInBinary="+byteInBinary);
System.out.println("longInBinary="+longInBinary);
System.out.println("add="+add);
}
}
Output
ccNumber=1234567890123456
ssn=999999999
pi=3.1415
hexadecimalBytes=-1253794
hexadecimalWords=-889275714
maxOfLong=9223372036854775807
byteInBinary=37
longInBinary=-764832622
add=444
Core Java
You cant put underscores next to decimal places, L/F suffix or radix
prefix. So 3._14, 110_L, 0x_123 are invalid and will cause compilation error.
You cant put underscores at the end of literal. So 123_ is invalid and
cause compile time error.
When you place underscore in the front of a numeric literal, its treated as