Skip to main content

Core java interview questions and answers

Core java interview questions and answers


Core java interview questions play a vital role in java/j2EE interviews. Whether you are fresher or experienced, you are going to face core java interview questions. You can also go through top java interview programs for practicing java programs.
Here I am providing some important core java interview questions with answers.

1. What do you mean by Platform independence of java?

You can write and compile program in one Operating system and run in other operating system.
For example:
You can compile program in Windows and can run it in Unix.

2. What is difference between JVM, JRE and JDK ?

JVM : JVM stands for Java Virtual Machine. It is virtual machine which actually runs the byte code.
JRE : JRE stands for Java Runtime Environment. It provides runtime environment for java code. It has JVM , libraries such as rt.jar and other files.
JDK : JDK stands for Java development kit. It is superset of JRE, it has JRE + compilation and debugging tools(javac and java).

3. What are memory areas allocated in JVM?

Memory areas allocated in JVM are:
  • Heap area
  • Method area
  • JVM language stacks
  • Program counter (PC) register
  • Native method stacks

4. What are some core concepts of OOPS in java ?

Core concepts of OOPs are :
  • Polymorphism
  • Abstraction
  • Encapsulation
  • Inheritance

5. What is Abstraction?

Abstraction is a concept of exposing essential information and hiding implementation details.
For example: 
When you see a car, you know it is running but how it running internally, you may not aware of it.
This is Abstraction. You just expose required details.

6. What is encapsulation?

Encapsulation is process of wrapping data and function into single unit. You can use access modifier for variables, so other classes may not access it directly but it can be accessed only through public methods of the class. You can create class fully encapsulated using private variables.

7. What is Polymorphism in java?

Polymorphism means one name many forms. It is concept by which you can perform same action in different ways. Method overloading and method overriding are example of Polymorphism.

8. What is inheritance in java?

Inheritance allows use of properties and methods of another class (Parent class), so you can reuse all methods and properties.

9. What is constructor in java?

Constructor is block of code which allows you to create instance of the object. It does not have return type.
It has two main points
  • Constructor name should be same as class
  • Constructor should not have any return type else it will be same as method.

10. Can we declare constructor as final?

No, Constructor can not be declared as final. If you do so, you will get compile time error.

11. What is immutable object in java?

Immutable object is object whose state can not be changed once created. You can take String object as example for immutable object.

12. Why String is declared final or immutable in java?

There are various reasons to make String immutable.
  • String pool
  • Thread Safe
  • Security
  • Class Loading
  • Cache hash value
You can refer why String is immutable in java for more details.

13. What are access modifier available in java?

It Specifies accessibility of variables, methods , constructor of class.
There are four access modifier in java
Private : Accessible only to the class.
Default : Accessible in the package.
Protected : Accessible in the packages and its subclasses.
Public : Accessible everywhere

14. What is difference between Abstract class and interface?

Parameter
Abstract class
Interface
Default method Implementation
It can have default method implementation
Interfaces are pure abstraction.It can not have implementation at all but in java 8, you can have default methods in interface.
Implementation
Subclasses use extends keyword to extend an abstract class and they need to provide implementation of all the declared methods in the abstract class unless the subclass is also an abstract class
subclasses use implements keyword to implement interfaces and should provide implementation for all the methods declared in the interface
Constructor
Abstract class can have constructor
Interface  can not have constructor
Different from normal java class
Abstract classes are almost same as java classes except you can not instantiate it.
Interfaces are altogether different type
Access Modifier
Abstract class methods can have public ,protected,private and default modifier
Interface methods are by default public. you can not use any other access modifier with it
Main() method
Abstract classes can have main method so we can run it
Interface do not have main method so we can not run it.
Multiple inheritance
Abstract class can extends one other class and can implement one or more interface.
Interface can extends to one or more interfaces only
Speed
It is faster than interface
Interface is somewhat slower as it takes some time to find implemented method in class
Adding new method
If you add new method to abstract class, you can provide default implementation of it. So you don’t need to change your current code
If you add new method to interface, you have to change the classes which are implementing that interface
You can refer difference between Abstract class and interface for more details.

15. Can one interface implement another interface in java?

No, One interface can not implement another interface. It can extend it using extends keyword.

16. What is marker interface?

Marker interfaces are interfaces which have no method but it is used to indicate JVM to behave specially when any class implement these interfaces.
For example : If you implement cloneable interface and then call .clone method of object, it will clone your object. If you do not implement cloneable interface, it will throw cloneNotSupported exception.

