Java interview questions for 3 years experience in 2024

In this post, we will share the JAVA interview questions for 3 years of experience in 2024, this content is well researched and collected the questions and answers who have cleared the Java interview

1. Explain the difference between try, catch, and finally blocks.

These three blocks are used for exception handling in Java. They are used for managing and responding to exceptions that may occur during the execution of a program. Let’s understand each block with an example.

Try:

Try block is used to enclose a section of a code where an exception may occur. If an exception occurs within this block, it is caught and handled by the corresponding catch/finally block. Try block must be followed by either a catch block or a finally block, or both.

Catch:

catch block follows the try block and is used to catch and handle specific types of exceptions that may occur within the associated try block. We can have multiple catch blocks to handle different types of exceptions from child to Parent. These catch blocks are evaluated in order, and the first one that matches the type of the thrown exception is executed.

Finally:

finally block is used to define a block of code that will be executed regardless of whether an exception occurred or not. It is typically used for cleanup operations, such as closing resources like file handles, database connections that need to be released, regardless of the occurrence of an exception. The finally block is optional and can be used with or without catch blocks


2. Difference between ArrayList and LinkedList?


Aspect
ArrayListLinkedList
Underlying Data Structure
Dynamic array
Doubly-linked list

Access to Elements
Direct and fast using index
Slower, requires traversal

Insertions/Deletions
Slower in the middle
Faster, especially in the middle

Performance
Better for random access
Better for insertions/deletions
Memory Usage
Generally less per element
Generally more per element

3. What is the difference between abstraction and encapsulation in Java?

Abstraction and encapsulation are two core concepts in object-oriented programming, and they are very much used in designing and implementing software. Let’s understand with an example:

Abstraction refers to hiding the implementation details of a code and exposing only the necessary information to the user. It provides the ability to simplify complex systems by hiding irrelevant details and reducing complexity.

In Java, Abstraction is achieved through abstract classes and interfaces. If you business required partial abstraction then developer should go with Abstract class. Abstract classes can have abstract methods (methods without a body) or non abstract method. Abstract Methods must be implemented by concrete subclasses.

Encapsulation refers to the bundling of fields and methods inside a single class. It prevents outer classes from accessing and changing fields and methods of a class. This also helps to achieve data hiding.

Here, we are making the balance variable private and applying logic inside the setBalance() method. Now, balance cannot be negative.

4. What are the differences between the equals() method and the == operator in Java?

In Java, the equals() method and the == operator are used for comparing objects, but they serve different purposes and operate differently. Lets understand the difference between them:

equals() method compares the content of a variable and == operator compares the reference/address of a variable. It checks if two object references point to the same memory location, determining if they are the same object. 

If a class does not override the equals method, then it defaults to the equals(Object o) method of the parent class I.e. Object Class. As per the Object class, this is the same as == operator i.e. it returns true if and only if both variables refers to the same object.

5. What is the use of the transient keyword in Java?

The transient keyword in Java is used to indicate that a field should not be part of the Serialization process. To understand this better, lets understand what is Serialization.

  • Serialization:
    • Java provides a mechanism called serialization, which allows objects to be converted into a byte stream for transmission and then reconstructed back into objects.
    • When an object is serialized, all of its non-transient instance variables are written to the byte stream by default.
  • Exclude variable from Serialization:
    • When an instance variable is marked with the transient keyword, it indicates to the JVM that the variable should be excluded from the serialization process.
    • This is useful when there are certain fields in an object that should not be persisted or transmitted, perhaps because they are temporary, derived, or contain sensitive information like password.
6. What is the difference between StringBuilder and StringBuffer?

StringBuilder and StringBuffer Class both represent mutable sequences of characters. They are used when you need to perform a lot of String manipulations, such as concatenation or modification. Let’s understand the key difference between both of them.

  • StringBuffer and StringBuilder are mutable objects in Java. They provide append(), insert(), delete(), and substring() methods for String manipulation.
  • StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That’s why StringBuilder is faster than StringBuffer.
  • For String manipulations in a non-multi threaded environment, we should use StringBuilder else use StringBuffer class.

7. How to make class immutable?

There are 5 principles we have to follow to make any class immutable

  • Make the class final or sealed: This prevents subclasses from being created, ensuring the class definition and as we know final class can’t be inherit
  • Make field private and final: This restricts direct access and modification of internal data.
  • No setter methods: Instead, provide getter methods to access data, but return copies of mutable objects if applicable.
  • Perform deep copies in constructors and methods: When dealing with mutable objects within the class, create copies to avoid modifying the original data.
  • Consider immutability libraries: Some languages offer libraries or built-in mechanisms to simplify creating immutable classes.

8. What is the significance of the static keyword in Java?

We can use the static keyword in different parts of a Java program like variables, methods, and static blocks.

