Core Java Interview Questions

Core java being the basis of any Java/J2EE interview, every IT engineer needs to go through core java interview questions. Whether you are a fresher or experienced professional, you are going to face core java questions. Here is the list of some important core java questions which are frequently asked in the interviews.

 

Q1. What is the difference between JRE, JVM and JDK?

Ans.

JRE – JRE stands for Java Runtime Environment. It provides a runtime environment for Java code. It has JVM, libraries like rt.jar and other files.

JVM – JVM stands for Java Virtual Machine. It is a virtual machine which runs the java byte code.

JDK – JDK stands for Java Development Toolkit. It contains JRE, compilation and debugging tools (javac and java).

 

Q2. How java becomes platform independent?

Ans. Java is independent means we can write and compile the code in one OS and run in another OS.

 

Q3. What are the four pillars of OOP?

Ans. Four pillars of OOPS are:

  1.  Encapsulation
  2. Polymorphism
  3. Abstraction
  4. Inheritance

 

Q4. Explain each OOP pillars?

Ans. The explanation is as below:

      1.      Abstraction

Data abstraction is the process of showing only the necessary details and hiding certain details. There are two ways in which we can achieve abstraction.

    a. Abstract Classes- They are the restricted classes that cannot be used to create the object. These classes have abstract as well as non-abstract methods. Abstract methods are those methods which are not defined and which are only declared.

    b. Interfaces- Interface is pure abstraction. These classes only contain a declaration of the method and do not contain a definition of the methods.

The abstract keyword is a non-access modifier which can be used for classes and methods.

Click here for details on “Abstraction in java”.

      2.      Encapsulation

It is the mechanism of binding data member and member function together. To achieve this, we must :

    a. Declare the class variable/attributes as private.

    b. Define get and set methods to access and modify these private attributes.

Click here for details on “Encapsulation in java”.

3.      Polymorphism

Polymorphism means “many forms”. In other words, it is the ability of a method to be displayed in more than one form. Mainly polymorphism is of two types:


    a. Compile Time Polymorphism
            Compile time polymorphism is Static polymorphism, which is achieved by overloading.

    b. Runtime Polymorphism
                Runtime Polymorphism is Dynamic Polymorphism, which is achieved by function overriding.

Click here to know more about “Compile Time Polymorphism and "Runtime Polymorphism in java”.

      4.      Inheritance

    Inheritance is the concept of inheriting the property of the parent class into the child class. During inheritance we come across two words: 

    a. Super Class –The class which will be inherited.

    b. Sub Class- The class which will inherit the superclass.

Click here for details on “Inheritance in java”.

 

Q5. What is a constructor in java? Can we declare constructor as final?

Ans. A constructor is the special member function of the class which has the same name as that of the class name. There are two main points about constructor:

        a.       Class and Constructor name should be the same.

        b.      There should not be any return type of the constructor.

No, we cannot declare the constructor as final. Doing so will give you a compile time Exception.

 

Q6. What is Immutability in java?

Ans. Immutability is the mechanism by which the state of the object/class can be changed once it is created. The string is the best example of immutability in java.

Click here to know more about “Immutability” and also to know how we can create our Immutable class.

 

Q7. What is the difference between Abstract class and Inheritance?

Ans. Differences are as follows:

  1. Abstract A class can have a default method definition whereas Interface is pure abstraction it cannot have a method definition.
  2. To use Abstract Class subclass uses extends keyword, whereas to use Interface, a subclass uses implements keyword.
  3. All the abstract methods have to be defined in the subclass when we use abstract whereas all the methods in the interface have to be defined in the subclass.
  4. An abstract class can have constructor whereas an interface cannot have a constructor.
  5. An Abstract class can have the main method whereas an interface cannot have the main method.
  6. An abstract class can extend only one class and can implement any number of interfaces whereas Interface can extend interface only.
  7. If we add methods to abstract class we can provide a default implementation in abstract class so we don’t have to change the current code whereas if we add methods in the interface we have to give the implementation of all the methods in the classes which implement the interface.

 

