Вы находитесь на странице: 1из 100

Java Hungry

2/5/2016

JAVA HUNGRY
Java developers tutorials and coding.
Search this blog...
HOME
SCJP

STRING
THREADS

COLLECTIONS

Search

INTERVIEW

BEST JAVA BOOKS

INTERVIEW TIPS

DATA-STRUCTURES

JAVA CODING PROGRAM

MORE JAVA TOPICS

5 Ways Of String Concatenation In Java


In this tutorial, we will discuss about string concatenation in java.
Although there can be number of ways for concatenating strings, we will
discuss 5 most important and widely used . Take a look at below
example of how string concatenation works:

Secure Connection Failed

The connection to the server was reset while the page w

Input: Hello and World


Output: HelloWorld
Input: 1234 and 5678
Output: 12345678

The page you are trying to view cannot be shown b


Please contact the website owners to inform them

Try Again
Report this error

Read Also : 5 Ways to Reverse a String in Java with Example


Points to Keep in Mind Before attempting the Solution :
1. String is immutable so once it is created in memory we will not be able to modify it rather than assigning new
String. StringBuffer and StringBuilder are mutable, so once it is created , modifications can be done later.
2. The first argument of String.join() method is delimiter used to join strings and there can any number of string
arguments starting from second argument.
Read more

5 Difference Between Sleep And Wait Method With Example


Today we will share the difference between sleep and wait method in
java . This is one of the most popular question of Threads topic for the
java beginners. Both sleep() and wait() methods are most widely used
methods in Thread programming in Java.

Secure Connection Failed

The connection to the server was reset while the page w

Read Also : Difference between implements Runnable and extends


Thread in Java

The page you are trying to view cannot be shown b


Please contact the website owners to inform them

Try Again

Difference between Sleep and Wait method in Java

Report this error

1. Class belongs : The wait() method belongs to java.lang.Object


class, thus can be called on any Object. The sleep() method belongs to
java.lang.Thread class, thus can be called on Threads.
2. Context : The wait() method can only be called from Synchronized context i.e. using synchronized block or
synchronized method. The sleep() method can be called from any context.
Read more

http://javahungry.blogspot.com/search?updated-max=2015-11-28T04%3A11%3A00-05%3A00&max-results=2#PageNo=2

1 / 100

Java Hungry

2/5/2016

Previous Page

3 ... 64

Next Page

Secure Connection Failed


The connection to the server was reset while the page was loading.
The page you are trying to view cannot be shown because the authenticity of the received data could not be verified.
Please contact the website owners to inform them of this problem.

Try Again
Report this error
Reporting the address and certificate information for
web!
Automatically report errors in the future
Learn more Report
Advanced

Try again Sending report

uses security technology that is outdated and vulnerable to attack. An attacker could easily reveal information which you thought to be
safe.
(Not secure) Try loading using outdated security

WHATS HOT
Difference between Arraylist and Vector : Core Java Interview Collection Question

Best Books for Learning Java

Amazon Interview Question : First Non repeated character in String

Count total number of times each alphabet appears in the string java program code with example

Java 8 new features : Lambda expressions , optional class , Defender methods with examples

http://javahungry.blogspot.com/search?updated-max=2015-11-28T04%3A11%3A00-05%3A00&max-results=2#PageNo=2

2 / 100

Java Hungry

2/5/2016

Javahungry's photo.

Javahungry
Like Page 2.1k likes

Subscribe for Our Newsletter

POPULAR POSTS
Java Interview Questions

Top 50 Java Collections Interview Questions and Answers

What Makes You Stand out from the Crowd

Threads , Lifecycle Explained with Example

Count number of words in the String with Example : Java Program Code

Return to Top
Java Hungry Copyright 2016 All Rights Reserved. Designed by studiopress

http://javahungry.blogspot.com/search?updated-max=2015-11-28T04%3A11%3A00-05%3A00&max-results=2#PageNo=2

3 / 100

5 Difference between Iterator and ListIterator in Java with Example | Java Hungry

2/5/2016

JAVA HUNGRY
Java developers tutorials and coding.
Search this blog...
HOME
SCJP

STRING
THREADS

COLLECTIONS

Search

INTERVIEW

BEST JAVA BOOKS

INTERVIEW TIPS

DATA-STRUCTURES

JAVA CODING PROGRAM

MORE JAVA TOPICS

5 Difference Between Iterator And ListIterator In Java With Example


In this tutorial we will learn about the difference between Iterator and
ListIterator . We will also look at the examples of Iterator and ListIterator
one by one. We have already discussed different type of iterators i.e
fail-fast iterator and fail-safe iterator.

Secure Connection Failed

The connection to the server was reset while the page w

Read Also : How LinkedHashMap works Internally in Java

The page you are trying to view cannot be shown b


Please contact the website owners to inform them

Try Again

Difference between Iterator and ListIterator in Java with Example Report this error
1. Traversal Direction : ListIterator allows the programmers to iterate
the list objects in both directions i.e forward as well as backward
direction using previous() and next() method.
Iterator can be used to iterate the list,map and set object in one direction i.e forward.
2. Set and Map implemented Objects Traversal : ListIterator can be used to traverse List object only . But
Iterator can be used to traverse Map, List and Set implemented objects.
for example
// ListIterator object is created
ListIterator listIteratorObject = List.listIterator();
// Iterator object is created
Iterator iteratorObject = List.iterator();
3. Add or Set operation at any index : According to ListIterator Oracle docs,
ListIterator can modify the list during iteration using add(E e) , remove() or set(E e).
Iterator can not add the element during traversal but they can remove the element from the underlying collection
during the iteration as they only consist of remove() method. There is no add(E e) and set(E e) method in
Iterator.
4. Determine Iterator's current position : ListIterator can obtain the iterator's current position in the list.
Iterator's current position during traversal can not be determined using Iterator.
5. Retrieve Index of the element : ListIterator can obtain the index of the elements using previousIndex(E e)
or nextIndex(E e) methods. We can not obtain the index using Iterator as there is no such methods present.
Example of Iterator and ListIterator
import java.util.Iterator;
import java.util.ListIterator;
http://javahungry.blogspot.com/2015/08/difference-between-iterator-and-listiterator-with-example.html

4 / 100

5 Difference between Iterator and ListIterator in Java with Example | Java Hungry

2/5/2016

public class IteratorListIteratorExample {


public static void main(String[] args) {

List listObject = new ArrayList();


listObject.add("Alive is awesome");
listObject.add("Love yourself");
ListIterator listIteratorObject = listObject.listIterator();
System.out.println("ListIterator object output in forward direction:");
System.out.println("");
while( listIteratorObject.hasNext() )
{
System.out.println(listIteratorObject.next());
}
System.out.println("ListIterator object output in backward direction:");
System.out.println("");
while( listIteratorObject.hasPrevious() )
{
System.out.println(listIteratorObject.previous());
}
List iteratorListObject = new ArrayList();
iteratorListObject.add("Facebook");
iteratorListObject.add("Google");
iteratorListObject.add("Apple");
Iterator javaHungryIterator = iteratorListObject.iterator();
System.out.println("Iterator object output in forward direction:");
while( javaHungryIterator.hasNext() )
{
System.out.println(javaHungryIterator.next());
}
}
}
Output :
ListIterator object output in forward direction:
Alive is awesome
Love yourself
ListIterator object output in backward direction:
Love yourself
Alive is awesome
Iterator object output in forward direction:
Facebook
Google
Apple

http://javahungry.blogspot.com/2015/08/difference-between-iterator-and-listiterator-with-example.html

5 / 100

5 Difference between Iterator and ListIterator in Java with Example | Java Hungry

2/5/2016

Similarities between Iterator and ListIterator in Java


1. Interfaces : Both Iterator and ListIterator are interfaces . ListIterator extends Iterator interface.
2. Collection Framework : Both Iterator and ListIterator are member
of the Java Collection Framework.
3. Traversal : Both are used to iterate over the collection of objects .
4. Interfaces added to jdk : Both interfaces are added to the jdk in
java 1.2

Recap : Difference between Iterator and ListIterator in Java with Example


ListIterator

Iterator

Traversal Direction

Both , forward and backward Forward

Objects traversal

List only

Map, Set and List

Add and Set operations Allows both operations

Not possible

Iterator's current position Yes , can be determined

Not possible.

Retrieve Index

Not possible

Yes

In case you have any questions regarding the difference between Iterator and ListIterator in Java with example ,
please feel free to mention in the comments.

About The Author


Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry

Share

You might also like


Count number of words in the String with Example : Java Program Code
5 Must Know Algorithm Problem Solving Techniques or Approaches for Software Programmer
Why String is final or immutable in Java with Example
Count total number of times each alphabet appears in the string java program code with example
Recommended by

http://javahungry.blogspot.com/2015/08/difference-between-iterator-and-listiterator-with-example.html

6 / 100

5 Difference between Iterator and ListIterator in Java with Example | Java Hungry

2/5/2016

WHATS HOT
Difference between Arraylist and Vector : Core Java Interview Collection Question

Best Books for Learning Java

Amazon Interview Question : First Non repeated character in String

Count total number of times each alphabet appears in the string java program code with example

Java 8 new features : Lambda expressions , optional class , Defender methods with examples

http://javahungry.blogspot.com/2015/08/difference-between-iterator-and-listiterator-with-example.html

7 / 100

5 Difference between Iterator and ListIterator in Java with Example | Java Hungry

2/5/2016

Subscribe for Our Newsletter

POPULAR POSTS
Java Interview Questions

Top 50 Java Collections Interview Questions and Answers

What Makes You Stand out from the Crowd

Threads , Lifecycle Explained with Example

Count number of words in the String with Example : Java Program Code

Return to Top
Java Hungry Copyright 2016 All Rights Reserved. Designed by studiopress

http://javahungry.blogspot.com/2015/08/difference-between-iterator-and-listiterator-with-example.html

8 / 100

5 ways to Reverse a String in Java with Example | Java Hungry

2/5/2016

JAVA HUNGRY
Java developers tutorials and coding.
Search this blog...
HOME
SCJP

STRING
THREADS

COLLECTIONS

Search

INTERVIEW

BEST JAVA BOOKS

INTERVIEW TIPS

DATA-STRUCTURES

JAVA CODING PROGRAM

MORE JAVA TOPICS

5 Ways To Reverse A String In Java With Example

In this tutorial we will discuss how to reverse a string in java . Although


there are many ways to get the solution but we are sharing 5 different
ways to reverse a string. This question is frequently asked in the
technical interview of java.This question is easy , but please mark this
The connection to the server was reset while the page w
question in your to do list before attending any technical interview in
java. First we will understand the question by writing example.
The page you are trying to view cannot be shown b

Secure Connection Failed

Input : Alive is awesome


Output: emosewa si evilA
Input : Be in present
Output : tneserp ni eB

Please contact the website owners to inform them

Try Again
Report this error

Read Also : Difference between String , StringBuilder and StringBuffer


Points to Keep in Mind Before attempting the Solution:
1. String class in java do not have reverse() method , StringBuilder class does have built in reverse() method.
2. StringBuilder class do not have toCharArray() method , while String class does have toCharArray() method.
Pseudo Code for Reverse String Method 1:
1. The user will input the string to be reversed.
2. First we will convert String to character array by using the built in java String class method toCharArray().
3. Then , we will scan the string from end to start, and print the character one by one.
import java.io.*;
import java.util.*;
public class reverseString {
public static void main(String[] args) {
String input="";
System.out.println("Enter the input string");
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
input = br.readLine();
char[] try1= input.toCharArray();
for (int i=try1.length-1;i>=0;i--)
System.out.print(try1[i]);
}
catch (IOException e) {
e.printStackTrace();
}
}}
http://javahungry.blogspot.com/2014/12/5-ways-to-reverse-string-in-java-with-example.html

9 / 100

5 ways to Reverse a String in Java with Example | Java Hungry

2/5/2016

Pseudo Code for Reverse String Method 2:


1. In the second method , we will use the built in reverse() method of the StringBuilder class ,.
Note : String class does not have reverse() method . So we need to convert the input string to StringBuilder ,
which is achieved by using the append method of the StringBuilder.
2. After that print out the characters of the reversed string by scanning from the first till the last index.
import java.io.*;
import java.util.*;
public class reverseString {
public static void main(String[] args) {
String input="AliveisAwesome";
StringBuilder input1 = new StringBuilder();
input1.append(input);
input1=input1.reverse();
for (int i=0;i<input1.length();i++)
System.out.print(input1.charAt(i));
}}

Pseudo Code for Reverse String Method 3:


