Here I am providing some important core java interview questions with answers.
Table of Contents
- 1. What do you mean by Platform independence of java?
- 2. What is difference between JVM, JRE and JDK ?
- 3. What are memory areas allocated in JVM?
- 4. What are some core concepts of OOPS in Java ?
- 5. What is Abstraction?
- 6. What is encapsulation?
- 7. What is Polymorphism in java?
- 8. What is inheritance in java?
- 9. What is constructor in java?
- 10. Can we declare constructor as final?
- 11. What is immutable object in java?
- 12. Why String is declared final or immutable in java?
- 13. What are access modifier available in java?
- 14. What is difference between Abstract class and interface?
- 15. Can one interface implement another interface in java?
- 16. What is marker interface?
- 17. What is method overloading and method overriding in java?
- 18. Can you override static methods in Java?
- 19. Can you override private methods in Java?
- 20. Difference between path and classpath in java?
- 21. What is difference between StringBuffer and StringBuilder in java?
- 22. What are methods you should override when you put an object as key in HashMap?
- 23. Can you explain internal working of HashMap in java?
- 24. Why java uses another hash function internally to calculate hash value apart from hashcode method which you have implemented?
- 25. What if you don’t override hashcode method while putting custom objects as key in HashMap?
- 26. Can you explain internal working of HashSet in java?
- 27. What are differences between HashMap and HashSet in java?
- 28. Can you explain internal working of ConcurrentHashMap in java?
- 29. Do we have lock while getting value from ConcurrentHashMap?
- 30. How do you sort Collection of custom objects in java?
- Â 31. What are differences between ArrayList and LinkedList in java?
- 32. What is Enum in java?
- 33. How do you create custom exception in java?
- 34.What is difference between Checked Exception and Unchecked Exception?
- 35. Can we have try without catch block in java ?
- 36. What are ways to create a thread in java ?
- 37. What are differences between Sleep and wait in java?
- 38. Define states of thread in java?
- 39. Can we call run method directly to start a thread?
- 40. Can we start a thread twice in java?
- 41. What is CountDownLatch in java?
- 42. What is difference between CountDownLatch and CyclicBarrier?
- 43. Why wait, notify and nofiyAll method belong to object class ?
- 44. Can you call wait, notify and notifyAll from non synchronized context?
- 45. What is the difference between creating String as new() and literal?
- 46. What is Covariant return type in java?
- 47. What is garbage Collection?
- 48. What is System.gc()?
- 49. What is use of finalize() method in object class?
- 50.What is difference between final, finally and finalize in Java?
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 ?
3. What are memory areas allocated in JVM?
- 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 :
- Encapsulation
- Polymorphism
- Abstraction
- Inheritance
5. What is Abstraction?
Abstraction is achieved using interface and abstract class in Java.
You can read about abstraction for more details..
6. What is encapsulation?
7. What is Polymorphism in java?
8. What is inheritance in java?
9. What is constructor in java?
Constructor can be considered a special code which is used to initiaze objects.It has two main points
- Class and Constuctor name should match
- Constructor should not have any return type else it will be same as method.
You can read more about Constructor in Java.
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?
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
13. What are access modifier available in java?
14. What is difference between Abstract class and interface?
15. Can one interface implement another interface in java?
16. What is marker interface?
17. What is method overloading and method overriding in java?
Method overloading :Â Method overloading is concept that allows a class to have same method name but diferent method arguments. Method overloading is also known as compile time polymorphism.
Method overriding :Â If child class contain same method as parent class with same method signature. This is called method overriding. Method overriding is also known as dynamic polymorphism.
18. Can you override static methods in Java?
No, you can not override static methods in Java. You can create same method in child class but it won’t be dynamic polymorphism. It will be method hiding. Static methods belong at class level not at object level hence you can not override static method.
19. Can you override private methods in Java?
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.
Let’s see the structure of entry class Entry Structure.
1 2 3 4 5 6 7 8 9 10 |
static class Entry implements Map.Entry { final K key; V value; Entry next; final int hash; ...//More code goes here } |
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 gets 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 the 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?
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?
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
|
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 a HashMap. ConcurrentHashMap does not lock whole object , it just lock part of it i.e. Segment.
Structure of Segment:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
/** * Segments are specialized versions of hash tables. This * subclasses from ReentrantLock opportunistically, just to * simplify some locking and avoid separate construction. */ static final class Segment extends ReentrantLock implements Serializable { /** * The per-segment table. */ transient volatile HashEntry[] table; // other methods and variables } |
It stores a key value pair in a class called HashEntry which is similar to Entry class in HashMap.
1 2 3 4 5 6 7 8 9 |
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?
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?
34.What is difference between Checked Exception and Unchecked Exception?
You can refer difference between checked exception and unchecked exception for more details.
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 the 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?
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 wait, notify and notifyAll 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?
1 2 3 4 5 |
String str1=new String("hello"); String str2=new String("hello"); System.out.println(str1==str2); |
false
as str1
and str2
will point to different object
1 2 3 4 5 |
String str1="helloworld"; String str2="helloworld"; System.out.println(str1==str2); |
str1
and str2
will point to the same object in String constant pool.46. What is 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
package org.arpit.java2blog; public class BaseClass { public A m1() { System.out.println("In BaseClass method"); return new A(); } public static void main(String args[]) { BaseClass b=new SubClass(); b.m1(); } } class SubClass extends BaseClass { public B m1() { System.out.println("In SubClass method"); return new B(); } } class A { } class B extends A { } |
47. What is garbage Collection?
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.
That’s all about core java interview questions.