Q8. What is marker interface in java? Give some example of marker interface?

Ans. A marker interface is an interface which has no method in them. They are just used to indicate JVM to behave in a particular manner. Some example of Marker interface is Serializable which is used when doing serialisation, Clonable which is used when doing cloning of the objects.

 

Q9. What are method overloading and method overriding in java?

Ans. Method Overloading

Method overloading is a concept that allows a class to have the same method name but have different arguments. Compile time Polymorphism is the second name of Method Overloading.

Method Overriding

If the same method of child class is present in Parent class with same method signature it is known as Method Overriding. Runtime Polymorphism is the second name of Method Overriding.

 

Q10. Can we override static methods?

Ans. No, we cannot override static methods as they belong at the class level and not at the object level. We can have a method with the same name but that will not be Runtime Polymorphism that will be called as method hiding.

 

Before we move further do check out the book link given below to buy this best book in the market. The book covers every aspect of core java with latest version upgrade java 8.

                                                 

Q11. Can we override private methods?

Ans. Private Methods are not visible to subclass hence we cannot override the private methods.

 

Q12. What is the difference between StringBuffer and StringBuilder?

Ans. Differences are as follows:

  1. StringBuffer is thread-safe, we can use it in a multi-threading environment whereas StringBuilder is not thread-safe hence we can use it in a multi-threading environment.
  2. StringBuffer is less performance efficient as it is thread-safe whereas StringBuilder is more efficient as it did not thread-safe.

 

Q13. Explain the internal working of hashmap in java.

Ans. This is a very important topic of core java interview. Keeping this in mind, I have a separate blog written for this topic. Please click here to read the blog.

 

Q14. Please explain the internal working of HashSet in java?

Ans. HashSet uses Hashmap internally to store values in it. It uses PRESENT as dummy object.

Example:

Hashset set = new hashset();

set.add(“java7”);

set.add(“java8”);

Here, we are adding two objects java7 and java8, in HashSet it will be stored in hashmap like this:

                                   

Key

Value

java7

PRESENT

java8

PRESENT

 

Q15. How HashSet removes duplicate values?

Ans. HashSet add() method internally uses HashMap put method. HashSet adds a method to have a return type of Boolean. So, the internally HashSet put method has an implementation like this:

            //add method

            // it calls put() method of a map and compare it return value with null

            Public Boolean add(E e){

                        return map.put(e, PRESENT) == null;

            }

With this example we understand two things:

1.      If map.put(key, value) is null, the statement "map.put(e, PRESENT) == null" will return true and the element is added to HashSet (internally HashMap).

2.      If map.put (key, value) returns the old value of the key, the statement "map.put (e, PRESENT) == null" will be false and the element has not been added to HashSet (HashMap internally).

 

Q16. What is the difference between HashMap and HashSet?

Ans. The difference between HashMap and HashSet areas follows:

 

HashMap

HashSet

         HashMap implements Map interface.

         HashSet implements Set interface

         It uses <key,value> in order to store the values.

      It uses the add(value) method to store the data

         HashMap allows duplicate values but not duplicate keys

         HashSet does not allow duplicate values

 

Q17. What is the internal working of ConcurrentHashMap in java?

Ans. This is also one of the most important topics of core java interviews. I have a separate post for this topic also. Please click here to read in detail.

 

Q18. What is the difference between ConcurrentHashMap and Collections.synchronizedMap(map)?

Ans. The main difference between these two is that ConcurrentHashMap works on the partial locking mechanism, the segment getting updated will be locked and unlocked segments can be accessed by other threads. Contrary to this Collections.synchronizedMap() will lock the whole object and will be available to access once the lock is released. Choose ConcurrentHashMap in frequent updates and less read.

In ConcurrentHashMap the insertion order is not maintained. This is similar to HashMap when storing data. Element order preservation is not guaranteed. While Collections.synchronizedMap() will preserve the order of the elements of the passed map.

ConcurrentHashMap can guarantee that there are no ConcurrentModificationException while one thread is updating the map and the other is tracing the iteration received from the thread map. However, Collections.synchronizedMap() does not guarantee this.

 

