Top 30 java interview questions and answers for freshers

Top 30 java interview questions and answers for freshers

  1. What is immutable object?
    Ans. Immutable objects can be created of immutable classes. Objects of these class cannot be modified. So whenever we try to change or modify these objects we will get a new object. E.g., the string class in Java. Most such classes are also final classes to prevent any sub class to modify their objects.

  2. Do you know what is a StringBuffer class?
    Ans. This is a class used to create mutable string. The StringBuffer class in java is quite similar to string class but with the feature of mutability.
    Constructor: StringBuffer()
    3.What is a StringBuilder class?
    Ans. StringBuilder class in java is used to create mutable string same like the StringBuffer class although String Builder class is non-synchronised i.e. two threads can call the StringBuilder class method simultaneously. It can be said that StringBuilder class is more efficient than StringBuffer class.

  3. Do you know the difference between runnable and callable interface in Java?
    Ans. Runnable is the only way to implement task in Java that can be executed in parallel. Later on Callable was defined to for multithreading, concurrency and performance optimisation.

  4. Give the difference between ArrayList and LinkedList ?
    Ans. ArrayList is based on arrays whereas LinkedList is supported by collection of nodes similar to linked list data structure. ArrayList provides faster lookups in constant time whereas LinkedList takes linear time to return a result. LinkedList uses wrapper objects for storing data and two node of next and previous type while ArrayList is stored as simple arrays.

  5. What kind of reference types exist in Java?
    Ans. There are various reference types such as Strong reference, weak reference soft reference and phantom reference. All these references can be collected by garbage collector except strong reference.

  6. What is a volatile variable in Java?
    Ans. Volatile is used to let Java Virtual Machine know that a thread accessing the variable should always merge its own copy of the variable with the original variable present in the memory. Volatile variable is synchronised to all the variable instances in the program.

  7. Do you know the difference between HashMap and HashTable ?
    Ans. HashMap is not thread safe i.e. two threads can simultaneously access the hashmap while hashtable is completely thread safe. Hashmap is not synchronised and hence has much better performance than Hashtable. Hashtable is basically obsolete now and concurrenthashmao is used now a days.

  8. Can you write a java program to find the nth Fibonacci number?
    Java Implementation –

    public class FibonacciNumber {
    public static int fibonacci(int n) {
        if (n == 0 || n == 1)
            return n;
        return fibonacci(n - 1) + fibonacci(n - 2);
    public static void main(String[] args) {
        Scanner scanner = new Scanner(;
        int n = scanner.nextInt();
  9. What is Singleton?
    Ans. Singleton class in Java has only one instance in the whole program. We can easily implement a singleton class with thread safe property. We can see the implementation below –

    public class Javasingleton
    private static  volatile Javasingleton  singleinstance;
    private Javasingleton(){}
    public static   Javasingleton  getInstance()
        if (singleinstance ==null )
                if (singleinstance ==null )
                    singleinstance=new Javasingleton();
        return singleinstance ;
  10. What is abstraction?
    Ans. The process of hiding information that are not necessarily changed rather only those methods or functions are extended such that they can be used to modify or perform a function. Abstraction helps to hide the complex data structures and variables from the users who might be only requiring a sub class of data and functionalities.
    Moreover, there are abstract classes too which can be implemented in java and their instances cannot be created.

  11. Do you know what is Polymorphism?
    Ans. It is the ability to have same interface for differing underlying data types. A polymorphic type is a type which can handle multiple types of data or in different form. There are two kind of polymorphism –
    Compile Time Polymorphism: Static binding
    Run time polymorphism: Dynamic binding

  12. Why is Java called platform independent language?
    Ans. In Java the code is compiled and converted to a class of file called Byte Code in the Java virtual environment. This Byte Code can be interpreted by any processor for execution. Hence Java codes are platform independent and can be used in any platform.

  13. Can you override private or static method?
    Ans. Well, we cannot override private or static method. If we try to override by defining new such method then it will go under method hiding.

  14. Write a code to print all the first n prime numbers where n will be given as input.

    public static void main(String[] args) {
        int N = 200;
        int k;
        Scanner sc = new Scanner(;
        k = sc.nextInt();
        int i = 0;
        for (int num = 2; num <= N; num++) {
            if (isPrimeNumber(num) && i!=k) {
    public static boolean isPrimeNumber(int num) {
        for (int i = 2; i < num; i++) {
            if (num % i == 0) {
                return false; 
        return true; 
  15. What is the difference between sleep() and wait() method?
    Ans. Wait method releases the lock whereas sleep method does not release the lock on the variables in thread. Wait method belongs to java.lang.Object class whereas sleep belongs to java.lang.Thread.

  16. How to find the middle element in a linked list in one pass?
    Ans. Well, this is an algorithm-based question. Normally we know we can traverse the whole linked list and count the size of the list and then again move to middle of the list from this size and return that element. But here we are asked to find the same using only one pass. So, we will use two pointers, a fast pointer and a slow pointer. For every iteration the slow pointer moves only one step ahead whereas the fast pointer moves twice. When the Fast pointer reaches the end of the list this means our slow pointer has reached the middle of the linked list. In this way we can find the middle element of the linked list in single pass.

  17. What is the difference between an Interface and an Abstract class?
    Ans. Both define an interface that has to be implemented. Abstract class can contain concrete methods as well as abstract. Abstract class can contain regular class fields. Interface can contain only public static final fields.

  18. Do you know about the Final keyword in Java?
    Ans. Yes, final is a keyword used to stop the class from being extended further and used for the following purposes –

    • When used with a method protects it from being overridden in subclasses. Done for security and/or performance reasons.
    • When used with a field means that the value stored in the field cannon be changed after initialization. Not to be confused with immutability of the object.
    • When used with a class declaration protects it from being subclassed. Done for security and/or performance reasons. Also, for immutability. Many of Java core classes are final (e.g., String)
  19. Does garbage collector prevent the program from running out of memory?
    Ans. No, running out of memory can be also due to recursive calls, in that case the garbage collector cannot remove all the variables until that call is finished. Hence it keeps on increasing and finally gets out of memory.

  20. What is the difference between throughput and latency?
    Ans. Throughput is the percentage of time application running versus Garbage Collector whereas Latency is the amount of pause time for application which is waiting for the Garbage Collection to complete.

  21. What do you mean by Object Life time?
    Ans. It is basically the time for which the Object lies in the memory and its instance is nor destroyed by the garbage collector. Lifetime of object is recorded in JVM as number of Garbage collection cycles survived.

  22. Explain HashMap in brief.
    Ans. HashMap is basically a key value pair type of data structure which has the following characteristics –
    Permits a null key, and null values.
    Iteration order not guaranteed.
    Throws ConcurrentModificationException.

  23. Why the main() method in Java static?
    Ans. The main() method in Java is static because they can then be invoked by the runtime engine without having to instantiate an instance of the parent class.The method is static because otherwise there would be ambiguity between which constructor should be called and should the JVM call new JavaClass(int) or a different one. There are just too many edge cases and ambiguities for it to make sense for the JVM to have to instantiate a class before the entry point is called. That’s why main is static.

  24. Why multiple inheritance is not supported in java?
    Ans. To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class.

  25. What is interface?
    Ans. Interface is a blueprint of a class that have static constants and abstract methods. It can be used to achieve fully abstraction and multiple inheritance. Interface method cannot be declared static since interface is abstract by default and abstract and static cannot be used together. An interface that has no data member and method is known as a marker interface. For example, Serializable, Cloneable etc.

  26. Why string objects are immutable in java?
    Ans. Meaning of immutable is unmodifiable or unchangeable. Java uses the concept of string literal. Suppose there are 5 reference variables, all refers to one object "caching". If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

  27. What is serialization?
    Ans. Serialization is a process of writing the state of an object into a byte stream. It is mainly used to travel object’s state on the network. Serializable is a marker interface (has no data member and method). It is used to "mark" java classes so that objects of these classes may get certain capability. The Cloneable and Remote are also marker interfaces.

  28. What does the hashCode() method do?
    Ans. The hashCode() method returns a hash code value (an integer number). The hashCode() method returns the same integer number, if two keys (by calling equals() method) are same. But, it is possible that two hash code numbers can have different or same keys.

  29. What is JDBC and why it is used?
    Ans. JDBC is a Java API that is used to connect and execute query to the database. JDBC API uses jdbc drivers to connect to the database. It is defined in java.sql package.
    Before JDBC, ODBC API was the database API to connect and execute query with the database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language).
    Hope this article provides wyou with good questions which might be common for your Java interview.

Previous post 50 simple java programs for beginners
Next post Cisco interview questions for freshers

Leave a Reply

Your email address will not be published. Required fields are marked *