The main purpose of using the static keyword in Java is to save memory. When we create a variable in a class that will be accessed by other classes, first we have to create an instance of the class and then assign a new value to each variable instance. Even if the value of the new variables are supposed to be the same across all new classes/objects.

However, when we create a static variables, its value remains constant across all other classes, and we do not have to create an instance to use the variable. This way, we are creating the variable once, so memory is only allocated once.

Let’s understand with an example.

create a class named Customer having three variables – name, bank, and balance.

then create two instances of the Customer class:

If we see the bank have the same value across all objects i.e. “SBI”. If we have to 1000 customer object then for each bank variable, compiler will allocate new memory even after having the same value.

In this case, if we make bank variable with static keyword then memory will be allocated only once irrespective of any number of object we create.

Static Method:

  • Similar to static variables, static methods belong to the class rather than to objects. They can be called using the class name without creating an object of the class.
  • Static methods often perform operations that are not dependent on the state of any particular instance.

Static Block:

  • Static blocks are used to initialize static variables. They are executed only once when the class is loaded into the JVM.
  • This is useful for performing one-time initialization tasks for the class.

9. What is the significance of finally block?

  • As we know finally block is always executed even if we have a return statement in the code
  • Even if any exception occurs finally block is always executed
  • For critical tasks such as closing the DB connection, Network Connection, and rollback the transaction code, we can write code inside finally block

10.Can we override private method?

No, we can’t override private method because those methods are not accessible outside the class and hence private method of Base class will not be visible to Derived class.
If we try to override private method then we will get compile time error I.e. method_name() has private access in Base Class.
Lets understand with an example:

In this example, we are creating a reference object of Base class which is holding the object of Derived class. Here, the compiler should call method whose object gets created. However, if you execute above code then you will get compile time error.

We can understand by seeing an error that compiler tries to call run method of Base class because overrides didn’t happen.

11. Can we override protected method?

Yes, we can override protected method in Java only if those classes are on the same package. As you know, protected method will only be visible in the same package. 

If the base class method is protected, the Derived class can override it. Moreover, Derived class can change the access specifier.

If Base class method is protected then you can make it public or protected in derived class,. However, you can’t have weaker access specifier like private or default.

12. Can we override static method in Java?

No, we can’t override static method. It is because method overriding is determined at run-time but static methods are determined at compile time with static binding. Hence, if we try to override static method then Derived Class method will get hidden and Base class method will get called based on the object reference. This is also known as method hiding.
For example:

Will become

Since run() is a static method it didn’t get override due to which Base class run() is called.

13. What is compile time and run time polymorphism?

Compile time polymorphism: Compile time polymorphism is also known as early binding, static binding and it is obtained through method overloading. Method overloading allows us to have more than one method of same name with different behaviour by changing the number parameters or data type of parameters. Since this process gets executed or determined by compiler at compile time, that’s why it is known as compile time polymorphism.

Run time polymorphism: Run time polymorphism is also known as late binding, dynamic binding and it is obtained through method overriding. Method overriding allows us to have more than one method with same name and same signature with different behaviour. Since, this process gets executed or we should say method to be executed is determined at run time based on the type of object referenced.

14. Can we override final method?

We can’t override final method. If we try to override the final method in java, we will get an error.

Developers will keep methods as final when they know that the implementation/behaviour is fully completed.

15. What is method hiding?

Method hiding is a functionality in Java in which Derived class override the static method of Base class. In this case, method present in the Base class hides the one present in the Derived class.

16. What is the difference between HashMap and HashTable?

HashMap and HashTable are both implementations of the Map interface in Java. Lets understand the difference between them.


Aspect
HashMapHashTable
Synchronizationit is not synchronized and not thread-safe. It means if multiple threads access a HashMap concurrently, it must be synchronized externallyit is synchronized and thread-safe, ensuring that only one thread can access the Hashtable at a time. This makes it suitable to use in multithreaded environments
Null Keys and Valuesallows one null key and any number of null valuesneither keys nor values can be null. If you try to insert a null key or value then NullPointerException will be thrown
Which one to use and whenrecommended for new code due to its better performance and the fact that it allows null values.use of HashTable is limited due to its synchronization nature. In modern era HashMap or ConcurrentHashMap are often preferred
Performance
give higher performance as it is not synchronizedit gives slower performance as it is synchronized
Iterating Over ElementsHashMap Iterator is fail-fastHashTable iterator is fail safe

17. What is the use of volatile keywords in Java?

Volatile keyword is used to indicate that a variable value may be modified by multiple threads concurrently. It ensures that all threads see the most up-to-date value of the volatile variable, preventing any caching or optimization issues that may arise due to thread-specific local copies.

The volatile keyword is not related to serialization. It is about ensuring proper visibility of variable changes in a multithreaded environment.

18. What is the difference between the throw and throws keyword?

throw:

  • The throw keyword is used to explicitly throw an exception within a method or a block of code.
  • It is used when you want to explicitly throw an exceptional condition during the execution of program manually.