1. Convert the input string into character array by using the toCharArray() built in method of the String Class .
2. In this method we will scan the character array from both sides , that is from the start index (left) as well as
from last index(right) simultaneously.
3. Set the left index equal to 0 and right index equal to the length of the string -1.
4. Swap the characters of the start index scanning with the last index scanning one by one .After that increase
the left index by 1 (left++) and decrease the right by 1 i.e (right--) to move on to the next characters in the
character array .
5. Continue till left is less than or equal to the right .
import java.io.*;
import java.util.*;
public class reverseString {
public static void main(String[] args) {
String input = "Be in present";
char[] temparray= input.toCharArray();
int left,right=0;
right=temparray.length-1;
for (left=0; left < right ; left++ ,right--)
{
// Swap values of left and right
char temp = temparray[left];
temparray[left] = temparray[right];
temparray[right]=temp;
}
for (char c : temparray)
System.out.print(c);
System.out.println();
}}
Pseudo Code for Reverse String Method 4:
http://javahungry.blogspot.com/2014/12/5-ways-to-reverse-string-in-java-with-example.html

10 / 100

5 ways to Reverse a String in Java with Example | Java Hungry

2/5/2016

1. Convert the input string into the character array by using toCharArray() built in method.

2. Then add the characters of the array into the LinkedList object . We used LinkedList because it maintains the
insertion order of the input values.
3. Java also has built in reverse() method for the Collections class . Since Collections class reverse() method
takes a list object , to reverse the list , we will pass the LinkedList object which is a type of list of characters.
4. We will create the ListIterator object by using the listIterator() method on the LinkedList object.
ListIterator object is used to iterate over the list.
5. ListIterator object will help us to iterate over the reversed list and print it one by one to the output screen.
import java.io.*;
import java.util.*;
public class reverseString {
public static void main(String[] args) {
String input = "Be in present";
char[] hello=input.toCharArray();
List<Character> trial1= new LinkedList<>();
for(char c: hello)
trial1.add(c);
Collections.reverse(trial1);
ListIterator li = trial1.listIterator();
while(li.hasNext())
{System.out.print(li.next());}
}}
Pseudo Code for Reverse String Method 5 :
1. The last method is converting string into bytes . getBytes() method is used to convert the input string into
bytes[].
2. Then we will create a temporary byte[] of length equal to the length of the input string.
3. We will store the bytes(which we get by using getBytes() method) in reverse order into the temporary byte[] .
package ctci;
import java.io.*;
import java.util.*;
public class reverseString {
public static void main(String[] args) {
String input = "Be in present";
byte [] strAsByteArray = input.getBytes();
byte [] result = new byte [strAsByteArray.length];
for(int i = 0; i<strAsByteArray.length; i++){
result[i] = strAsByteArray[strAsByteArray.length-i-1];
}
System.out.println( new String(result));
}}

http://javahungry.blogspot.com/2014/12/5-ways-to-reverse-string-in-java-with-example.html

11 / 100

5 ways to Reverse a String in Java with Example | Java Hungry

2/5/2016

Read Also : 5 ways to Determine if String has all Unique Characters


Please mention in the comments in case if you know any way to reverse the string other then the above
mentioned ways or in case you have any doubts.

About The Author


Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry

You might also like


How to Reverse a String without using reverse built in method or recursion in Java : Source code with example
Square Root Code in Java : Simple Gui with Example
5 Difference between ArrayList and LinkedList in Java with Example
Count total number of times each alphabet appears in the string java program code with example
Recommended by

http://javahungry.blogspot.com/2014/12/5-ways-to-reverse-string-in-java-with-example.html

12 / 100

5 ways to Reverse a String in Java with Example | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2014/12/5-ways-to-reverse-string-in-java-with-example.html

13 / 100

5 ways to Reverse a String in Java with Example | Java Hungry

Share

2/5/2016

http://javahungry.blogspot.com/2014/12/5-ways-to-reverse-string-in-java-with-example.html

14 / 100

5 ways to Reverse a String in Java with Example | Java Hungry

2/5/2016

WHATS HOT
Difference between Arraylist and Vector : Core Java Interview Collection Question

Best Books for Learning Java

Amazon Interview Question : First Non repeated character in String

Count total number of times each alphabet appears in the string java program code with example

Java 8 new features : Lambda expressions , optional class , Defender methods with examples

Subscribe for Our Newsletter

POPULAR POSTS
Java Interview Questions

Top 50 Java Collections Interview Questions and Answers

What Makes You Stand out from the Crowd

Threads , Lifecycle Explained with Example

Count number of words in the String with Example : Java Program Code

Return to Top
Java Hungry Copyright 2016 All Rights Reserved. Designed by studiopress

http://javahungry.blogspot.com/2014/12/5-ways-to-reverse-string-in-java-with-example.html

15 / 100

5 Ways to Determine if String has all Unique Characters : Java Code with Example | Java Hungry

2/5/2016

JAVA HUNGRY
Java developers tutorials and coding.
Search this blog...
HOME
SCJP

STRING
THREADS

COLLECTIONS

Search

INTERVIEW

BEST JAVA BOOKS

INTERVIEW TIPS

DATA-STRUCTURES

JAVA CODING PROGRAM

MORE JAVA TOPICS

5 Ways To Determine If String Has All Unique Characters : Java


Code With Example
In the technical interviews ,you may come across this question many
times ,determine whether a string has all unique characters or not .
Before moving to the solution , here in this question we have taken
one assumption that is all the characters in the string are ASCII
characters.
For those who are not familiar with ASCII characters.
ASCII abbreviation is known as American Standard Code for
Information Interchange.
In simple words it is just the number representation of characters.
So , First understand the question by writing examples :
Input : Alive is awesome
Output : false
Input : Live present moment
Output : false
Input : Alive swum
Output: true

PseudoCode for Method 1 :


1. Create a HashSet object.
2. Scan the whole string, and add each character one by one to the HashSet object
3. If the add object returns true then continue
else return false

Method 1
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
public class uniquechar {
public static void main (String args[])
{
boolean result=false;
String inputstring="Alve i@wsom";
System.out.println(inputstring);
http://javahungry.blogspot.com/2014/11/string-has-all-unique-characters-java-example.html

16 / 100

5 Ways to Determine if String has all Unique Characters : Java Code with Example | Java Hungry

2/5/2016

HashSet < Character> uniquecharset= new HashSet();


for(int i=0;i < inputstring.length();i++)
{
result=uniquecharset.add(inputstring.charAt(i));
if (result == false)
break;
}
System.out.println(result); }
}
PseudoCode for Method 2 :
1. Scan the input string , take each character one by one and set count flag to 0.
2. For each character in the inputstring ,Rescan the inputstring and compare the character with each character
appear in the inputstring
3. If equal then increase the count by 1
else continue the loop
4. If count flag value is greater than 1 then return false
else return true
Method 2
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
public class UniqueChar2 {
public static void main (String args[])
{
boolean result=false;
String inputstring="Alive is awesome";
System.out.println("String method 2 answer "+ method2(inputstring));
}
public static boolean method2(String input)
{
for(int i=0; i < input.length();i++)
{
char charcterofinputstring=input.charAt(i);
int count=0;
for(int j=i; j < input.length();j++)
{
if (charcterofinputstring==input.charAt(j))
count++;
}
if(count > 1)
return false;
}
return true;
}
}

PseudoCode for Method 3:


1. indexOf() returns the index of first occurence of the character or else return -1. So , here we are creating an
arraylist object.
http://javahungry.blogspot.com/2014/11/string-has-all-unique-characters-java-example.html

17 / 100

5 Ways to Determine if String has all Unique Characters : Java Code with Example | Java Hungry

2/5/2016

2. Scan the inputstring and add the index of each character to the arraylist object.
3. Sort the arraylist object.
4. Compare the values of each adjacent positions of arraylist object
if equal then return false
else continue scanning the arraylist
5. return true

Method 3
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
public class UniqueChar3 {
public static void main (String args[])
{
boolean result=false;
String inputstring="Alive is awesome";
System.out.println("String method 3 answer "+ method3(inputstring));
}
public static boolean method3(String input)
{
ArrayList ar= new ArrayList();
for (int i=0; i < input.length() ; i++ )
{
int j = input.indexOf(input.charAt(i));
ar.add(j);
}
Collections.sort(ar);
for (int i=0;i < (ar.size()-1);i++)
{
if (ar.get(i) == ar.get(i+1))
return false;
}
return true;
}
}
PseudoCode for Method 4 :
1. For this method we need to know about two inbuilt functions in java , indexOf() which returns the index of
first occurence of the character in the string , while second function lastIndexOf() returns the index of last
occurence of the character in the given string.
2. First , we convert the given inputstring into characterarray by using toCharArray() function.
3. Calculate the indexOf() and lastIndexOf() for each character in the given inputstring
4. If both are equal then continue and make result= true
else set flag result = false
5. Return result
Method 4
import java.util.ArrayList;
http://javahungry.blogspot.com/2014/11/string-has-all-unique-characters-java-example.html

18 / 100

5 Ways to Determine if String has all Unique Characters : Java Code with Example | Java Hungry

2/5/2016

import java.util.Collections;
import java.util.HashSet;
public class UniqueChar4 {
public static void main (String args[])
{
boolean result=false;
String inputstring="Alive is awesome";
System.out.println("String method 4 answer "+ method4(inputstring));
}
public static boolean method4(String input)
{
boolean result=false;
for (char ch: input.toCharArray())
{
if(input.indexOf(ch)== input.lastIndexOf(ch))
result= true;
else
{
result=false;
break;
}
}
return result;
}
}

Method 5
Most memory efficient answer
Please mention in the comments what is the time complexity of each of the above method and why ?
Also write in comments if you have any other method to find all the unique characters in string.

About The Author


Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry

3 Comments
Recommend

Java Hungry
Share

You might also like


6 Difference between HashMap and HashTable : Popular Interview Question in Java with Example
Why String is final or immutable in Java with Example
Difference between HashSet and TreeSet : Java Collections Interview Question
Remove Specific Characters from String with Example
http://javahungry.blogspot.com/2014/11/string-has-all-unique-characters-java-example.html

19 / 100

5 Ways to Determine if String has all Unique Characters : Java Code with Example | Java Hungry

2/5/2016

Recommended by

http://javahungry.blogspot.com/2014/11/string-has-all-unique-characters-java-example.html

20 / 100

5 Ways to Determine if String has all Unique Characters : Java Code with Example | Java Hungry

2/5/2016

WHATS HOT
Difference between Arraylist and Vector : Core Java Interview Collection Question

Best Books for Learning Java

Amazon Interview Question : First Non repeated character in String

Count total number of times each alphabet appears in the string java program code with example

Java 8 new features : Lambda expressions , optional class , Defender methods with examples

Subscribe for Our Newsletter

POPULAR POSTS
Java Interview Questions

Top 50 Java Collections Interview Questions and Answers

What Makes You Stand out from the Crowd

Threads , Lifecycle Explained with Example

Count number of words in the String with Example : Java Program Code

Return to Top
Java Hungry Copyright 2016 All Rights Reserved. Designed by studiopress

http://javahungry.blogspot.com/2014/11/string-has-all-unique-characters-java-example.html

21 / 100

Difference Between String , StringBuilder and StringBuffer Classes with Example : Java | Java Hungry

2/5/2016

JAVA HUNGRY
Java developers tutorials and coding.
Search this blog...
HOME
SCJP

STRING
THREADS

COLLECTIONS

Search

INTERVIEW

BEST JAVA BOOKS

INTERVIEW TIPS

DATA-STRUCTURES

JAVA CODING PROGRAM

MORE JAVA TOPICS

Difference Between String , StringBuilder And StringBuffer Classes


With Example : Java
Today we are going to understand the difference between String ,
StringBuilder and StringBuffer . As you will find that there are minor
differences between the above mentioned classes.

Secure Connection Failed

String

The connection to the server was reset while the page w

The page you are trying to view cannot be shown b

String is immutable ( once created can not be changed )object . The