17. What is method overloading and method overriding in java?

Method overloading :If two or more methods have same name , but different argument then it is called method overloading.

Method overriding : If subclass is having same method as base class then it is known as method overriding Or in another words, If subclass provides specific implementation to any method which is present in its one of parents classes then it is known as method overriding

18. Can you override static methods in java?

No, you can not override static methods in java. Static methods belongs to class level not at object level.You can create static method with same name in child class and it won’t give you compilation error but it is called method hiding. You won’t get overriding behaviour with it.

19. Can you override private methods in java?

No, you can not override private methods in java. Private methods are not visible to child class, hence you can not override it , you can only hide it.

20. Difference between path and classpath in java?

Parameter
Path
classpath
Locate
It allows operating system to locate executable such as javac, java
It allows classloader to locate all .class file used by program
Overriding
You can not override path variable with java setting
You can override classpath by using -cp with java,javac or class-path in manifest file.
Inclusion
You need to include bin folder of jdk (For example jdk1.7.1/bin)
You need to include all the classes which is required by program
Used by
Operating system
java classloaders
You can refer difference between Path and ClassPath in java for more details.

21. What is difference between StringBuffer and StringBuilder in java?

Parameter
StringBuffer
StringBuilder
Thread-safe
StringBuffer is thread safe. Two threads can not call methods of StringBuffer simultaneously.
StringBuilder is not thread safe, so two threads can call methods of StringBuilder simultaneously.
Performance
It is less performance efficient as it is thread-safe
It is more performance efficient as it is not thread-safe.

22. What are methods you should override when you put an object as key in HashMap?

You need to implement hashcode() and equals() method , if you put key as object in HashMap. You can go through hashcode and equals method in java for more details.

23. Can you explain internal working of HashMap in java?

  • There is an Entry[] array called table which has size 16.
  • This table stores Entry class’s object. HashMap class has a inner class called Entry.This Entry have key value as instance variable.
Lets see structure of entry class Entry Structure.
Whenever we try to put any key value pair in hashmap, Entry class object is instantiated for key value and that object will be stored in above mentioned Entry[](table). Now you must be wondering, where will above created Entry object get stored(exact position in table). The answer is, hash code is calculated for a key by calling Hashcode() method. This hashcode is used to calculate index for above Entry[] table.
You can read How HashMap works internally in java for more details.

24. Why java uses another hash function internally to calculate hash value apart from hashcode method which you have implemented?

It is due to avoid large number of collisions due to bad hashcode method written by developers.
You can refer hash method of HashMap for more details.

25. What if you don’t override hashcode method while putting custom objects as key in HashMap?

As we did not implement hashcode method, each object will have different hashcode(memory address) by default, so even if we have implemented equals method correctly, it won’t work as expected.

26. Can you explain internal working of HashSet in java?

HashSet internally uses HashMap to store elements in HashSet. It uses PRESENT as dummy object as value in that HashMap. HashSet uses HashMap to check duplicates in the HashSet.
You can refer How HashSet works internally in java for more details

27. What are differences between HashMap and HashSet in java?

Parameter
HashMap
HashSet
Interface
This is core difference among them.HashMap implements Map interface
HashSet implement Set interface
Method for storing data
It stores data in a form of key->value pair.So it uses put(key,value) method for storing data
It uses add(value) method for storing data
Duplicates
HashMap allows duplicate value but not duplicate keys
HashSet does not allow duplicate values.
Performance
It is faster than hashset as values are stored with unique keys
It is slower than HashMap
HashCode Calculation
In hash map hashcode value is calculated using key object
In this,hashcode is calculated on the basis of value object. Hashcode can be same for two value object so we have to implement equals() method.If equals() method return false then two objects are different.

28. Can you explain internal working of ConcurrentHashMap in java?

ConcurrentHashMap uses concept of Segments to store elements. Each Segment logically contains an HashMap. ConcurrentHashMap does not lock whole object , it just lock part of it i.e. Segment.
Structure of Segment:
It stores a key value pair in a class called HashEntry which is similar to Entry class in HashMap. static final class HashEntry {         final K key;         final int hash;         volatile V value;         final HashEntry next; }
You can refer internal working of ConcurrentHashMap in java for more details

29. Do we have lock while getting value from ConcurrentHashMap?

There is no lock while getting values from ConcurrentHashMap.Segments are only for write operation.In case of read operation, it allows full concurrency and provides most recently updated value using volatile variables.

30. How do you sort Collection of custom objects in java?

