Articles

Top 20 java interview questions and answers for freshers

Top 20 java interview questions and answers for freshers


In this article, we are going to share with our java aspirants the top 20 java interview questions that are frequently asked in any java interview. These questions are basic questions that checks your understanding on the core and basic concepts of java.

Experience required to answer below java question: Freshers or upto 3 years of experienced in java development.


1. Suppose you are given a list that contains duplicate elements. How you can remove the duplicates with the use of Collection itself?

If you are not allowed to remove elements from list (say linkedlist, arraylist) either manually or by iterating over it then you can simply go for - Set.

As we know, Set doesn't allow duplicate elements in it so if we store all the element contained in the list into set then duplicates would automatically be removed.

 

Follow the example given below to convert list to set in java.

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class ListToSet {

	public static void main(String[] args) {
		List

OUTPUT

Arraylist[Rajneesh, Mukesh, Mukesh, Puja, Simmi]
Converted Set[Simmi, Rajneesh, Puja, Mukesh]

 

You can see that duplicate element "Mukesh" is removed when List is converted to Set.


2. You are asked to define a list that would mostly involve in updation process like addition and deletion of elements frequently. Which list would you prefer for such tasks?

Linked list is mostly prefered in such scenarios.

Because for updation process like add and remove elements in java, if we use arraylist then lots of shifting needs to be carried out to complete the update process. This would be time consuming and makes the application slow.

But since linked list doesn't require shifting of elements so it provides faster operation while adding and removing elements in java.

 


3. What is the difference between arraylist and linkedlist in java?

Given below is the major difference between arraylist and linkedlist in java:

  • Arraylist implements list interface whereas linkedlist implements both the list and queue interface.
  • Arraylist can only act as a list but linkedlist can act as both list and queue (since it implements both the list and queue interface)
  • Arraylist uses dynamic array to store elements while linkedlist uses doubly linked list to store the elements.

Given is the link that contains more questions on collection in java.


4. Why is iterator considered as fail-fast in java?

Iterator is considered as fail-fast as it immediately throws concurrent modification exception, if it senses that the collection on which it is iterating currently is attempted to be modified by any other thread from outside. 

 

Fail fast features ensures that if iterator feels that modification of collection would result in anamolous behaviour at any point of time in future, it fails immediately.

Example of fail-fast iterator

package FailFastIterator;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class FailFastItr {

	public static void main(String[] args) {
		List

OUTPUT:

Java
C++
Python
Exception in thread "main" java.util.
ConcurrentModificationException
at java.util.ArrayList$Itr.
checkForComodification(Unknown Source)
at java.util.
ArrayList$Itr.next(Unknown Source)
at FailFastIterator.
FailFastItr.main(FailFastItr.java:18)
 

 

Another question that can follow this one is:

What is fail-safe feature in java?


5. Show an example of traversal over hash map?

This question is asked to simply check whether you understand the mechanism of hashmap or not. You should be aware that hashmap stores element as key, value pair as Map.Entry

Given below is a program that shows the way we can traverse over hashmap in java.

package HashMap;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HashMapTraversal {

	public static void main(String a[]){

		Map m = new HashMap();

		m.put("a", 1);
		m.put("b", 2);
		m.put("c", 3);
		m.put("d", 4);
		m.put("e", 55);
		// m.put("a", 5);   //Error: key needs to be unique in Map

		Iterator k = m.keySet().iterator();  //keyset just fetches the key not the value

		while (k.hasNext()){
			System.out.println(k.next());
		}

		Iterator i = m.entrySet().iterator();

		while(i.hasNext()){

			Map.Entry entry = (Map.Entry) i.next();
			System.out.println("Key : " + entry.getKey() + " Value :" + entry.getValue());

		}

	}

}

Output:

a
b
c
d
e
Key : a Value :1
Key : b Value :2
Key : c Value :3
Key : d Value :4
Key : e Value :55

 


6. Name few synchronized collection classes in java?

Given below are few synchronized collection classes in java:

  • Vector - It is an obsolete class and not recommended to be used currently.
  • Hashtable - It is also a legacy class and not recommended to be used.
  • CopyOnWriteArrayList
  • ConcurrentHashMap

7. What is the base class of all the java classes?

java.lang.Object class is the base class of all the classes in java


8. Which collection allows you to traverse over any list in both forward and backward directions in java?

ListIterator allows to iterator over any list in both the directions. 

 


9. How many instance of abstract class can be created?

Zero.

Abstract class cannot be instantiated in java. 

 

Interface cannot be instantiated as well. 

If you have around 3 years of experience you must know this.

10. Why multiple inheritance is not supported in java?

To reduce ambiguity, java doesn't support multiple inheritance.

Read more on this topic about how ambiguity arises - follow the link 


11. How can we achieve abstraction in java?

Abstraction in java can be achieved in two ways - partial and complete abstraction.

partial abstraction: Abstract class helps achieve partial to complete abstraction. 

complete abstraction (100% abstraction): Interface helps in achieving complete abstraction in java.

 


12. What is the difference between method overloading and method overriding in java?

Given below is the major difference between method overloading and method overriding in java:

  • Method overloading occurs when a method with same name is invoked with different parameters or parameters with different return type whereas method overriding occurs when sub-class implements method of super-class with exactly same type signature as its parent class.
  • Inheritance is not required for method overloading whereas method overriding occurs only in sub-class that inherits a super-class and tries to give its own specific implementation to parent class method.

Detailed Reading: method overloading

Detailed Reading: method overriding

This question is mostly asked to freshers.


13. Abstract class vs Interface in java?

Given below is the detailed explanation of differences between abstract class and interface in java:

  • Abstract class is declared using 'abstract' keyword while interface is declared using 'interface' keyword in java.
  • Abstract class helps in achieving partial to complete abstraction while interface helps achieve complete abstraction in java.
  • Abstract class can contain both abstract and non abstract methods while interface contains only abstract methods.
  • Abstract class is a class and can be extended by any other class whereas interface can only be implemented by any class.

Detailed Reading: Abstract class

Detailed Reading: Interface


14. Why String is immutable in java?

We have provided detailed explanation to this question in String section of our java tutorial. Click to read the answer - why String is immutable in java

3 years experienced candidates must be able to explain it clearly.


15. Given a String str = "I love java programming". Write a java program to split the str on each space. So desired output is words split as splitStr[] = {"I", "love", "java", "programming"}

Given below is a java program that demonstrates the use of split method:

package string;

public class splitDemo {

	public static void main(String[] args) {
		String strDemo = "I love java programming";

		String[] strArray = strDemo.split("\\s");

		for(String s : strArray){
			System.out.println(s);
		}
	}
}

OUTPUT

I
love
java
programming

16. String builder vs String buffer in java

Given below is the difference between string builder and string buffer in java:

  • String builder is not synchronized while String buffer is synchronized or thread safe.
  • String builder is faster in comparison to string buffer as it is not synchronized.

17. What are the methods provided by Object class in java?

There are lots of methods provided by Object class as listed below:

  • clone()
  • equals()
  • finalize()
  • notify()
  • notifyAll()
  • wait()
  • getClass()
  • hashCode()
  • toString()

Given above are almost all the methods that are provided by Object class.

Both the freshers and experienced should note it down.


18. Why java is considered platform independent?

Java is considered platform independent as it exhibits write once, run anywhere. This is due to bytecode which can be executed on any system that has JVM (Java Virtual Machine) installed on it. 

Read more on java platform independence here

 


19. What is checked exception in java?

Checked exception are those exceptions that are checked at the compile time. Examples of checked exception include IOException, SQLException, ClassNotFoundException

Detailed answer to checked exception is given in our java tutorial

 


20. Checked vs Unchecked Exception in java?

Given below is the major difference between checked exception and unchecked exception in java: 

  • Checked exception are all the exception that are checked at compile time whereas unchecked exception are checked at runtime.
  • Example of checked exception is IOException, SQLException, ClassNotFoundException whereas example of unchecked exceptions are ArithmeticException, IndexOutOfBoundException, NullPointerException

Detailed Reading: Checked Exception

Detailed Reading: Unchecked Exception


This is all for this article that consists of frequently asked java interview questions

You should know answer to each of the above questions in-depth to ensure your selection in the interview.

 

We have already provided java interview questions that consists of more that 200 questions along with answers provided. To revise all those questions as well, we request you to follow the below link.


Java Interview Questions

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Sonu Pandit
Technology geek, loves to write and share knowledge with the world. Having 10+ years of IT experience. B.Tech in Computer Science & Engineering
Page Views :    Published Date : Jun 28,2020  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!