Please contact the website owners to inform them
object created as a String is stored in the Constant String Pool .
Every immutable object in Java is thread safe ,that implies String is also Try Again
thread safe . String can not be used by two threads simultaneously.
Report this error
String once assigned can not be changed.
String demo = " hello " ;
// The above object is stored in constant string pool and its value can not be modified.
demo="Bye" ; //new "Bye" string is created in constant pool and referenced by the demo variable
// "hello" string still exists in string constant pool and its value is not overrided but we lost reference to the
"hello"string
StringBuffer
StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer
is stored in the heap . StringBuffer has the same methods as the StringBuilder , but each method in
StringBuffer is synchronized that is StringBuffer is thread safe .
Due to this it does not allow two threads to simultaneously access the same method . Each method can be
accessed by one thread at a time .
But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe
property . Thus StringBuilder is faster than the StringBuffer when calling the same methods of each class.
StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its a most
common interview question ,the differences between the above classes .
String Buffer can be converted to the string by using
toString() method.
StringBuffer demo1 = new StringBuffer("Hello") ;
// The above object stored in heap and its value can be changed .
demo1=new StringBuffer("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuffer
StringBuilder
StringBuilder is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The
main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe.
http://javahungry.blogspot.com/2013/06/difference-between-string-stringbuilder.html

22 / 100

Difference Between String , StringBuilder and StringBuffer Classes with Example : Java | Java Hungry

2/5/2016

StringBuilder is fast as it is not thread safe .


StringBuilder demo2= new StringBuilder("Hello");
// The above object too is stored in the heap and its value can be modified
demo2=new StringBuilder("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuilder
---------------------------------------------------------------------------------String
StringBuffer
StringBuilder
---------------------------------------------------------------------------------Storage Area | Constant String Pool
Heap
Heap
Modifiable | No (immutable)
Yes( mutable )
Yes( mutable )
Thread Safe |
Yes
Yes
No
Performance |
Fast
Very slow
Fast
----------------------------------------------------------------------------------Please mention in the comments in case you have any doubts related to the post: difference between string,
stringbuffer and stringbuilder.

About The Author


Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry

You might also like


5 ways of String Concatenation in Java
8 Difference between HashMap and TreeMap with Example
Count total number of times each alphabet appears in the string java program code with example
Palindrome String Verification Example : console based java program
Recommended by

http://javahungry.blogspot.com/2013/06/difference-between-string-stringbuilder.html

23 / 100

Difference Between String , StringBuilder and StringBuffer Classes with Example : Java | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2013/06/difference-between-string-stringbuilder.html

24 / 100

Difference Between String , StringBuilder and StringBuffer Classes with Example : Java | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2013/06/difference-between-string-stringbuilder.html

25 / 100

Difference Between String , StringBuilder and StringBuffer Classes with Example : Java | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2013/06/difference-between-string-stringbuilder.html

26 / 100

Difference Between String , StringBuilder and StringBuffer Classes with Example : Java | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2013/06/difference-between-string-stringbuilder.html

27 / 100

Difference Between String , StringBuilder and StringBuffer Classes with Example : Java | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2013/06/difference-between-string-stringbuilder.html

28 / 100

Difference Between String , StringBuilder and StringBuffer Classes with Example : Java | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2013/06/difference-between-string-stringbuilder.html

29 / 100

Difference Between String , StringBuilder and StringBuffer Classes with Example : Java | Java Hungry

2/5/2016

WHATS HOT
Difference between Arraylist and Vector : Core Java Interview Collection Question

Best Books for Learning Java

Amazon Interview Question : First Non repeated character in String

Count total number of times each alphabet appears in the string java program code with example

Java 8 new features : Lambda expressions , optional class , Defender methods with examples

Subscribe for Our Newsletter

http://javahungry.blogspot.com/2013/06/difference-between-string-stringbuilder.html

30 / 100

Difference Between String , StringBuilder and StringBuffer Classes with Example : Java | Java Hungry

2/5/2016

POPULAR POSTS
Java Interview Questions

Top 50 Java Collections Interview Questions and Answers

What Makes You Stand out from the Crowd

Threads , Lifecycle Explained with Example

Count number of words in the String with Example : Java Program Code

Return to Top
Java Hungry Copyright 2016 All Rights Reserved. Designed by studiopress

http://javahungry.blogspot.com/2013/06/difference-between-string-stringbuilder.html

31 / 100

Constructor:Overloading ,Examples ,Basics, Rules,Important Points | Java Hungry

2/5/2016

JAVA HUNGRY
Java developers tutorials and coding.
Search this blog...
HOME
SCJP

STRING
THREADS

COLLECTIONS

Search

INTERVIEW

BEST JAVA BOOKS

INTERVIEW TIPS

DATA-STRUCTURES

JAVA CODING PROGRAM

MORE JAVA TOPICS

Constructor:Overloading ,Examples ,Basics, Rules,Important Points


Constructor is one of the most common term in java . Yet it is so big in
details and meaning that we need to write an entirely new post for it .

Secure Connection Failed

What is Constructor ?

The connection to the server was reset while the page w

Constructor are used to create the objects . new keyword always call
constructor of the class in the java code .

The page you are trying to view cannot be shown b


Please contact the website owners to inform them

Constructor and method have so much common , that it is difficult to


Try Again
differentiate between two . So you can easily identify constructor in the Report this error
code by keeping following points in the mind
1 . Constructor name is always be the same as the name of the class
.Generally in 99% code ,the name of the method is different from the name of the class . But the problem arises
that method too can have same name as the name of the class (Although it is considered as bad coding
practice)

Constructor example
JavaHungry.java
public class JavaHungry
{
public JavaHungry()
{}

// Class name
// Default Constructor

public void JavaHungry() //Valid Method name but it is considered as bad coding practice
{}
}
2 . So if the name is same , then the only way we can differentiate between constructor and method , by looking
at the return type .
Constructor never has a return type while method always has a return type . In the above example we
have shown the return type in red color . Return type is the declaration of the data type of the value which is
returned to the calling method .
Points to remember :
1. While creating new object for the class ,every constructor calls the constructor of the superclass first , which
is also known as constructor chaining . Internally , an implicit call to super() has been made ,unless
the constructor invokes an overloaded constructor of the same class .
2. Constructor can use any access modifier . Keep in mind that constructor can use private also .
http://javahungry.blogspot.com/2013/07/constructor-overloading-chaining-example-basics-rules-important.html

32 / 100

Constructor:Overloading ,Examples ,Basics, Rules,Important Points | Java Hungry

2/5/2016

3. Constructor name should be same as the name of the class .


4. Unlike methods , constructor do not have return types .
5. If one do not provide any constructor for the class ,then compiler put one implicitly in the code.
6. The default constructor is always no argument constructor .

7. If you have typed your constructor then , compiler do not provide the implicit constructor . So if you have
overloaded the constructor , and also want to use the no arg constructor , then you need to write it by yourself in
the code .
8. One cannot make a call to an instance method, or access an instance variable,
until after the super constructor runs.
9. Abstract classes always has constructor , and those constructors are called when a concrete (the
class which implemented the abstract class) subclass is instantiated (creating an object).
10. Another important point is that interfaces do not have constructors .
11 . The first line in the constructor must be either call to super() or call to this() .Calls to this() and
super() cannot be in the same constructor. You can have one or the other, but never both.
12. Every class, even an abstract class, has at least one constructor
13. Constructors are never inherited, thus they cannot be overridden.
Overloading a Constructor
Just like methods constructors can also be overloaded .Overloading a constructor means writing a multiple
version of the constructor .
Continuing with above example
JavaHungry.java
public class JavaHungry
{
public JavaHungry()
{}

// Class name
//Default Constructor 1

public JavaHungry(int a , int b) // Overloaded Constructor 2


{}
public JavaHungry(String x , String y) // Overloaded Constructor 3
{}
}

http://javahungry.blogspot.com/2013/07/constructor-overloading-chaining-example-basics-rules-important.html

33 / 100

Constructor:Overloading ,Examples ,Basics, Rules,Important Points | Java Hungry

2/5/2016

About The Author


Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry

You might also like


Count total number of times each alphabet appears in the string java program code with example
Difference between HashSet and TreeSet : Java Collections Interview Question
Difference between Iterator and Enumeration with example : Java Collections Question
5 Must Know Algorithm Problem Solving Techniques or Approaches for Software Programmer
Recommended by

http://javahungry.blogspot.com/2013/07/constructor-overloading-chaining-example-basics-rules-important.html

34 / 100

Constructor:Overloading ,Examples ,Basics, Rules,Important Points | Java Hungry


Share

2/5/2016

WHATS HOT
Difference between Arraylist and Vector : Core Java Interview Collection Question

Best Books for Learning Java

Amazon Interview Question : First Non repeated character in String

Count total number of times each alphabet appears in the string java program code with example

Java 8 new features : Lambda expressions , optional class , Defender methods with examples

Subscribe for Our Newsletter

POPULAR POSTS
Java Interview Questions

http://javahungry.blogspot.com/2013/07/constructor-overloading-chaining-example-basics-rules-important.html

35 / 100

Constructor:Overloading ,Examples ,Basics, Rules,Important Points | Java Hungry

2/5/2016

Top 50 Java Collections Interview Questions and Answers

What Makes You Stand out from the Crowd

Threads , Lifecycle Explained with Example

Count number of words in the String with Example : Java Program Code

Return to Top
Java Hungry Copyright 2016 All Rights Reserved. Designed by studiopress

http://javahungry.blogspot.com/2013/07/constructor-overloading-chaining-example-basics-rules-important.html

36 / 100

Difference between Arraylist and Vector : Core Java Interview Collection Question | Java Hungry

2/5/2016

JAVA HUNGRY
Java developers tutorials and coding.
Search this blog...
HOME
SCJP

STRING
THREADS

COLLECTIONS

Search

INTERVIEW

BEST JAVA BOOKS

INTERVIEW TIPS

DATA-STRUCTURES

JAVA CODING PROGRAM

MORE JAVA TOPICS

Difference Between Arraylist And Vector : Core Java Interview


Collection Question

Difference between Vector and Arraylist is the most common Core Java
Interview question you will come across in Collection . This question is
mostly used as a start up question by the Interviewers before testing
deep roots of the Collection .
Vector , ArrayList classes are implemented using dynamically resizable The connection to the server was reset while the page w
array providing fast random access and fast list traversal very much
The page you are trying to view cannot be shown b
like using an ordinary array . ArrayList support dynamic arrays that can
Please contact the website owners to inform them
grow as needed that is ArrayList can be dynamically increased or
decreased in size .
Try Again

Secure Connection Failed

Report this error

Read Also : Difference between HashMap and ConcurrentHashMap


Arraylist vs Vector in Java
1. Synchronization and Thread-Safe
Vector is synchronized while ArrayList is not synchronized . Synchronization and thread safe means at a
time only one thread can access the code .In Vector class all the methods are synchronized .Thats why the
Vector object is already synchronized when it is created .
2. Performance
Vector is slow as it is thread safe . In comparison ArrayList is fast as it is non synchronized . Thus in
ArrayList two or more threads can access the code at the same time , while Vector is limited to one thread at a
time.
3. Automatic Increase in Capacity
A Vector defaults to doubling size of its array . While when you insert an element into the ArrayList ,
increases
its Array size by 50% .

it

By default ArrayList size is 10 . It checks whether it reaches the


last element then it will create the new array
,copy the new data of last array to new array ,then old array is garbage collected by the Java Virtual Machine
(JVM) .
4. Set Increment Size
ArrayList does not define the increment size . Vector defines the increment size .
You can find the following method in Vector Class

http://javahungry.blogspot.com/2013/12/difference-between-arraylist-and-vector-in-java-collection-interview-question.html

37 / 100

Difference between Arraylist and Vector : Core Java Interview Collection Question | Java Hungry

2/5/2016

public synchronized void setSize(int i) { //some code }


There is no setSize() method or any other method in ArrayList which can manually set the increment size.
5. Enumerator
Other than Hashtable ,Vector is the only other class which uses both Enumeration and Iterator .While
ArrayList can only use Iterator for traversing an ArrayList .
6. Introduction in Java
java.util.Vector class was there in java since the very first version of the java development kit (jdk).
java.util.ArrayList was introduced in java version 1.2 , as part of Java Collections framework . In java version 1.2
, Vector class has been refactored to implement the List Inteface .
Please do mention in the comments in case if you have any doubts or suggestions regarding the post.

About The Author


Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry

You might also like


How to get Thread ID in Java with Example
Internal implementation of Set/HashSet (How Set Ensures Uniqueness) : Core Java Collection Interview Question
Difference between Iterator and Enumeration with example : Java Collections Question
8 Difference between Array and ArrayList in Java with Example
Recommended by

http://javahungry.blogspot.com/2013/12/difference-between-arraylist-and-vector-in-java-collection-interview-question.html

38 / 100

Difference between Arraylist and Vector : Core Java Interview Collection Question | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2013/12/difference-between-arraylist-and-vector-in-java-collection-interview-question.html

39 / 100

Difference between Arraylist and Vector : Core Java Interview Collection Question | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2013/12/difference-between-arraylist-and-vector-in-java-collection-interview-question.html

40 / 100

Difference between Arraylist and Vector : Core Java Interview Collection Question | Java Hungry
Share

2/5/2016

WHATS HOT
Difference between Arraylist and Vector : Core Java Interview Collection Question

Best Books for Learning Java

Amazon Interview Question : First Non repeated character in String

Count total number of times each alphabet appears in the string java program code with example

Java 8 new features : Lambda expressions , optional class , Defender methods with examples

Subscribe for Our Newsletter

POPULAR POSTS
Java Interview Questions

http://javahungry.blogspot.com/2013/12/difference-between-arraylist-and-vector-in-java-collection-interview-question.html

41 / 100

Difference between Arraylist and Vector : Core Java Interview Collection Question | Java Hungry

2/5/2016

Top 50 Java Collections Interview Questions and Answers

What Makes You Stand out from the Crowd

Threads , Lifecycle Explained with Example

Count number of words in the String with Example : Java Program Code

Return to Top
Java Hungry Copyright 2016 All Rights Reserved. Designed by studiopress

http://javahungry.blogspot.com/2013/12/difference-between-arraylist-and-vector-in-java-collection-interview-question.html

42 / 100

Threads , Lifecycle Explained with Example | Java Hungry

2/5/2016

JAVA HUNGRY
Java developers tutorials and coding.
Search this blog...
HOME
SCJP

STRING
THREADS

COLLECTIONS

Search

INTERVIEW

BEST JAVA BOOKS

INTERVIEW TIPS

DATA-STRUCTURES

JAVA CODING PROGRAM

MORE JAVA TOPICS

Threads , Lifecycle Explained With Example


What is Thread ?
Thread is a sequence of code executed independently with other
threads of control with in a single executed program .

Secure Connection Failed

The connection to the server was reset while the page w

for example : Here we are going to calculate the sum of next hundred
numbers from the given input number by the user

The page you are trying to view cannot be shown b


Please contact the website owners to inform them

Try Again

Read Also : How to Manually Throw Interrupted Exception in Threads

Report this error

public class ThreadExample


{
public static void main (String args[])
{
int n= Integer.parseInt(args[0]);
System.out.println("Number is : " +n);
int sum=0;
int nexthundred=n+100;
while(nexthundred > n)
sum = sum+(nexthundred--);
System.out.println("Sum of next hundred numbers is " + sum);
}
}

So at machine level following instructions are executing :


1.
2.
3.
4.
5.
6.
7.

Convert args[0] to integer


Store the integer to the n memory location
Print the number
Stote 0 in the location known as sum
Stote n+100 in the location known as nexthundred
Now Test if nexthundred is greater than n
Again print the sum as final result

The above steps happened at the machine level.


So we learn that The execution path of the above steps is called as Thread .
* Each computer program has atleast one thread that is the thread which starts the application
and we normally call this thread as main thread
http://javahungry.blogspot.com/2013/07/threads-lifecycle-example-java-methods-explanation.html

43 / 100

Threads , Lifecycle Explained with Example | Java Hungry

2/5/2016

Why Threads
If the program is break into different parts , then it is easier to write code for the algorithm as separate tasks or
threads .Please note that , using thread in the program does not make the program to execute faster . But it
sorts of create an illusion .

LifeCycle of a Thread
Creating a Thread
A thread can be created by two ways :
By extending the thread class
or
By implementing the runnable interface
Thread are created with three pieces of information :
These are
1. Thread Name : It will assign some name to the thread
2. Runnable target : It is the list of code that needs to be executed by the thread . This information is generally
in the run() of the thread .
3. Stack size : Every thread has a stack where it stores its local variables or temporary variables . Everything
related to the size of stack is platform dependent.Use of stack size in portable programs is highly discouraged

Starting a Thread
We can start the thread by calling the start() method on Thread object . Although a thread is there once it is
created but it is not executing or running . So it is in waiting state .
Being in waiting state , other threads can interact with this thread ,and attributes of the waiting thread can be
set along with its priority , its daemon status etc. can also be set by the other threads .
So in short
http://javahungry.blogspot.com/2013/07/threads-lifecycle-example-java-methods-explanation.html

44 / 100

Threads , Lifecycle Explained with Example | Java Hungry

2/5/2016

So in short
Even though the thread is waiting , its state can be changed by other threads .
Terminating a Thread
Once the thread finish executing run() method , no matter how much time it takes to complete or number of calls
to other methods, it terminates the thread . Means the thread dead . Once dead , it can not be restarted.
Pausing,Suspending and Resuming Thread
A thread can be paused by using sleep(time) method . Can be suspended by using wait method .
Now the question arises what is the difference between wait and sleep method

Sleep() method will make sure that the thread sleeps atleast for the amount of time we passed in the sleep
method , but there is no such guarantee for the wait method .
Also , sleep method affects only the thread that executes it , its not possible to tell another thread to go to
sleep .
Thread Cleanup
Although the thread completed its run()method and is terminated . Still , Thread object contains some
interesting information .As long as some other active object holds a reference to the terminated
thread object, other threads can execute methods on the terminated thread and retrieve that information.
If the thread object representing the terminated thread goes out of scope, the thread object is garbage collected
.
Please mention in comments in case you have any doubts regarding threads or multithreading.

About The Author


Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry

Share

You might also like


THREADS
How to get Thread ID in Java with Example
How to manually generate Interrupted Exception in Threads : Java Program Code
How to Reverse a String without using reverse built in method or recursion in Java : Source code with example
Recommended by

http://javahungry.blogspot.com/2013/07/threads-lifecycle-example-java-methods-explanation.html

45 / 100

Threads , Lifecycle Explained with Example | Java Hungry

2/5/2016

WHATS HOT
Difference between Arraylist and Vector : Core Java Interview Collection Question

Best Books for Learning Java

Amazon Interview Question : First Non repeated character in String

Count total number of times each alphabet appears in the string java program code with example

Java 8 new features : Lambda expressions , optional class , Defender methods with examples

http://javahungry.blogspot.com/2013/07/threads-lifecycle-example-java-methods-explanation.html

46 / 100

Threads , Lifecycle Explained with Example | Java Hungry

2/5/2016

Subscribe for Our Newsletter

POPULAR POSTS
Java Interview Questions

Top 50 Java Collections Interview Questions and Answers

What Makes You Stand out from the Crowd

Threads , Lifecycle Explained with Example

Count number of words in the String with Example : Java Program Code

Return to Top
Java Hungry Copyright 2016 All Rights Reserved. Designed by studiopress

http://javahungry.blogspot.com/2013/07/threads-lifecycle-example-java-methods-explanation.html

47 / 100

5 Difference between Sleep and Wait method with Example | Java Hungry

2/5/2016

JAVA HUNGRY
Java developers tutorials and coding.
Search this blog...
HOME
SCJP

STRING
THREADS

COLLECTIONS

Search

INTERVIEW

BEST JAVA BOOKS

INTERVIEW TIPS

DATA-STRUCTURES

JAVA CODING PROGRAM

MORE JAVA TOPICS

5 Difference Between Sleep And Wait Method With Example


Today we will share the difference between sleep and wait method in
java . This is one of the most popular question of Threads topic for the
java beginners. Both sleep() and wait() methods are most widely used
methods in Thread programming in Java.

Secure Connection Failed

The connection to the server was reset while the page w

Read Also : Difference between implements Runnable and extends


Thread in Java

The page you are trying to view cannot be shown b


Please contact the website owners to inform them

Try Again

Difference between Sleep and Wait method in Java

Report this error

1. Class belongs : The wait() method belongs to java.lang.Object


class, thus can be called on any Object. The sleep() method belongs to
java.lang.Thread class, thus can be called on Threads.
2. Context : The wait() method can only be called from Synchronized context i.e. using synchronized block or
synchronized method. The sleep() method can be called from any context.
3. Locking : The wait() method releases the lock on an object and gives others chance to execute. The sleep()
method does not releases the lock of an object for specified time or until interrupt.
4. Wake up condition : A waiting thread can be awake by notify() or notifyAll() method. A sleeping can be
awaked by interrupt or time expires.
5. Execution : Each object has each wait() method for inter-communication between threads. The sleep()
method is static method belonging to Thread class. There is a common mistake to write t.sleep(1000) because
sleep() is a class method and will pause the current running thread not t.

Example of wait() and sleep() method

import java.util.Hashtable;
public class Message {
/*** A Message class shared between Waiter and Notifier */
// volatile guarantees latest value to Waiter and Notifier.
public Message(String textMessage) {
this.textMessage = textMessage;
}
private volatile String textMessage;
http://javahungry.blogspot.com/2015/11/5-difference-between-sleep-and-wait-with-example.html

48 / 100

5 Difference between Sleep and Wait method with Example | Java Hungry

2/5/2016

public String getTextMessage() {


return textMessage;
}
public void setTextMessage(String textMessage){
this.textMessage = textMessage;
}
}
WAITER.JAVA
import java.util.Date;
public class Waiter implements Runnable {

/*** A Waiter class reading text message from Message class */

private Message message;


public Waiter(Message message) {
this.message = message;
}
public void run() {
// Synchronized context is necessary for wait()
// The below synchronized block will lock message object
synchronized (message) {
try {
System.out.println("Waiter is waiting for the Notifier at "
+ new Date());
// Release lock on message for Notifier
message.wait();
}
catch(InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
}
// Synchronized block over, now message object is no more locked
// Notifier notifies using notify() on message
System.out.println("Waiter is done waiting at " + new Date());
// Reading shared message set by Notifier
System.out.println("Waiter got the message: "
+ message.getTextMessage());
}
}

http://javahungry.blogspot.com/2015/11/5-difference-between-sleep-and-wait-with-example.html

49 / 100

5 Difference between Sleep and Wait method with Example | Java Hungry

2/5/2016

NOTIFIER.JAVA
import java.util.Date;

public class Notifier implements Runnable {

/*** A Notifier class writing Message vslue and notifies to waiter */


private Message message;
public Notifier(Message message) {
this.message = message;
}
public void run() {
System.out.println("Notifier is sleeping for 5 seconds at "
+ new Date());
// Sleeping current thread for 5 seconds.
try {
Thread.sleep(5000);
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
// Synchronized context is necessary for notify()
// The below synchronized block will lock message object
synchronized (message) {
// Writing into shared message object
message.setTextMessage("Notifier took 5 seconds");
System.out.println("Notifier is notifying waiting thread to wake up at " + new Date());
// Notify the Waiter thread which is waiting for message
message.notify();
}
// Synchronized block over, now message object is no more locked
}
}
// ThreadDemo.java
/**
* Main class performing sleep(), wait() and notify() over Message, Waiter and
* Notifier classes
*/
public class ThreadDemo {
public static void main(String[] args) {
// Simple Message with Hello World! as text message
Message message = new Message("Hello World!");
// Waiter thread waiting for message from Notifier
Waiter waiter = new Waiter(message);
Thread waiterThread = new Thread(waiter, "Waiter Thread");
http://javahungry.blogspot.com/2015/11/5-difference-between-sleep-and-wait-with-example.html

50 / 100

5 Difference between Sleep and Wait method with Example | Java Hungry

2/5/2016

waiterThread.start();
// Notifier thread notifying message to Waiter
Notifier notifier = new Notifier(message);
Thread notifierThread = new Thread(notifier, "Notifier Thread");
notifierThread.start();
}
}

Output:
Waiter is waiting for the Notifier at Sat Oct 31 01:37:51 IST 2015
Notifier is sleeping for 5 seconds at Sat Oct 31 01:37:51 IST 2015
Notifier is notifying waiting thread to wake up at Sat Oct 31 01:37:56 IST 2015
Waiter is done waiting at Sat Oct 31 01:37:56 IST 2015
Waiter got the message: Notifier took 5 seconds
Similarities between wait() and sleep()
Thread state: Both the method wait() and sleep() makes the running thread into Not Runnable state.
Running time: Both the method wait() and sleep() takes total execution time in milliseconds as an argument,
after that it will be expired.
When to use wait()
The wait() is used for multi threaded synchronization, where single
resource is shared among multiple thread.
For example, file resources over network.
When to use sleep()
The wait() is used for time synchronization, where the thread actually
needs a delay in background.
For example, process something on specific interval.
Recap : Difference between Sleep and Wait in Java

Sleep

Wait

Class belongs

java.lang.Thread

java.lang.Object

Context

Called from any context

Only synchronized context

Locking

Does not release the lock


for specified time or until
interrupt.

Releases the lock

Wake up Condition

When time expires or


due to interruption

Awake by call to notify()


or notifyAll() method

http://javahungry.blogspot.com/2015/11/5-difference-between-sleep-and-wait-with-example.html

51 / 100

5 Difference between Sleep and Wait method with Example | Java Hungry

2/5/2016

Execution of sleep will


Thread wait()
pause the current running
continues till a specific condition
thread not the object on which
holds true
it is called.

Execution

Please mentioned in the comments in case you have any questions regarding difference between sleep and wait
method in java.

About The Author


Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry

You might also like


Remove Specific Characters from String with Example
5 ways to Reverse a String in Java with Example
How to convert Signed integer to String in java with example
Difference between Iterator and Enumeration with example : Java Collections Question
Recommended by

http://javahungry.blogspot.com/2015/11/5-difference-between-sleep-and-wait-with-example.html

52 / 100

5 Difference between Sleep and Wait method with Example | Java Hungry
Share

2/5/2016

WHATS HOT
Difference between Arraylist and Vector : Core Java Interview Collection Question

Best Books for Learning Java

Amazon Interview Question : First Non repeated character in String

Count total number of times each alphabet appears in the string java program code with example

Java 8 new features : Lambda expressions , optional class , Defender methods with examples

Subscribe for Our Newsletter

POPULAR POSTS
Java Interview Questions

http://javahungry.blogspot.com/2015/11/5-difference-between-sleep-and-wait-with-example.html

53 / 100

5 Difference between Sleep and Wait method with Example | Java Hungry

2/5/2016

Top 50 Java Collections Interview Questions and Answers

What Makes You Stand out from the Crowd

Threads , Lifecycle Explained with Example

Count number of words in the String with Example : Java Program Code

Return to Top
Java Hungry Copyright 2016 All Rights Reserved. Designed by studiopress

http://javahungry.blogspot.com/2015/11/5-difference-between-sleep-and-wait-with-example.html

54 / 100

5 Difference between "implements Runnable" and "extends Thread" in Java | Java Hungry

2/5/2016

JAVA HUNGRY
Java developers tutorials and coding.
Search this blog...
HOME
SCJP

STRING
THREADS

COLLECTIONS

Search

INTERVIEW

BEST JAVA BOOKS

INTERVIEW TIPS

DATA-STRUCTURES

JAVA CODING PROGRAM

MORE JAVA TOPICS

5 Difference Between "Implements Runnable" And "Extends


Thread" In Java

How to instantiate a Thread in java either by implementing Runnable or


extending Thread class . We will go through the difference between
"implements Runnable" and "extends Thread" . It will help us to choose
the correct way to instantiate the Thread in our application.
The connection to the server was reset while the page w
Although, in the real world application you are much more likely to
implement Runnable interface than extends Thread. Extending the
The page you are trying to view cannot be shown b
Thread class is easiest but not a good Object Oriented practice.
Please contact the website owners to inform them
In this post we will see the difference between "implements Runnable"
and "extends Thread". This is one of the basic interview question on the Try Again
topic of Threads.
Report this error

Secure Connection Failed

Read Also : Life Cycle of Thread in Java


Difference between "implements Runnable" and "extends Thread" in Java
1. Inheritance Option: The limitation with "extends Thread" approach is that if you extend Thread, you can
not extend anything else . Java does not support multiple inheritance. In reality , you do not need Thread class
behavior , because in order to use a thread you need to instantiate one anyway.
On the other hand,
Implementing the Runnable interface gives you the choice to extend any class you like , but still define behavior
that will be run by separate thread.
2. Reusability : In "implements Runnable" , we are creating a different Runnable class for a specific behavior
job (if the work you want to be done is job). It gives us the freedom to reuse the specific
behavior job whenever required.
"extends Thread" contains both thread and job specific behavior code. Hence once thread completes execution
, it can not be restart again.
3. Object Oriented Design: Implementing Runnable should be preferred . It does not specializing or modifying
the thread behavior . You are giving thread something to run. We conclude that Composition is the better way.
Composition means two objects A and B satisfies has-a relationship.
"extends Thread" is not a good Object Oriented practice.
4. Loosely-coupled : "implements Runnable" makes the code loosely-coupled and easier to read .
Because the code is split into two classes . Thread class for the thread specific code and your Runnable
implementation class for your job that should be run by a thread code.
"extends Thread" makes the code tightly coupled . Single class contains the thread code as well as the job that
needs to be done by the thread.
5. Functions overhead : "extends Thread" means inheriting all the functions of the Thread class which we
may do not need . job can be done easily by Runnable without the Thread class functions overhead.
Example of "implements Runnable" and "extends Thread"

http://javahungry.blogspot.com/2015/05/implements-runnable-vs-extends-thread-in-java-example.html

55 / 100

5 Difference between "implements Runnable" and "extends Thread" in Java | Java Hungry

2/5/2016

public class RunnableExample implements Runnable {


public void run() {
System.out.println("Alive is awesome");
}
}

public class ThreadExample extends Thread {


}
}

public void run() {


System.out.println(" Love Yourself ");

When to use "extends Thread" over "implements Runnable"


The only time it make sense to use "extends Thread" is when you
have a more specialized version of Thread class. In other words ,
because you have more specialized thread specific behavior.
But the conditions are that the thread work you want is really just a
job to be done by a thread. In that case you need to use "implements
Runnable" which also leaves your class free to extend some other class.

Recap : Difference between "implements Runnable" and "extends Thread"

implements Runnable

extends Thread

Inheritance option

extends any java class

No

Reusability

Yes

No

Object Oriented Design Good,allows composition Bad


Loosely Coupled

Yes

No

Function Overhead

No

Yes

If you have any doubts regarding the difference between "implements Runnable" and "extends Thread" then
please mention in the comments .

About The Author


Subham Mittal has worked in Oracle for 3 years .
http://javahungry.blogspot.com/2015/05/implements-runnable-vs-extends-thread-in-java-example.html

56 / 100

5 Difference between "implements Runnable" and "extends Thread" in Java | Java Hungry

2/5/2016

For more java articles ,Click here to Subscribe JavaHungry

You might also like


INTERVIEW TIPS
5 Difference between ArrayList and LinkedList in Java with Example
How to get Thread ID in Java with Example
How Remove Method Works Internally in HashMap with Example
Recommended by

http://javahungry.blogspot.com/2015/05/implements-runnable-vs-extends-thread-in-java-example.html

57 / 100

5 Difference between "implements Runnable" and "extends Thread" in Java | Java Hungry
Share

2/5/2016

WHATS HOT
Difference between Arraylist and Vector : Core Java Interview Collection Question

Best Books for Learning Java

Amazon Interview Question : First Non repeated character in String

Count total number of times each alphabet appears in the string java program code with example

Java 8 new features : Lambda expressions , optional class , Defender methods with examples

Subscribe for Our Newsletter

POPULAR POSTS
Java Interview Questions

http://javahungry.blogspot.com/2015/05/implements-runnable-vs-extends-thread-in-java-example.html

58 / 100

5 Difference between "implements Runnable" and "extends Thread" in Java | Java Hungry

2/5/2016

Top 50 Java Collections Interview Questions and Answers

What Makes You Stand out from the Crowd

Threads , Lifecycle Explained with Example

Count number of words in the String with Example : Java Program Code

Return to Top
Java Hungry Copyright 2016 All Rights Reserved. Designed by studiopress

http://javahungry.blogspot.com/2015/05/implements-runnable-vs-extends-thread-in-java-example.html

59 / 100

Top 25 Most Frequently Asked Interview Core Java Interview Questions And Answers | Java Hungry

2/5/2016

JAVA HUNGRY
Java developers tutorials and coding.
Search this blog...
HOME
SCJP

STRING
THREADS

COLLECTIONS

Search

INTERVIEW

BEST JAVA BOOKS

INTERVIEW TIPS

DATA-STRUCTURES

JAVA CODING PROGRAM

MORE JAVA TOPICS

Top 25 Most Frequently Asked Interview Core Java Interview


Questions And Answers

We are sharing 25 java interview questions , these questions are


frequently asked by the recruiters.Java questions can be asked from
any core java topic . So we try our best to provide you the java interview
questions and answers for experienced which should be in your to do
The connection to the server was reset while the page w
list before facing java questions in technical interview .

Secure Connection Failed

The page you are trying to view cannot be shown b


Please contact the website owners to inform them

Top 25 Java Interview Questions :


1. Which two method you need to implement for key Object in
HashMap ?
In order to use any object as Key in HashMap, it must implements
equals and hashcode method in Java. Read How HashMap works in
Java for detailed explanation on how equals and hashcode method is
used to put and get object from HashMap.

Try Again
Report this error

2. What is immutable object? Can you write immutable object?Immutable classes are Java classes whose
objects can not be modified once created. Any modification in Immutable object result in new object. For example
is String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class
from overriding methods in Java which can compromise Immutability. You can achieve same functionality by
making member as non final but private and not modifying them except in constructor.
3. What is the difference between creating String as new() and literal?
When we create string with new() Operator, its created in heap and not added into
string pool while String created using literal are created in String pool itself which exists in PermGen area of
heap.
String s = new String("Test");
does not put the object in String pool , we need to call String.intern() method which is used to put them into
String pool explicitly. its only when you create String object as String literal e.g. String s = "Test" Java
automatically put that into String pool.
4. What is difference between StringBuffer and StringBuilder in Java ?
Classic Java questions which some people thing tricky and some consider very easy. StringBuilder in Java is introduced in Java 5 and only difference
between both of them is that Stringbuffer methods are synchronized while StringBuilder is non synchronized. See StringBuilder vs StringBuffer for
more differences.

5. Write code to find the First non repeated character in the String ?
Another good Java interview question, This question is mainly asked by Amazon and equivalent companies. See
first non repeated character in the string : Amazon interview question

http://javahungry.blogspot.com/2013/06/top-25-most-frequently-asked-core-java.html

60 / 100

Top 25 Most Frequently Asked Interview Core Java Interview Questions And Answers | Java Hungry

2/5/2016

6. What is the difference between ArrayList and Vector ?


This question is mostly used as a start up question in Technical interviews on the topic of Collection framework
. Answer is explained in detail here Difference between ArrayList and Vector .

7. How do you handle error condition while writing stored procedure or accessing stored procedure
from java?
This is one of the tough Java interview question and its open for all, my friend didn't know the answer so he
didn't mind telling me. my take is that stored procedure should return error code if some operation fails but if
stored procedure itself fail than catching SQLException is only choice.
8. What is difference between Executor.submit() and Executer.execute() method ?
There is a difference when looking at exception handling. If your tasks throws an exception and if it was submitted
with execute this exception will go to the uncaught exception handler (when you don't have provided one explicitly, the
default one will just print the stack trace to System.err). If you submitted the task with submit any thrown
exception, checked exception or not, is then part of the task's return status. For a task that was submitted
with submit and that terminates with an exception, the Future.get will re-throw this exception, wrapped in
an ExecutionException.

9. What is the difference between factory and abstract factory pattern?


Abstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract
Factory and responsible for creation of different hierarchies of objects based on the type of factory.
E.g. AbstractFactory extended by AutomobileFactory, UserFactory, RoleFactory etc. Each individual factory would be
responsible for creation of objects in that genre.

You can also refer What is Factory method design pattern in Java to know more details.
10. What is Singleton? is it better to make whole method synchronized or only critical section
synchronized ?
Singleton in Java is a class with just one instance in whole Java application, for example java.lang.Runtime is a
Singleton class. Creating Singleton was tricky prior Java 4 but once Java 5 introduced Enum its very easy. see
my article How to create thread-safe Singleton in Java for more details on writing Singleton using enum and
double checked locking which is purpose of this Java interview question.
11. Can you write critical section code for singleton?
This core Java question is followup of previous question and expecting candidate to write Java singleton using
double checked locking. Remember to use volatile variable to make Singleton thread-safe.
12. Can you write code for iterating over hashmap in Java 4 and Java 5 ?
Tricky one but he managed to write using while and for loop.
13. When do you override hashcode and equals() ?
Whenever necessary especially if you want to do equality check or want to use your object as key in HashMap.
14. What will be the problem if you don't override hashcode() method ?
You will not be able to recover your object from hash Map if that is used as key in HashMap.
See here How HashMap works in Java for detailed explanation.
15. Is it better to synchronize critical section of getInstance() method or whole getInstance() method ?
Answer is critical section because if we lock whole method than every time some one call this method will have
to wait even though we are not creating any object)
16. What is the difference when String is gets created using literal or new() operator ?
When we create string with new() its created in heap and not added into string pool while String created using
literal are created in String pool itself which exists in Perm area of heap.

http://javahungry.blogspot.com/2013/06/top-25-most-frequently-asked-core-java.html

61 / 100

Top 25 Most Frequently Asked Interview Core Java Interview Questions And Answers | Java Hungry

2/5/2016

17. Does not overriding hashcode() method has any performance implication ?
This is a good question and open to all , as per my knowledge a poor hashcode function will result in frequent
collision in HashMap which eventually increase time for adding an object into Hash Map.
18. Whats wrong using HashMap in multithreaded environment? When get() method go to infinite loop
?
Another good question. His answer was during concurrent access and re-sizing.
19. What do you understand by thread-safety ? Why is it required ? And finally, how to achieve
thread-safety in Java Applications ?
Java Memory Model defines the legal interaction of threads with the memory in a real computer system. In a
way, it describes what behaviors are legal in multi-threaded code. It determines when a Thread can reliably see
writes to variables made by other threads. It defines semantics for volatile, final & synchronized, that makes
guarantee of visibility of memory operations across the Threads.
Let's first discuss about Memory Barrier which are the base for our further discussions. There are two type of
memory barrier instructions in JMM - read barriers and write barrier.
A read barrier invalidates the local memory (cache, registers, etc) and then reads the contents from the main
memory, so that changes made by other threads becomes visible to the current Thread.
A write barrier flushes out the contents of the processor's local memory to the main memory, so that changes
made by the current Thread becomes visible to the other threads.
JMM semantics for synchronized
When a thread acquires monitor of an object, by entering into a synchronized block of code, it performs a read
barrier (invalidates the local memory and reads from the heap instead). Similarly exiting from a synchronized
block as part of releasing the associated monitor, it performs a write barrier (flushes changes to the main
memory)
Thus modifications to a shared state using synchronized block by one Thread, is guaranteed to be visible to
subsequent synchronized reads by other threads. This guarantee is provided by JMM in presence of
synchronized code block.
JMM semantics for Volatile fields
Read & write to volatile variables have same memory semantics as that of acquiring and releasing a monitor
using synchronized code block. So the visibility of volatile field is guaranteed by the JMM. Moreover afterwards
Java 1.5, volatile reads and writes are not reorderable with any other memory operations (volatile and nonvolatile both). Thus when Thread A writes to a volatile variable V, and afterwards Thread B reads from variable
V, any variable values that were visible to A at the time V was written are guaranteed now to be visible to B.
Let's try to understand the same using the following code
Data data = null;
volatile boolean flag = false;
Thread A
------------data = new Data();
flag = true; <-- writing to volatile will flush data as well as flag to main memory
Thread B
------------if(flag==true){ <-- as="" barrier="" data.="" flag="" font="" for="" from="" perform="" read="" reading="" volatile=""
well="" will="">
use data; <!--- data is guaranteed to visible even though it is not declared volatile because of the
JMM semantics of volatile flag.
}
20. What will happen if you call return statement or System.exit on try or catch block ? will finally
block execute?
This is a very popular tricky Java question and its tricky because many programmer think that finally block
always executed. This question challenge that concept by putting return statement in try or catch block or
calling System.exit from try or catch block. Answer of this tricky question in Java is that finally block will execute
even if you put return statement in try block or catch block but finally block won't run if you call System.exit form
try or catch.
19. Can you override private or static method in Java ?
Another popular Java tricky question, As I said method overriding is a good topic to ask trick questions in
http://javahungry.blogspot.com/2013/06/top-25-most-frequently-asked-core-java.html

62 / 100

Top 25 Most Frequently Asked Interview Core Java Interview Questions And Answers | Java Hungry

2/5/2016

Another popular Java tricky question, As I said method overriding is a good topic to ask trick questions in
Java. Anyway, you can not override private or static method in Java, if you create similar method with same
return type and same method arguments that's called method hiding.
20. What will happen if we put a key object in a HashMap which is already there ?
This tricky Java questions is part of How HashMap works in Java, which is also a popular topic to create
confusing and tricky question in Java. well if you put the same key again than it will replace the old mapping
because HashMap doesn't allow duplicate keys.
21. If a method throws NullPointerException in super class, can we override it with a method which
throws RuntimeException?
One more tricky Java questions from overloading and overriding concept. Answer is you can very well throw
super class of RuntimeException in overridden method but you can not do same if its checked Exception.
22. What is the issue with following implementation of compareTo() method in Java
public int compareTo(Object o){
Employee emp = (Employee) emp;
return this.id - o.id;
}
23. How do you ensure that N thread can access N resources without deadlock
If you are not well versed in writing multi-threading code then this is real tricky question for you. This Java
question can be tricky even for experienced and senior programmer, who are not really exposed
to deadlock and race conditions. Key point here is order, if you acquire resources in a particular order and
release resources in reverse order you can prevent deadlock.
24. What is difference between CyclicBarrier and CountDownLatch in Java
Relatively newer Java tricky question, only been introduced form Java 5. Main difference between both of them
is that you can reuse CyclicBarrier even if Barrier is broken but you can not reuse CountDownLatch in Java.
See CyclicBarrier vs CountDownLatch in Java for more differences.
25. Can you access non static variable in static context?
Another tricky Java question from Java fundamentals. No you can not access static variable in non static context
in Java. Read why you can not access non-static variable from static method to learn more about this tricky Java
questions.

About The Author


Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry

You might also like


HashMap vs ConcurrentHashMap : Java Collections Interview Question
Answers to Core Java Coding / Programming Questions and Answers : Technical Interview in Java
5 ways of String Concatenation in Java
8 Difference between HashMap and TreeMap with Example
Recommended by

http://javahungry.blogspot.com/2013/06/top-25-most-frequently-asked-core-java.html

63 / 100

Top 25 Most Frequently Asked Interview Core Java Interview Questions And Answers | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2013/06/top-25-most-frequently-asked-core-java.html

64 / 100

Top 25 Most Frequently Asked Interview Core Java Interview Questions And Answers | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2013/06/top-25-most-frequently-asked-core-java.html

65 / 100

Top 25 Most Frequently Asked Interview Core Java Interview Questions And Answers | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2013/06/top-25-most-frequently-asked-core-java.html

66 / 100

Top 25 Most Frequently Asked Interview Core Java Interview Questions And Answers | Java Hungry

2/5/2016

WHATS HOT
Difference between Arraylist and Vector : Core Java Interview Collection Question

Best Books for Learning Java

Amazon Interview Question : First Non repeated character in String

Count total number of times each alphabet appears in the string java program code with example

Java 8 new features : Lambda expressions , optional class , Defender methods with examples

Share

http://javahungry.blogspot.com/2013/06/top-25-most-frequently-asked-core-java.html

67 / 100

Top 25 Most Frequently Asked Interview Core Java Interview Questions And Answers | Java Hungry

Like

2/5/2016

167

Subscribe for Our Newsletter


Tweet

POPULAR POSTS
Java Interview Questions

Top 50 Java Collections Interview Questions and Answers

What Makes You Stand out from the Crowd

Threads , Lifecycle Explained with Example

Count number of words in the String with Example : Java Program Code

http://javahungry.blogspot.com/2013/06/top-25-most-frequently-asked-core-java.html

68 / 100

Top 25 Most Frequently Asked Interview Core Java Interview Questions And Answers | Java Hungry

2/5/2016

Return to Top
Java Hungry Copyright 2016 All Rights Reserved. Designed by studiopress

http://javahungry.blogspot.com/2013/06/top-25-most-frequently-asked-core-java.html

69 / 100

Top 50 Java Collections Interview Questions and Answers | Java Hungry

2/5/2016

JAVA HUNGRY
Java developers tutorials and coding.
Search this blog...
HOME
SCJP

STRING
THREADS

COLLECTIONS

Search

INTERVIEW

BEST JAVA BOOKS

INTERVIEW TIPS

DATA-STRUCTURES

JAVA CODING PROGRAM

MORE JAVA TOPICS

Top 50 Java Collections Interview Questions And Answers


We have already shared the most frequently asked java interview
questions for experience candidates. Also shared the tricky coding
interview questions in our previous posts. Today , we will learn about
the top 50 java collections interview questions and answers. We will
divide this post into three categories :
Beginner level (0-1 year experience (Freshers)) ,
Intermediate level (1-3 years experienced Java Developers)
Advanced level(3+ Experienced) java collections interview questions
and answers

Secure Connection Failed

The connection to the server was reset while the page w

The page you are trying to view cannot be shown b


Please contact the website owners to inform them

Try Again
Report this error

Note : Please prepare all the below questions . Interviewer may choose to ask any question.
Beginner Level (0-1 yr): Java Collections Interview Questions and Answers
Q1 What is Collection ? What is a Collections Framework ? What are the benefits of Java Collections
Framework ?
Collection : A collection (also called as container) is an object that groups multiple elements into a single unit.
Collections Framework : Collections framework provides unified architecture for manipulating and
representing collections.
Benefits of Collections Framework :
1. Improves program quality and speed
2. Increases the chances of reusability of software
3. Decreases programming effort.
Q2 What is the root interface in collection hierarchy ?
Root interface in collection hierarchy is Collection interface . Few interviewer may argue that
Collection interface extends Iterable interface. So iterable should be the root interface. But you should reply
iterable interface present in java.lang package not in java.util package .It is clearly mentioned in Oracle
Collection docs , that Collection interface is a member of the Java Collections framework. For Iterable interface
Oracle doc , iterable interface is not mentioned as a part of the Java Collections framework .So if the question
includes collection hierarchy , then you should answer the question as Collection interface (which is found in
java.util package).
Q3 What is the difference between Collection and Collections ?
Collection is an interface while Collections is a java class , both are present in java.util package and part of
java collections framework.
Q4 Which collection classes are synchronized or thread-safe ?
http://javahungry.blogspot.com/2015/05/50-java-collections-interview-questions-and-answers.html

70 / 100

Top 50 Java Collections Interview Questions and Answers | Java Hungry

2/5/2016

Stack, Properties , Vector and Hashtable can be used in multi threaded environment because they are
synchronized classes (or thread-safe).

Q5 Name the core Collection interfaces ?

source of image : By Ervinn at en.wikibooks [CC BY-SA 3.0 ], from Wikimedia Commons

The list of core collection interfaces are : just mention the important ones
Important : Collection , Set , Queue , List , Map
Other interface also in the list : SortedSet, SortedMap , Deque, ListIterator etc.
Q6 What is the difference between List and Set ?
Set contain only unique elements while List can contain duplicate elements.
Set is unordered while List is ordered . List maintains the order in which the objects are added .
Q7 What is the difference between Map and Set ?
Map object has unique keys each containing some value, while Set contain only unique values.
Q8 What are the classes implementing List and Set interface ?
Class implementing List interface : ArrayList , Vector , LinkedList ,
Class implementing Set interface : HashSet , TreeSet
Q9 What is an iterator ?
Iterator is an interface . It is found in java.util package. It provides methods to iterate over any Collection.
Q10 What is the difference between Iterator and Enumeration ?
The main difference between Iterator and Enumeration is that Iterator has remove() method while Enumeration
doesn't.
http://javahungry.blogspot.com/2015/05/50-java-collections-interview-questions-and-answers.html

71 / 100

Top 50 Java Collections Interview Questions and Answers | Java Hungry

2/5/2016

Hence , using Iterator we can manipulate objects by adding and removing the objects from the collections.
Enumeration behaves like a read only interface as it can only traverse the objects and fetch it .
Q11 Which design pattern followed by Iterator ?
It follows iterator design pattern. Iterator design pattern provides us to navigate through the collection of objects
by using a common interface without letting us know about the underlying implementation.
Enumeration is an example of Iterator design pattern.
Q12 Which methods you need to override to use any object as key in HashMap ?
To use any object as key in HashMap , it needs to implement equals() and hashCode() method .
Q13 What is the difference between Queue and Stack ?
Queue is a data structure which is based on FIFO ( first in first out ) property . An example of Queue in real
world is buying movie tickets in the multiplex or cinema theaters.
Stack is a data structure which is based on LIFO (last in first out) property . An example of Stack in real world is
insertion or removal of CD from the CD case.
Q14 How to reverse the List in Collections ?
There is a built in reverse method in Collections class . reverse(List list) accepts list as parameter.
Collections.reverse(listobject);
Q15 How to convert the array of strings into the list ?
Arrays class of java.util package contains the method asList() which accepts the array as parameter.
So,
String[] wordArray = {"Love Yourself" , "Alive is Awesome" , "Be in present"};
List wordList = Arrays.asList(wordArray);
Intermediate Level (1-3 yrs): Java Collections Interview Questions and Answers
Q16 What is the difference between ArrayList and Vector ?
It is one of the frequently asked collection interview question , the main differences are
Vector is synchronized while ArrayList is not . Vector is slow while ArrayList is fast . Every time when needed,
Vector increases the capacity twice of its initial size while ArrayList increases its ArraySize by 50%. find detailed
explanation ArrayList vs Vector .

Q17 What is the difference between HashMap and Hashtable ?


It is one of the most popular collections interview question for java developer . Make sure you go through this
once before appearing for the interview .
Main differences between HashMap and Hashtable are :
a. HashMap allows one null key and any number of null values while Hashtable does not allow null keys and null
values.
b. HashMap is not synchronized or thread-safe while Hashtable is synchronized or thread-safe .
find detailed explanation here Hashtable vs HashMap in Java
Q18 What is the difference between peek(),poll() and remove() method of the Queue interface ?
http://javahungry.blogspot.com/2015/05/50-java-collections-interview-questions-and-answers.html

72 / 100

Top 50 Java Collections Interview Questions and Answers | Java Hungry

2/5/2016

Both poll() and remove() method is used to remove head object of the Queue. The main difference lies when the
Queue is empty().
If Queue is empty then poll() method will return null . While in similar case , remove() method will throw
NoSuchElementException .
peek() method retrieves but does not remove the head of the Queue. If queue is empty then peek() method also
returns null.
Q19 What is the difference between Iterator and ListIterator.
Using Iterator we can traverse the list of objects in forward direction . But ListIterator can traverse the collection
in both directions that is forward as well as backward.
Q20 What is the difference between Array and ArrayList in Java ?
This question checks whether student understand the concept of static and dynamic array. Some main
differences between Array and ArrayList are :
a. Array is static in size while ArrayList is dynamic in size.
b. Array can contain primitive data types while ArrayList can not contain primitive data types.
find detailed explanation ArrayList vs Array in Java
Q21 What is the difference between HashSet and TreeSet ?
Main differences between HashSet and TreeSet are :
a. HashSet maintains the inserted elements in random order while TreeSet maintains elements in the sorted
order
b. HashSet can store null object while TreeSet can not store null object.
find detailed explanation here TreeSet vs HashSet in Java
Q22 Write java code showing insertion,deletion and retrieval of HashMap object ?
Do it yourself (DIY) , if found any difficulty or doubts then please mention in the comments.
Q23 What is the difference between HashMap and ConcurrentHashMap ?
This is also one of the most popular java collections interview question . Make sure this question is in your to do
list before appearing for the interview .
Main differences between HashMap and ConcurrentHashMap are :
a. HashMap is not synchronized while ConcurrentHashMap is synchronized.
b. HashMap can have one null key and any number of null values while ConcurrentHashMap does not allow null
keys and null values .
find detailed explanation here ConcurrentHashMap vs HashMap in Java
Q24 Arrange the following in the ascending order (performance):
HashMap , Hashtable , ConcurrentHashMap and Collections.SynchronizedMap
Hashtable < Collections.SynchronizedMap < ConcurrentHashMap < HashMap
Q25 How HashMap works in Java ?
This is one of the most important question for java developers. HashMap works on the principle of Hashing .
Find detailed information here to understand what is hashing and how hashmap works in java .
Q26 What is the difference between LinkedList and ArrayList in Java ?
Main differences between LinkedList and ArrayList are :
a. LinkedList is the doubly linked list implementation of list interface , while , ArrayList is the resizable array
implementation of list interface.
b. LinkedList can be traversed in the reverse direction using descendingIterator() method provided by the Java
Api developers , while , we need to implement our own method to traverse ArrayList in the reverse direction . find
http://javahungry.blogspot.com/2015/05/50-java-collections-interview-questions-and-answers.html

73 / 100

Top 50 Java Collections Interview Questions and Answers | Java Hungry

2/5/2016

the detailed explanation here ArrayList vs LinkedList in java.

Q27 What are Comparable and Comparator interfaces ? List the difference between them ?

We already explained what is comparable and comparator interface in detail along with examples here, Comparable vs Comparator in Java

Q28 Why Map interface does not extend the Collection interface in Java Collections Framework ?
One liner answer : Map interface is not compatible with the Collection interface.
Explanation : Since Map requires key as well as value , for example , if we want to add key-value pair then we
will use put(Object key , Object value) . So there are two parameters required to add element to the HashMap
object . In Collection interface add(Object o) has only one parameter.
The other reasons are Map supports valueSet , keySet as well as other appropriate methods which have just
different views from the Collection interface.
Q29 When to use ArrayList and when to use LinkedList in application?
ArrayList has constant time search operation O(1) .Hence, ArrayList is preferred when there are more get() or
search operation .
Insertion , Deletion operations take constant time O(1) for LinkedList. Hence, LinkedList is preferred when there
are more insertions or deletions involved in the application.
Q30 Write the code for iterating the list in different ways in java ?
There are two ways to iterate over the list in java :
a. using Iterator
b. using for-each loop
Coding part : Do it yourself (DIY) , in case of any doubts or difficulty please mention in the comments .
Advance Level (3+ yrs): Java Collections Interview Questions and Answers
Q31 How HashSet works internally in java ?
This is one of the popular interview question . HashSet internally uses HashMap to maintain the uniqueness of
elements. We have already discussed in detail hashset internal working in java.
Q32 What is CopyOnWriteArrayList ? How it is different from ArrayList in Java?
CopyOnWriteArrayList is a thread safe variant of ArrayList in which all mutative operations like add , set are
implemented by creating a fresh copy of the underlying array.
It guaranteed not to throw ConcurrentModificationException.
It permits all elements including null. It is introduced in jdk 1.5 .
Q33 How HashMap works in Java ?
We are repeating this question , as it is one of the most important question for java developer.HashMap works
on the principle of Hashing . please find the detailed answer here hashmap internal working in java .
Q34 How remove(key) method works in HashMap ?
This is the new question which is getting popular among java interviewers . We have shared the detailed
explanation here how remove method works internally in java.

http://javahungry.blogspot.com/2015/05/50-java-collections-interview-questions-and-answers.html

74 / 100

Top 50 Java Collections Interview Questions and Answers | Java Hungry

2/5/2016

Q35 What is BlockingQueue in Java Collections Framework?


BlockingQueue implements the java.util.Queue interface . BlockingQueue supports operations that wait for the
queue to become non-empty when retrieving an element , and wait for space to become available in the queue
when storing an element .
It does not accept null elements.
Blocking queues are primarily designed for the producer-consumer problems.
BlockingQueue implementations are thread-safe and can also be used in inter-thread communications.
This concurrent Collection class was added in jdk 1.5
Q36 How TreeMap works in Java ?
TreeMap internally uses Red-Black tree to sort the elements in natural order. Please find the detailed answers
here internal implementation of TreeMap in java .
Q37 All the questions related to HashSet class can be found here , frequently asked HashSet interview
questions
Q38 What is the difference between Fail- fast iterator and Fail-safe iterator ?
This is one of the most popular interview question for the higher experienced java developers .
Main differences between Fail-fast and Fail-safe iterators are :
a. Fail-fast throw ConcurrentModificationException while Fail-safe does not.
b. Fail-fast does not clone the original collection list of objects while Fail-safe creates a copy of the original
collection list of objects.
The difference is explained in detail here fail-safe vs fail-fast iterator in java.
Q39 How ConcurrentHashMap works internally in Java?
The detailed answer is already explained here internal implementation of concurrenthashmap
Q40 How do you use a custom object as key in Collection classes like HashMap ?
If one is using the custom object as key then one needs to override equals() and hashCode() method
and one also need to fulfill the contract.
If you want to store the custom object in the SortedCollections like SortedMap then one needs to make sure that
equals() method is consistent to the compareTo() method. If inconsistent , then collection will not follow their
contracts ,that is , Sets may allow duplicate elements.
Q41 What is hash-collision in Hashtable ? How it was handled in Java?
In Hashtable , if two different keys have the same hash value then it lead to hash -collision. A bucket of type
linkedlist used to hold the different keys of same hash value.
Q42 Explain the importance of hashCode() and equals() method ? Explain the contract also ?
HashMap object uses Key object hashCode() method and equals() method to find out the index to put the keyvalue pair. If we want to get value from the HashMap same both methods are used . Somehow, if both methods
are not implemented correctly , it will result in two keys producing the same hashCode() and equals() output.
The problem will arise that HashMap will treat both output same instead of different and overwrite the most
recent key-value pair with the previous key-value pair.
Similarly all the collection classes that does not allow the duplicate values use hashCode() and equals() method
to find the duplicate elements.So it is very important to implement them correctly.
Contract of hashCode() and equals() method
a. If object1.equals(object2) , then object1.hashCode() == object2.hashCode() should always be true.
b. If object1.hashCode() == object2.hashCode() is true does not guarantee object1.equals(object2)
http://javahungry.blogspot.com/2015/05/50-java-collections-interview-questions-and-answers.html

75 / 100

Top 50 Java Collections Interview Questions and Answers | Java Hungry

2/5/2016

Q43 What is EnumSet in Java ?


EnumSet is a specialized Set implementation for use with enum types. All of the elements in an enum set must
come from a single enum type that is specified explicitly or implicitly , when the set is created.
The iterator never throws ConcurrentModificationException and is weakly consistent.
Advantage over HashSet:
All basic operations of EnumSet execute in constant time . It is most likely to be much faster than HashSet
counterparts.
It is a part of Java Collections Framework since jdk 1.5.
Q44 What are concurrentCollectionClasses?
In jdk1.5 , Java Api developers had introduced new package called java.util.concurrent that have thread-safe
collection classes as they allow collections to be modified while iterating . The iterator is fail-fast that is it will
throw ConcurrentModificationException.
Some examples of concurrentCollectionClasses are :
a. CopyOnWriteArrayList
b. ConcurrentHashMap
Q45 How do you convert a given Collection to SynchronizedCollection ?
One line code : Collections.synchronizedCollection(Collection collectionObj) will convert a given collection to
synchronized collection.
Q46 What is IdentityHashMap ?
IdentityHashMap
IdentityHashMap is a class present in java.util package. It implements the Map interface with a hash table , using
reference equality instead of object equality when comparing keys and values.In other words , in
IdentityHashMap two keys k1 and k2 are considered equal if only if (k1==k2).
IdentityHashMap is not synchronized.
Iterators returned by the iterator() method are fail-fast , hence , will throw ConcurrentModificationException.
Q47 What is WeakHashMap ?
WeakHashMap :
WeakHashMap is a class present in java.util package similar to IdentityHashMap. It is a Hashtable based
implementation of Map interface with weak keys. An entry in WeakHashMap will automatically be removed when
its key is no longer in ordinary use. More precisely the presence of a mapping for a given key will not prevent
the key from being discarded by the garbage collector.
It permits null keys and null values.
Like most collection classes this class is not synchronized.A synchronized WeakHashMap may be constructed
using the Collections.synchronizedMap() method.
Iterators returned by the iterator() method are fail-fast , hence , will throw ConcurrentModificationException.
Q48 How will you make Collections readOnly ?
We can make the Collection readOnly by using the following lines code:
General : Collections.unmodifiableCollection(Collection c)
Collections.unmodifiableMap(Map m)
Collections.unmodifiableList(List l)
Collections.unmodifiableSet(Set s)
Q49 What is UnsupportedOperationException?
http://javahungry.blogspot.com/2015/05/50-java-collections-interview-questions-and-answers.html

76 / 100

Top 50 Java Collections Interview Questions and Answers | Java Hungry

2/5/2016

This exception is thrown to indicate that the requested operation is not supported.
Example of UnsupportedOperationException:
In other words, if you call add() or remove() method on the readOnly collection . We know readOnly collection
can not be modified . Hence , UnsupportedOperationException will be thrown.
Q50 Suppose there is an Employee class. We add Employee class objects to the ArrayList. Mention
the steps need to be taken , if I want to sort the objects in ArrayList using the employeeId attribute
present in Employee class.
a. Implement the Comparable interface for the Employee class and now to compare the objects by employeeId
we will override the emp1.compareTo(emp2)
b. We will now call Collections class sort method and pass the list as argument , that is ,
Collections.sort(empList)
If you want to add more java collections interview questions and answers or in case you have any doubts
related to the Java Collections framework , then please mention in the comments.

About The Author


Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry

Share

You might also like


8 Difference between Array and ArrayList in Java with Example
5 Difference between ArrayList and LinkedList in Java with Example
Top 10 HashSet Java Interview Questions : Collections
5 Must Know Algorithm Problem Solving Techniques or Approaches for Software Programmer
Recommended by

http://javahungry.blogspot.com/2015/05/50-java-collections-interview-questions-and-answers.html

77 / 100

Top 50 Java Collections Interview Questions and Answers | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2015/05/50-java-collections-interview-questions-and-answers.html

78 / 100

Top 50 Java Collections Interview Questions and Answers | Java Hungry

2/5/2016

WHATS HOT
Difference between Arraylist and Vector : Core Java Interview Collection Question

Best Books for Learning Java

Amazon Interview Question : First Non repeated character in String

Count total number of times each alphabet appears in the string java program code with example

Java 8 new features : Lambda expressions , optional class , Defender methods with examples

Subscribe for Our Newsletter

POPULAR POSTS
Java Interview Questions

http://javahungry.blogspot.com/2015/05/50-java-collections-interview-questions-and-answers.html

79 / 100

Top 50 Java Collections Interview Questions and Answers | Java Hungry

2/5/2016

Top 50 Java Collections Interview Questions and Answers

What Makes You Stand out from the Crowd

Threads , Lifecycle Explained with Example

Count number of words in the String with Example : Java Program Code

Return to Top
Java Hungry Copyright 2016 All Rights Reserved. Designed by studiopress

http://javahungry.blogspot.com/2015/05/50-java-collections-interview-questions-and-answers.html

80 / 100

Count number of words in the String with Example : Java Program Code | Java Hungry

2/5/2016

JAVA HUNGRY
Java developers tutorials and coding.
Search this blog...
HOME
SCJP

STRING
THREADS

COLLECTIONS

Search

INTERVIEW

BEST JAVA BOOKS

INTERVIEW TIPS

DATA-STRUCTURES

JAVA CODING PROGRAM

MORE JAVA TOPICS

Count Number Of Words In The String With Example : Java


Program Code
To find the number of words in the given String in java is easy . Here
we are using arrays and string class to achieve our goal .
Read Also : Count number of times each alphabet appears in
the String

Secure Connection Failed

The connection to the server was reset while the page w

The page you are trying to view cannot be shown b


Please contact the website owners to inform them

For example :
Original String : "Alive is awesome "
If we pass the above string in the wordcount method then it will return
Output : 3

Try Again
Report this error

as the answer.

Here we are passing String to the wordcount() function which return the int value that is the number of words in
the string .
Read Also : Find first non repeated character in the String with Example

Demo :

http://javahungry.blogspot.com/2013/06/count-number-of-words-in-string-example-java-program-code.html

81 / 100

Count number of words in the String with Example : Java Program Code | Java Hungry

2/5/2016

Please find the code below :

public class StringDemo


{
static int i,c=0,res;
static int wordcount(String s)
{
char ch[]= new char[s.length()]; //in string especially we have to mention the () after length
for(i=0;i<s.length();i++)
{
ch[i]= s.charAt(i);
if( ((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!=' ')&&(i==0)) )
c++;
}
return c;
}
public static void main (String args[])
{
res=StringDemo.wordcount(" manchester united is also known as red devil ");
//string is always passed in double quotes
System.out.println("The number of words in the String are : "+res);
}
}

About The Author


Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry

You might also like


Count total number of times each alphabet appears in the string java program code with example
Difference between HashSet and TreeSet : Java Collections Interview Question
Length of the String without using java built in length method : Java code with example
How to Become a Good Software Programmer : What it takes to stand out from the rest
Recommended by

http://javahungry.blogspot.com/2013/06/count-number-of-words-in-string-example-java-program-code.html

82 / 100

Count number of words in the String with Example : Java Program Code | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2013/06/count-number-of-words-in-string-example-java-program-code.html

83 / 100

Count number of words in the String with Example : Java Program Code | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2013/06/count-number-of-words-in-string-example-java-program-code.html

84 / 100

Count number of words in the String with Example : Java Program Code | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2013/06/count-number-of-words-in-string-example-java-program-code.html

85 / 100

Count number of words in the String with Example : Java Program Code | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2013/06/count-number-of-words-in-string-example-java-program-code.html

86 / 100

Count number of words in the String with Example : Java Program Code | Java Hungry

2/5/2016

WHATS HOT
Difference between Arraylist and Vector : Core Java Interview Collection Question

Best Books for Learning Java

Amazon Interview Question : First Non repeated character in String

Count total number of times each alphabet appears in the string java program code with example

Java 8 new features : Lambda expressions , optional class , Defender methods with examples

Share

Subscribe for Our Newsletter

POPULAR POSTS
Java Interview Questions

http://javahungry.blogspot.com/2013/06/count-number-of-words-in-string-example-java-program-code.html

87 / 100

Count number of words in the String with Example : Java Program Code | Java Hungry

2/5/2016

Top 50 Java Collections Interview Questions and Answers

What Makes You Stand out from the Crowd

Threads , Lifecycle Explained with Example

Count number of words in the String with Example : Java Program Code

Return to Top
Java Hungry Copyright 2016 All Rights Reserved. Designed by studiopress

http://javahungry.blogspot.com/2013/06/count-number-of-words-in-string-example-java-program-code.html

88 / 100

Hashing :How hash map works in java or How get() method works internally | Java Hungry

2/5/2016

JAVA HUNGRY
Java developers tutorials and coding.
Search this blog...
HOME
SCJP

STRING
THREADS

COLLECTIONS

Search

INTERVIEW

BEST JAVA BOOKS

INTERVIEW TIPS

DATA-STRUCTURES

JAVA CODING PROGRAM

MORE JAVA TOPICS

Hashing :How Hash Map Works In Java Or How Get() Method


Works Internally

One of the most darling question of the core java interviewers is How
hash map works in java or internal.implementation of hashmap. Most of
the candidates rejection chances increases if the candidate do not give
the satisfactory explanation . This question shows that candidate has
good knowledge of Collection . So this question should be in your to do The connection to the server was reset while the page w
list before appearing for the interview.
The page you are trying to view cannot be shown b

Secure Connection Failed

Read also How Hashset works in java or How it ensures uniqueness in


java
How Hashmap works in Java

Please contact the website owners to inform them

Try Again
Report this error

HashMap works on the principle of Hashing . To understand Hashing ,


we should understand the three terms first i.e Hash Function , Hash Value and Bucket .
What is Hash Function , Hash Value and Bucket ?
hashCode() function which returns an integer value is the Hash function. The important point to note that ,
this method is present in Object class ( Mother of all class ) .
This is the code for the hash function(also known as hashCode method) in Object Class :
public native int hashCode();
The most important point to note from the above line : hashCode method return int value .
So the Hash value is the int value returned by the hash function .
So summarize the terms in the diagram below :

What is bucket ?
A bucket is used to store key value pairs . A bucket can have multiple key-value pairs . In hash map, bucket
used simple linked list to store objects .

http://javahungry.blogspot.com/2013/08/hashing-how-hash-map-works-in-java-or.html

89 / 100

Hashing :How hash map works in java or How get() method works internally | Java Hungry

2/5/2016

After understanding the terms we are ready to move next step , How hash map works in java or How get()
works internally in java .
Code inside Java Api (HashMap class internal implementation) for HashMap get(Obejct key) method
1. Public V get(Object key)
{
2. if (key ==null)
3. //Some code
4.

int hash = hash(key.hashCode());

5. // if key found in hash table then return value


6. // else return null
}
Hash map works on the principle of hashing
HashMap get(Key k) method calls hashCode method on the key object and applies returned hashValue to its
own static hash function to find a bucket location(backing array) where keys and values are stored in form of a
nested class called Entry (Map.Entry) . So you have concluded that from the previous line that Both key and
value is stored in the bucket as a form of Entry object . So thinking that Only value is stored in the bucket
is not correct and will not give a good impression on the interviewer .
* Whenever we call get( Key k ) method on the HashMap object . First it checks that whether key is null or not .
Note that there can only be one null key in HashMap .
If key is null , then Null keys always map to hash 0, thus index 0.
If key is not null then , it will call hashfunction on the key object , see line 4 in above method i.e. key.hashCode()
,so after key.hashCode() returns hashValue , line 4 looks like
4.

int hash = hash(hashValue)

, and now ,it applies returned hashValue into its own hashing function .
We might wonder why we are calculating the hashvalue again using hash(hashValue). Answer is ,It
defends against poor quality hash functions.
Now step 4 final hashvalue is used to find the bucket location at which the Entry object is stored . Entry object
stores in the bucket like this (hash,key,value,bucketindex) .
Interviewer: What if when two different keys have the same hashcode ?
Solution, equals() method comes to rescue.Here candidate gets puzzled. Since bucket is one and we have two
objects with the same hashcode .Candidate usually forgets that bucket is a simple linked list.
The bucket is the linked list effectively . Its not a LinkedList as in a java.util.LinkedList - It's a separate
(simpler) implementation just for the map .
So we traverse through linked list , comparing keys in each entries using keys.equals() until it return
true. Then the corresponding entry object Value is returned .

http://javahungry.blogspot.com/2013/08/hashing-how-hash-map-works-in-java-or.html

90 / 100

Hashing :How hash map works in java or How get() method works internally | Java Hungry

2/5/2016

One of our readers Jammy asked a very good question


When the functions 'equals' traverses through the linked list does it traverses from start to end one by
one...in other words brute method. Or the linked list is sorted based on key and then it traverses?
Answer is when an element is added/retrieved, same procedure follows:
a. Using key.hashCode() [ see above step 4],determine initial hashvalue for the key
b. Pass intial hashvalue as hashValue in hash(hashValue) function, to calculate the final hashvalue.
c. Final hash value is then passed as a first parameter in the indexFor(int ,int )method .
The second parameter is length which is a constant in HashMap Java Api , represented by
DEFAULT_INITIAL_CAPACITY
The default value of DEFAULT_INITIAL_CAPACITY is 16 in HashMap Java Api .
indexFor(int,int) method returns the first entry in the appropriate bucket. The linked list in the bucket is then
iterated over - (the end is found and the element is added or the key is matched and the value is returned )
Explanation about indexFor(int,int) is below :
/**
* Returns index for hash code h.
*/
http://javahungry.blogspot.com/2013/08/hashing-how-hash-map-works-in-java-or.html

91 / 100

Hashing :How hash map works in java or How get() method works internally | Java Hungry

2/5/2016

static int indexFor(int h, int length) {


return h & (length-1);
}
The above function indexFor() works because Java HashMaps always have a capacity, i.e. number of buckets,
as a power of 2.
Let's work with a capacity of 256,which is 0x100, but it could work with any power of 2. Subtracting 1
from a power of 2 yields the exact bit mask needed to bitwise-and with the hash to get the proper bucket index,
of range 0 to length - 1.
256 - 1 = 255
0x100 - 0x1 = 0xFF
E.g. a hash of 257 (0x101) gets bitwise-anded with 0xFF to yield a bucket number of 1.

Interviewer: What if when two keys are same and have the same hashcode ?
If key needs to be inserted and already inserted hashkey's hashcodes are same, and keys are also same(via
reference or using equals() method) then override the previous key value pair with the current key value pair.
The other important point to note is that in Map ,Any class(String etc.) can serve as a key if and only if it
overrides the equals() and hashCode() method .
Interviewer: How will you measure the performance of HashMap?
According to Oracle Java docs,
An instance of HashMap has two parameters that affect its performance: initial capacity and load factor.
The capacity is the number of buckets in the hash table( HashMap class is roughly equivalent to Hashtable,
except that it is unsynchronized and permits nulls.), and the initial capacity is simply the capacity at the time the
hash table is created.
The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically
increased. When the number of entries in the hash table exceeds the product of the load factor and the current
capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has
approximately twice the number of buckets.
In HashMap class, the default value of load factor is (.75) .
Interviewer : What is the time complexity of Hashmap get() and put() method ?
The hashmap implementation provides constant time performance for (get and put) basic operations
i.e the complexity of get() and put() is O(1) , assuming the hash function disperses the elements properly among
the buckets.
Interviewer : What is the difference between HashMap and ConcurrentHashMap ?
It is also one of the popular interview question on HashMap , you can find the answer here
HashMap vs ConcurrentHashMap
If you still have any doubts then please write in comments .
Source of image : http://ru.wikipedia.org

http://javahungry.blogspot.com/2013/08/hashing-how-hash-map-works-in-java-or.html

92 / 100

Hashing :How hash map works in java or How get() method works internally | Java Hungry

2/5/2016

About The Author


Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry

Share

You might also like


How Remove Method Works Internally in HashMap with Example
Top 10 HashSet Java Interview Questions : Collections
HashMap vs ConcurrentHashMap : Java Collections Interview Question
How ConcurrentHashMap Internally Works in Java with Example
Recommended by

http://javahungry.blogspot.com/2013/08/hashing-how-hash-map-works-in-java-or.html

93 / 100

Hashing :How hash map works in java or How get() method works internally | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2013/08/hashing-how-hash-map-works-in-java-or.html

94 / 100

Hashing :How hash map works in java or How get() method works internally | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2013/08/hashing-how-hash-map-works-in-java-or.html

95 / 100

Hashing :How hash map works in java or How get() method works internally | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2013/08/hashing-how-hash-map-works-in-java-or.html

96 / 100

Hashing :How hash map works in java or How get() method works internally | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2013/08/hashing-how-hash-map-works-in-java-or.html

97 / 100

Hashing :How hash map works in java or How get() method works internally | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2013/08/hashing-how-hash-map-works-in-java-or.html

98 / 100

Hashing :How hash map works in java or How get() method works internally | Java Hungry

2/5/2016

http://javahungry.blogspot.com/2013/08/hashing-how-hash-map-works-in-java-or.html

99 / 100

Hashing :How hash map works in java or How get() method works internally | Java Hungry

2/5/2016

WHATS HOT
Difference between Arraylist and Vector : Core Java Interview Collection Question

Best Books for Learning Java

Amazon Interview Question : First Non repeated character in String

Count total number of times each alphabet appears in the string java program code with example

Java 8 new features : Lambda expressions , optional class , Defender methods with examples

Tweet

Subscribe for Our Newsletter

POPULAR POSTS
Java Interview Questions

Top 50 Java Collections Interview Questions and Answers

What Makes You Stand out from the Crowd

Threads , Lifecycle Explained with Example

Count number of words in the String with Example : Java Program Code

Return to Top
Java Hungry Copyright 2016 All Rights Reserved. Designed by studiopress

http://javahungry.blogspot.com/2013/08/hashing-how-hash-map-works-in-java-or.html

100 / 100

Вам также может понравиться