20 Core Java Interview Questions for Fresher, 1 to 2 Yrs Exp

1. Which data type you should use to represent currency in Java?

Answer – Please tell him/her long or BigDecimal because if you say double, then you need to convince them about rounding and how do you avoid floating point issues.

This is one of common mistake we make until they are familiar with the BigDecimal class in java. In Java programming, we have been told that use float and double to represent decimal numbers its not been told that result of floating point number is not exact, which makes them unsuitable for any financial calculation which requires exact result and not the approximation.

float and double are designed for engineering and scientific calculation and many times don’t produce exact result also the result of floating point calculation may vary from JVM to JVM. Look at below example of BigDecimal and double primitive which is used to represent money value, it’s quite clear that floating point calculation may not be exact and one should use BigDecimal for financial calculations.

Output –

difference between 3.15 and 2.10 using double is: 1.0499999999999998
difference between 2.15 and 1.0 using BigDecimal is: 1.05

From above example of floating point calculation is pretty clear that result of floating point calculation may not be exact at all time and it should not be used in places where the exact result is expected.

 

2. What is the difference between Overloading and Overriding in Java?

There are many points what you can explain to the interviewer in an interview. For better understanding, you can learn Method Overloading in Java and Method Overriding in Java tutorials.

 

3. Why is String immutable in Java?

The string is Immutable in Java because String objects are cached in String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client’s action would affect all another client. For better understanding visit Why String is Immutable in Java

 

4. What is the difference between ArrayList and LinkedList in Java?

You can easily differentiate the ArrayList and LinkedList in Java in terms of Insertion complexity, Search performance, Delete Operation Performance and much more, for more details visit Difference in ArrayList and LinkedList in Java

 

5. Can we create the Object of Abstract Class in Java?

As per Java, We can’t create the Object of Abstract Class directly. But we can create the Object of Abstract Class in Java indirectly. You can see here, How can we create the Object of Abstract Class

 

6. What is the difference between wait and sleep in Java?

The main difference between wait and sleep is that wait() method release the acquired monitor when the thread is waiting on the other hand Thread.sleep() method keeps the lock or monitor even if the thread is waiting. Also, wait for method in Java should be called from synchronized method or block while there is no such requirement for sleep() method.

Another difference is Thread.sleep() method is a static method and applies on current thread, while wait() is an instance specific method and only got wake up if some other thread calls notify method on same object. also, in the case of sleep, sleeping thread immediately goes to Runnable state after waking up while in the case of wait, waiting for a thread first acquires the lock and then goes into Runnable state. So based upon your need, if you want to pause a thread for specified duration then use sleep() method and if you want to implement inter-thread communication use wait method.
Here is the list of difference between wait and sleep in Java :

1) wait is called from synchronized context only while sleep can be called without synchronized block. see Why to wait and notify needs to call from synchronized method for more detail.

2) waiting thread can be awake by calling notify and notifyAll while sleeping thread can not be awakened by calling notify method.

3) wait is normally done on condition, Thread wait until a condition is true while sleep is just to put your thread to sleep.

4) wait for release lock on an object while waiting while sleep doesn’t release lock while waiting.

5) The wait() method is called on an Object on which the synchronized block is locked, while sleep is called on the Thread.

 

7. What is the difference between “==” and equals() method in Java??

  • == -> is a reference comparison, i.e. both objects point to the same memory location
  • .equals() -> evaluates to the comparison of values in the objects

The equals() method compares the “value” inside String instances (on the heap) irrespective if the two object references refer to the same String instance or not. If any two object references of type String refer to the same String instance then great! If the two object references refer to two different String instances .. it doesn’t make a difference. It’s the “value” (that is: the contents of the character array) inside each String instance that is being compared.

On the other hand, the “==” operator compares the value of two object references to see whether they refer to the same String instance. If the value of both object references “refer to” the same String instance then the result of the boolean expression would be “true”..duh. If, on the other hand, the value of both object references “refer to” different String instances (even though both String instances have identical “values”, that is, the contents of the character arrays of each String instance are the same) the result of the boolean expression would be “false”.

For more Details please refer String Class in Java.

 

8. What happens if you compare an object to null using equals()?
When a null object is passed as an argument to equals() method, it should return false, it must not throw NullPointerException, but if you call equals method on reference, which is null it will throw NullPointerException. That’s why it’s better to use == operator for comparing null e.g. if(object != null) object.equals(anohterObject). By the way, if you comparingString literal with another String object then you better call equals() method on the String literal rather than known object to avoid NPE, one of those simple tricks to avoid NullPointerException in Java.

 

9. Difference between List and Set in Java ?

List is ordered, allows duplicates and indexed, Set is unordered, don’t allow duplicates, you can find it in more details List in Java and Set in Java.

 