We need to implement comparable interface to custom object class(Lets say Country) and then implement compareTo(Object o) method which will be used for sorting. It will provides default way of sorting custom objects.
If we want to sort custom object (Lets say country) on different attributes such as name,population etc.We can implement Comparator interface and can be used for sorting.
For more details,you can go through following links:

 31. What are differences between ArrayList and LinkedList in java?

Parameter
ArrayList
LinkedList
Internal data structure
It uses dynamic array to store elements internally
It uses doubly Linked List to store elements internally
Manipulation
If  We need to insert or delete element in ArrayList, it may take O(n), as it internally uses array and we may have to shift elements in case of insertion or deletion
If  We need to insert or delete element in LinkedList, it will take O(1), as it internally uses doubly LinkedList
Search
Search is faster in ArrayList as uses array internally which is index based. So here time complexity is O(1)
Search is slower in LinkedList as uses doubly Linked List internally So here time complexity is O(n)
Interfaces
ArrayList implements List interface only, So it can be used as List only
LinkedList implements List,Deque interfaces, so it can be used as List,Stack or Queue
 
You can refer difference between ArrayList and LinkedList in java for more details.

32. What is Enum in java?

Java Enum is special data type which represents list of constants values. It is a special type of java class. It can contain constant, methods and constructors etc.
You can refer Enum in java for more details.

33. How do you create custom exception in java?

You just need to extends Exception class to create custom exception.
Lets understand this with example.You have list of counties and if You have “USA” in list of country, then you need to throw invalidCountryException(Our custom exception).
Example: 
Create InvalidCountryException.java as below

Create POJO class called Country.java

Lets create CountryCheckMain.java. This class will have main method.

When you run above program, you will get following output:

As you can see, if we have “USA” in list of Countries,we are throwing InvalidCountryException.

34.What is difference between Checked Exception and Unchecked Exception?

Checked Exception: Checked exceptions are those exceptions which are checked at compile. If you do not handle them , you will get compilation error.
For example: IOException
Unchecked Exception : Unchecked exceptions are those exceptions which are not checked at compile time. Java won’t complain if you do not handle the exception.
For example: NullPointerException, ArrayIndexOutOfBoundsException

35. Can we have try without catch block in java ?

Yes, we can have try without catch block by using finally block. You can use try with finally. As you know finally block always executes even if you have exception or return statement in try block except in case of System.exit().
You can refer Try with finally block for more details.

36. What are ways to create a thread in java ?

There are two ways to create a thread in java
  • By extending thread class
  • By implementing Runnable interface.

37. What are differences between Sleep and wait in java?

Parameter
wait
sleep
Synchonized
wait should be called from synchronized context i.e. from block or method, If you do not call it using synchronized context, it will throw IllegalMonitorStateException
It need not be called from synchronized block or methods
Calls on
wait method operates on Object and defined in Object class
Sleep method operates on current thread and is in java.lang.Thread
Release of lock
wait release lock of object on which it is called and also other locks if it holds any
Sleep method does not release lock at all
Wake up condition
until call notify() or notifyAll() from Object class
Until time expires or calls interrupt()
static
wait is non static method
sleep is static method
You can refer difference between sleep and wait in java for more details.

38. Define states of thread in java?

There are 5 states of thread in java
New : When you create a thread object and it is not alive yet.
Runnable:  When you call start method of thread, it goes into Runnable state. Whether it will execute immediately or execute after some times , depends on thread scheduler.
Running : When thread is being executed, it goes to running state.
Blocked : When thread waits for some resources or some other thread to complete (due to thread’s join), it goes to blocked state.
Dead: When thread’s run method returns, thread goes to dead state.

39. Can we call run method directly to start a thread?

No, you can not directly call run method to start a thread. You need to call start method to create a new thread. If you call run method directly , it won’t create a new thread and it will be in same stack as main.
You can refer can we call run method directly to start a thread for more details

40. Can we start a thread twice in java?

No, Once you have started a thread, it can not be started again. If you try to start thread again , it will throw IllegalThreadStateException.
You can refer can we start thread twice for more details

41. What is CountDownLatch in java?

As per java docs, CountDownLatch is synchronisation aid that allow one or more threads to wait until set of operations being performed in other threads completes. So in other words, CountDownLatch waits for other threads to complete set of operations.
CountDownLatch is initialized with count. Any thread generally main threads calls latch.awaits() method, so it will wait for either count becomes zero or it’s interrupted by another thread and all other thread need to call latch.countDown() once they complete some operation.
So count is reduced by 1 whenever latch.countDown() method get called, so if count is n that means count can be used as n threads have to complete some action or some action have to be completed n times.
You can refer CountDownLatch in java with example for more details.