throws:

  • throws keyword is used in the method signature to declare that a method may throw one or more types of exceptions
  • It is used when you want to indicate to the caller that the method may propagate certain types of exceptions, and the caller should handle them or declare them as well.

19. Explain the concept of garbage collection in Java. How does it work?

Garbage collection in Java is the automated process of deleting code that is no more longer needed or used. This automatically frees up memory space and it end up increase the performance of our applications. 

20. What is equals() method in Java?

The equals() method  in Java is used to compare two variables and returns true if they are logically same. The default implementation of equals() method compares the reference or memory location of both the object. However, we can customise the default implementation by overriding this method in our custom Java classes.

The default implementation of equals() method defined in Object class is:

21. What is hashCode() method in Java?

The hashCode() method  in Java is used to distinguish buckets in Hash implementations like HashMap, HashSet and it returns an integer value which represents the value of object. The default implementation of hashCode() method returns the reference or memory location of object. However, similar to equals() method, we can also customise its default implementation by overriding this method in our custom Java classes.

22. Explain the principle of method overloading and method overriding in Java?

Method overloading allows us to have more than one method of same name with different behaviour by changing the number parameters or data type of parameters. Since this process gets executed or determined by compiler at compile time, that’s why it is also known as compile time polymorphism.

Method overriding allows us to have more than one method with same name and same signature with different behaviour. Since, this process gets executed at run time and hence it is also known as run time polymorphism.

23. What is the purpose of the super keyword in Java?

The ‘super’ keyword is used to referencing the parent class or superclass of a subclass in Java. It is also used to access members (variables or methods) of the superclass that have been overridden in the subclass. You can call the superclass method from the subclass using super.method(). Moreover, super() is used to call the constructor of the superclass from the subclass constructor, which is very useful for initializing inherited members.

24. Describe the access modifiers (public, private, protected, default) and their usage.

Public: Members marked as public are accessible from any other class. This means that there are no restrictions on accessing these members from outside the class, regardless of the package.

Private: Members marked as private are accessible only within the same class. They cannot be accessed from outside the class, not even from subclasses in the same package.

Default (Package-private): If no access modifier is specified, it’s considered as package-private. Members with default access are accessible only within the same package.

Protected: Members marked as protected accessible within the same package or by subclasses outside the package. They cannot be accessed by non-subclasses outside the

25. Differentiate between inheritance and polymorphism.

Inheritance: Inheritance is a mechanism where a new class (subclass) is derived from an existing class (superclass). The subclass inherits the properties and behaviors (methods and fields) of the superclass. It allows code reuse and facilitates the creation of a hierarchy of classes.

Polymorphism: Polymorphism is the ability of objects to take on different forms or behave differently based on the context. In Java, polymorphism is achieved through method overriding (runtime polymorphism) and method overloading (compile-time polymorphism).

26. What is a singleton class in Java and How can we make a class singleton?

Singleton class is a class whose only one instance can be created at any given time, in one JVM. A class can be made singleton using the below steps:

  1. Private Constructor: Ensure that the class has a private constructor to prevent instantiation of the class from outside.
  2. Static Instance: Provide a static member variable of the same class type, usually named instance, which holds the single instance of the class.
  3. Static Method to Get Instance: Provide a static method that returns the instance of the class. This method should be responsible for creating the instance if it doesn’t exist or returning the existing instance.

27. Discuss about the various collection frameworks (List, Set, Map) and their use cases.

let’s discuss the three main collection frameworks in Java: List, Set, and Map, along with their common use cases:

1. List: A List is an ordered collection of elements where each element is identified by its index. It allows duplicate elements and maintains the insertion order.

Implementations: ArrayList, LinkedList, Vector.

2. Set: A Set is a collection of unique elements where duplicate elements are not allowed. It does not maintain any specific order of elements.

Implementations: HashSet, TreeSet, LinkedHashSet.

3. Map: A Map is a collection of key-value pairs where each key is unique, and it maps to a single value. Keys are used to retrieve values, and duplicate keys are not allowed.

Implementations: HashMap, TreeMap, LinkedHashMap.

28. Describe the purpose of thread synchronization and provide common methods like synchronized, volatile, and AtomicInteger.

  • Synchronization is essential for avoiding race conditions and data corruption.
  • Explain when to use each method and their trade-offs (e.g., synchronized being heavier but more flexible, volatile providing visibility guarantees but not atomicity).

29. What is the ‘this’ keyword in Java?

this‘ keyword refers to the current instance of the class. It is primarily used to differentiate between instance variables and local variables with the same name.

30. Explain the ‘static’ keyword in Java.

The ‘static‘ keyword is used to declare variables, methods, and nested classes that belong to the class rather than instances of the class. For example, static int count = 0;

I hope you liked our content ‘Java interview questions for 3 years experience in 2024, please comment if you have any suggestions and if you are someone who has encountered more questions in interview

Leave a comment