10. How do you make a class Immutable in Java?

  1. Create a final class.

  2. Make the class properties final and private.

  3. Set the class properties values using constructor only.

  4. Don’t declare any setter method for the class properties.

Now your class is Immutable.

 

11. When to use abstract class and interface in Java?

Use interface for type declaration, use the abstract class if evolution is the concern. For more details please find Interface in Java and Abstract Class in Java .

 

12. The difference between Hashtable and HashMap in Java?

HashTable and HashMap, both have the different implementation. You can see the Detailed difference between HashTable and HashMap here.

 

13. What kind of reference types are exists in Java?

The answer is a Strong reference, Weak references, Soft reference and Phantom reference. Except strong, all other reference allows the object to be garbage collected. For example, if an object hashes only weak reference, then it’s eligible for GC if the program needs space.

 

14. The difference between checked and unchecked exception in Java?

  • Checked Exception – The exception that can be predicted by the programmer are called checkedException or we can say all exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during compilation to see whether the programmer has handled them or not. If these exceptions are not handled/declared in the program, it will give the compilation error.
    like – ClassNotFoundException, IllegalAccessException, NoSuchFieldException, EOFException etc.
  • UnChecked Exception – Unchecked exceptions are the class that extends RuntimeException. The unchecked exception is ignored at compile time. These exceptions need not be included in any method’s throws list because the compiler does not check to see if a method handles or throws these exceptions.
    Like – ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException, NegativeArraySizeException etc.

For more Details, You can refer Exceptions and it’s typed in Java.

 

15. Does Java array is an instance of Object?

Yes, Array is the instance of Object class. For more details look into Array in Java .

 

16. How to prevent your class from being subclassed?

Make your class final or make it’s constructor private. For more details, you can visit Final Class in Java

17.  Can we override Static method in Java?

No, you can not override static method in Java, though you can declare the method with the same signature in the subclass. It won’t be overridden in the exact sense, instead, that is called method hiding.

But at the same time, you can overload static methods in Java, there is nothing wrong declaring static methods with the same name, but different arguments. Some time interviewer also ask Why you can not override static methods in Java? Answer of this question lies at the time of resolution. As I said in a difference between static and dynamic binding , the static method is bonded during compile time using Type of reference variable, and not Object. If you have using IDE like Netbeans and Eclipse, and If you try to access static methods using an object, you will see warnings. As per Java coding convention, static methods should be accessed by class name rather than an object. In short Static method can be overloaded, but can not be overridden in Java. If you declare,  another static method with the same signature in derived class than the static method of super class will be hidden, and any call to that static method in the subclass will go to the static method declared in that class itself. This is known as method hiding in Java.

 

18. What is the difference between StringBuffer and StringBuilder in Java?

There are many differences in StringBuffer and StringBuilder class, Look at the details in given details, Difference in StringBuilder and StringBuffer class in Java.

 

19. What is the difference between abstract class and interface in Java ?

The difference between abstract class and interface in Java is one of the tricky Java interview question and mostly appear in core Java interviews. It has become now even trickier after Java 8 introduced default methods and allowed interfaces to have both default and static methods.

Anyway, you can find the differences between Interface and Abstract Class in Java here!

 

20. The difference between Stack and Heap memory in Java ?

Here are few differences between stack and heap memory in Java:

1) The main difference between heap and stack is that stack memory is used to store local variables and function call while heap memory is used to store objects in Java. No matter, where the object is created in code e.g. as a member variable, local variable or class variable,  they are always created inside heap space in Java.

2) Each Thread in Java has their own stack which can be specified using -Xss JVM parameter, similarly, you can also specify heap size of Java program using JVM option -Xms and -Xmx where -Xms is starting size of the heap and -Xmx is a maximum size of java heap.

3) If there is no memory left in the stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError, while if there is no more heap space for creating an object, JVM will throw java.lang.OutOfMemoryError: Java Heap Space.

4) If you are using Recursion, on which method calls itself, You can quickly fill up stack memory. Another difference between stack and heap is that size of stack memory is a lot lesser than the size of  heap memory in Java.

5) Variables stored in stacks are only visible to the owner Thread while objects created in the heap are visible to all thread. In other words, stack memory is kind of private memory of Java Threads while heap memory is shared among all threads.

That’s all on the difference between Stack and Heap memory in Java. As I said, It’s important to understand what is heap and what is stack in Java and which kind of variables goes where, how you can run out of stack and heap memory in Java etc. Let us know if you are familiar with any other difference between stack and heap memory in java.

2 Comments
  1. K Sandhya 9:32 AM / September 2, 2016 - Reply

    Nice Article …. Some questions and Explanation is very nice …. Thanks to share

  2. Nice Article 4:06 PM / September 14, 2016 - Reply

    Very Helpful …. I am working as Testing Engineer in HeadStrong ….. All mentioned questions are very Helpful for me Thanks to share ….

Leave a Reply