Q19.  Is there any lock while getting values from ConcurrentHashMap?

Ans. No, while getting the values there is no lock in ConcurrentHashMap. Segments come into picture while performing the write operation. While reading, ConcurrentHashMap provides full concurrency and provides the most recent value using volatile variables.

 

Q20. In how many ways we can sort the collections in java?

Ans. There are two ways to sort collections in java.

      1. Using Comparable Interface – 

              Comparable interface has compareTo() method inside it. We can use Comparable interface when we want to sort the collection on natural sorting order.

       2. Using Comparator Interface  

              Comparator interface has compare() method in it. We can use the Comparator interface when we want to sort the collection on different criteria for example name, salary etc.

For more details on Comparable and Comparable interface click here

Before we move further do check out the book link given below to buy this best book in the market. The book covers every aspect of core java with latest version upgrade java 8.

                                                 

Q21. What are the differences between ArrayList and LinkedList?

Ans. The differences between ArrayList and LinkedList is as follows:

 

ArrayList

LinkedList

1.      It uses a dynamic array to store data internally.

It uses a doubly linked list to store the data in it.

2.      While inserting or deleting data into ArrayList it takes O(n) as ArrayList uses an array internally. While inserting or deleting we have to rearrange the index of the elements.

If we are inserting or deleting elements into LinkedList it takes O(1) as it uses DoublyLinked List internally.

3.      As ArrayList is index-based data structure searching is fast. Complexity is O(1).

For searching in LinkedList we have t traverse the list from starting. Complexity is O(n).

4.      ArrayList implements List interface

LinkedList implements List, Dequeue interfaces hence, it can be used as Link, stack, queue.


Q22. What is enum in java?

Ans. Enum is a special data type in java which represents a list of constant values. It is a special java class which can contain constants, methods and constructor.

 

Q23.  How to create custom exception in java?

Ans. We need to extend the class with the Exception class to create a custom exception. To create unchecked exception then we should extend the class with RuntimeException.

To know more click here.

 

Q24. What is the Difference between Checked and Unchecked Exception?

Ans. A checked exception is exceptions that come at compile time. If we do not handle these exceptions, we will get a compilation error. Example: IOException.

Unchecked Exceptions are exceptions which are not checked at compile time. Java will not complain if we don’t handle these exceptions, but at runtime, it will create the problem and will cause the unexpected termination of the program. Example: NullPointerException, ArrayIndexOutOfBoundException.

 

Q25. Can we write try without a catch?

Ans. Yes, we can have a try block without the catch. But to work, we need to write the finally block. As we know that the finally block will execute even if we get an exception or even after the return statement.

 

Q26. How we can avoid finally block to execute?

Ans. We can use System.exit().

 

Q27. What are the ways to create a thread in java?

Ans. There are two ways in which we can create a thread in java:

1.      By extending Thread class.

2.      By implementing the Runnable interface.


Q28. What is the difference between Sleep and wait methods of thread?

Ans. The difference is as follows:

        1.      Wait should be called from synchronized context if we don’t do so it will throw                         IllegalMonitorStateException whereas Sleep need not be called from synchronized context.

        2.      Wait the method operates on the object and is defined in Object class whereas Sleep method operates on the current thread and is in Thread class.

        3.      Wait releases the lock of an object on which it is called and any other lock if it holds any whereas Sleep does not release any lock.

        4.      Wait will not happen until call notify() or notifyAll() whereas in sleep it will happen when the time expires or call interrupt().

        5.      Wait is a static method whereas Sleep is a non-static method.


Q29. What are the different states of threads in java?

Ans. There are 5 thread states in java

New: Thread is newly created and is not alive.

Executable - When you call the thread's startup method, it enters the Executable state. Whether it will run immediately or after a few moments depends on the thread scheduler.

Running - When the thread runs, it goes into the running state.

Blocked - When the thread waits for some resources or some other thread to complete (due to the thread joining), it goes into the blocked state.

Dead: When the thread execution method returns, the thread goes into the dead state.

 