42. What is difference between CountDownLatch and CyclicBarrier?

Parameter
CountDownLatch
CyclicBarrier
Reuse
It can not be reused once count reaches 0
It can be reinitialized once parties reaches to 0, so it can reused
Method 
It calls countDown() method to reduce the counter
It calls await() method to reduce the counter.
Common Event
It can not trigger common event when count reaches 0
It can trigger common event (Runnable) once reaches to a barrier point. Constructor :CyclicBarrier(int parties, Runnable barrierAction)
Constructor
CountDownLatch(int count)
CyclicBarrier(int parties)

43. Why wait, notify and nofiyAll method belong to object class ?

In java, we put locks on shared objects not on thread, so these methods are present in Object class. As every object have mutex(lock), it make sense to put these methods in object class.

44. Can you call wait, notify and notifyAll from non synchronized context?

No, you can not call wait, notify and notifyAll from non synchronized context. If you do so, it will throw IllegalMonitorStateException.

45. What is the difference between creating String as new() and literal?

If you create a String using new operator, it is not interned. It will  create new object in heap memory even if String object already exists with same content.
It will return false as str1 and str2 will point to different object
If you create a String using assignment operator, it goes to the String constant pool and it is interned. If you create another String with same content, both will reference to same object in String constant pool.
It will return true as str1 and str2 will point to same object in String constant pool.

46. What are Covariant return type in java?

Covariant return type means if subclass overrides any method, return type of this overriding method can be subclass of return type of base class method.
For example:
Above example is perfect example of covariant return type.

47. What is garbage Collection?

Garbage Collection is a process of looking at heap memory and deleting unused object present in heap memory. Garbage Collection frees unused memory. Garbage Collection is done by JVM.

48. What is System.gc()?

This method is used to invoke garbage collection for clean up unreachable object but it is not guaranteed that when you invoke System.gc(), garbage collection will definitely trigger.

49. What is use of finalize() method in object class?

Finalize method get called when object is being collected by Garbage Collector. This method can be used to write clean code before object is collected by Garbage Collector.

50.What is difference between final, finally and finalize in Java?

final : Final is a keyword which is used with class to avoid being extended, with instance variable so they can not reassigned, with methods so that they can not be overridden.
finally : Finally is a keyword used with try, catch and finally blocks. Finally block executes even if there is an exception. It is generally used to do some clean up work.
finalize :  Finalize is a method is used to invoke garbage collection for clean up unreachable object but it is not guaranteed that when you invoke System.gc(), garbage collection will definitely trigger.

Comments

Popular posts from this blog

Mockito interview Questions

1.       Question 1. What Is Mockito? Answer : Mockito allows creation of mock object for the purpose of Test Driven Development and Behavior Driven development. Unlike creating actual object, Mockito allows creation of fake object (external dependencies) which allows it to give consistent results to a given invocation. 2.       Question 2. Why Do We Need Mockito? What Are The Advantages? Answer : Mockito differentiates itself from the other testing framework by removing the expectation beforehand. So, by doing this, it reduces the coupling. Most of the testing framework works on the "expect-run-verify". Mockito allows it to make it "run-verify" framework. Mockito also provides annotation which allows to reduce the boilerplate code. 3.       Question 3. Can You Explain A Mockito Framework? Answer : In Mockito, you always check a particular class. The dependency in that class is injected using m...

JAVA Expert Interview Questions Answers 2017

Java Basics ::  Interview Questions and Answers Home  »  Interview Questions  »  Technical Interview  »  Java Basics  » Interview Questions 1.     What is the difference between a constructor and a method? A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator. 2.     What is the purpose of garbage collection in Java, and when is it used? The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. 3.  ...

Java Example Program to Convert List to Set

import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class ListToSet {  /**   * @author Amarjit Kumar   * @category interview questions   *   * Description: Convert List to set in java with example program   *   */  public static void main(String[] args) {   ArrayList<String> arrList= new ArrayList<>();   arrList.add("Java");   arrList.add("Java");   arrList.add("List to String");   arrList.add("Example Program");   Set<String> strSet = new HashSet<String>(arrList);   System.out.println(strSet);   System.out.println(arrList);  } } /*  * Java program to convert list to set. Convert ArrayList of string to HashSet  * in java example program How to convert List to Set in java Set<String> strSet  * = new HashSet<String>(arrList); HashSet having a constructor which will take  * list as an ar...