Q30. What will happen if we call the run method directly to start a thread?

Ans. If we call the run method directly, it will not create the thread but the method will act as other normal methods and will be in the same stack as main. We need to call the start method to create the new thread.

 

Q31. What will happen if we start a thread twice?

Ans. Once the thread is started it can not be started again. If we try to start the thread again it will throw IllegalThreadStateException.

 

Q32. What is CountDownLatch?

Ans. The CountDownLatch class is a synchronization aid that allows one or more threads to wait until mandatory operations are performed by other threads.

The CountDownLatch is started with a given count of threads that must be completed before the main thread.

The CountDownLatch.await() method stops the main thread execution until the current count reaches zero. Threads are executed using the countDown() method when their work is completed. Any call to await returns immediately after the count is 0.

 

Q33. What is the difference between CountDownLatch and CyclicBarrier?

Ans. The differences are:

1.   Once the count reaches 0 CountDownLatch cannot be reused whereas CyclicBarrier can be reinitialised once the parties reach to 0, so it can be reused.

2.  CountDownLatch calls countDown() to reduce the count whereas CyclicBarrier calls await() to reduce the count.

3.  CountDownLatch cannot trigger common events when the count reaches to 0 whereas CyclicBarrier can trigger common events when the count reaches to barrier point.

 

Q34. Why wait, notify and notifyAll are present in object class?

Ans. As we put a lock on the shared object and not on thread, so these methods are present in the object class.

 

Q35. Can we call notify, notifyAll and wait for methods from non-synchronised context?

Ans. No, we cannot call these methods from non-synchronised context doing so will give IllegalThreadStateException.

 

Q36. What is the difference between String str = new String(“Core Java”) and String str = “Core Java”?

Ans. Creating a string object with a new keyword. It is not interned. It will create a new object in heap memory even if the string object is already present with the same content.

            String str1 = new String(“Core Java”);

            String str2 = new String(“Core Java”);

            System.out.println(str1==str2);

It will return false as str1 and str2 will point to different objects.

If we create a string using the assignment operator. It will go to string literal pool and will be interned. If we create another string object with the same content, both will refer to the same object in string constant pool.

            String str1 = “Core Java”;

            String str2 = “Core Java”;

            System.out.println(str1==str2);

It will return true as str1 and str2 will point to different objects.

Click here to know more about String class, String pool and String literals


Q37. What is the difference between == and .equals method?

Ans. The differences are:

1. The main difference between the .equals () method and the == operator is that one is the method and the other is the operator. 

2. We can use the == operators for reference comparison (address comparison) and .equals () method for content comparisons. == checks that both objects point to the same memory location while .equals() Evaluates the comparison of values ​​across objects. 

3. If a class does not override the equals method, by default it uses the equals(object O) method of the closest parent class that overrides this method.

To know more in detail please go through this blog.

 

Q38. What is garbage collection?

Ans. Garbage collection is the mechanism in which JVM will look into heap memory and will delete the unused objects present in the heap memory. Garbage collection frees unused memory. Garbage collection is done by JVM.

 

Q39. What is system.gc()?

Ans. This method is used to invoke garbage collections for cleanup unreachable code, but it is not sure that once this method is called the garbage collections will happen.

 

Q40. What is the difference between final, finally and finalize in java?

Ans. The difference is as follows:

Final: Final is a keyword which is used with the class to avoid being extended, with instance variable so they cannot be reassigned, with methods so that they cannot be overridden.

Finally: Finally is a keyword that is used with a try, catch and finally block. Finally, the block will execute even in case of an exception. It is commonly used to do some cleaning work.

Finalize: Finalize is a method that is used for an object accessible to clean garbage collection, but it is not guaranteed that when you implement System.gc(), the garbage collection will trigger.


Related Articles:

        1.      Java 8 interview questions.

        2.      Abstraction in Java

        3.    Encapsulation in Java.

        4.       Internal working of Hashmap in java.

        5.    Compile time polymorphism in java

        6.    Runtime Polymorphism in java.

Post a Comment

0 Comments