Top 20 Java Interview Questions For preparing yourself for the Best

In this Java Interview Questions blog, we will list some of the most important Java programming questions and answers that will set you apart in the interview process. This blog was created by a group of highly qualified and experienced interviewers. As you may be aware, Java is used by approximately 10 million developers worldwide to create applications for the 15 billion Java-enabled devices. Java has a wide range of applications, so diving into it would be one of the wisest moves you could make. It will assist you in honing your coding skills and, more importantly, will be used in almost everything from big data to devices such as mobile phones. As a result, Java is now used everywhere!






 

1. What is ThreadLocal and how does it work?

ThreadLocal is a Java class that enables the creation of thread-local variables. We know that all of an object’s threads share its variables. Synchronization can be used if a variable isn’t thread-safe. To avoid synchronisation, we can use ThreadLocal variables.
Each thread has its own ThreadLocal variable, which can be used to retrieve the default value or change the local thread value using the get () and set () methods. In classes that want to associate a thread with the state, ThreadLocal instances are usually private static fields.

 
 
 

2. What is the JDBC Prepared Statement and how does it work?

The JDBC PreparedStatement object represents a precompiled SQL statement. We can use the query’s setter method to set the query’s variables. Because PreparedStatement is precompiled, it can be used to efficiently execute this statement multiple times. PreparedStatement is a better choice than Statement because it automatically escapes special characters and prevents SQL injection attacks.




3. Describe the exception hierarchy in Java.

In Java, exceptions are hierarchical, and inheritance is used to categorize the various types of exceptions. The Java Exceptions Hierarchy’s parent class is Throwable, which has two child objects: Error and Exceptions.

Hardware failure, JVM crash, or out-of-memory error are examples of errors that occur outside the scope of programs and can not be predicted or recovered from. The two types of exceptions are checked and runtime exceptions.


Checked exceptions, such as FileNotFoundException, are rare events that we can anticipate and try to recover from in a program. We should catch this problem and send a helpful message to the user, as well as properly log it for debugging purposes. The parent class of all other classes is the only exception.


Runtime exceptions are caused by bad programming, such as attempting to extract an element from an array. We should check the length of the array before retrieving an element; otherwise, an ArrayIndexOutOfBoundException will be thrown at runtime. RuntimeException is the parent class of all runtime exceptions.




4. In C and C++, pointers are used. Why is it that Java doesn’t use pointers?

Beginner programmers should stay away from pointers because they are difficult to work with. Because Java focuses on code simplicity, the use of pointers can be challenging. The use of a pointer may also result in errors. Furthermore, because pointers allow people to directly access memory, security is compromised when they are used.
A certain amount of abstraction is provided by not including pointers in Java.
Additionally, the use of pointers may make garbage collection more time-consuming and inaccurate. Because references, unlike pointers, cannot be changed, they are used in Java.



5. In Java, what is a singleton class? What’s more, how do you make a singleton class?

Singleton classes are those in which only one object is created. The class members can only be accessed with that object.
With the help of an example, you can grasp this concept:
Consider the office water jug: if every employee wants that water, there will be no need to create a new water jug for drinking. As a reference, they will use the existing one with their own reference. As a result, it should be implemented programmatically as
class WaterJug
private int waterQuantity = 500;
private WaterJug ()
private WaterJug object = null;
//Method to provide the service of giving water.
public int getWater (int quantity)
waterQuantity-= quantity;
return quantity;
()
// method to return the object to the user.
public static Waterjug getInstance ()
// will create a new object if the object is not already created and return the object.
if (object == null)
object = new WaterJug();
return object;
Since the Constructor is private in the above class, we are unable to create the class’s object. However, we can obtain the object by invoking the getInstance method. Because getInstance is static, it can be used without having to create the object. And it gives you the object back. We can now get the water by calling getWater() on that object.


waterjug glass1 = waterjug.getInstance();
glass1.getWater (1);


This getInstance method returns a single object (). It’s also a thread-safe singleton class because it’s static. There are numerous approaches to creating a thread-safe singleton class. As a result, thread-safe classes include:
Singletons can be thread-safe if they are written with double-checked locking.
Static singletons that are initialised during class loading can be used. As we did in the previous example,
However, using Java enums is the most straightforward way to create a thread-safe singleton.




6. Overriding static and private methods is possible in Java. Consider the following statement:

The statement is completely false in this context. The static methods have no bearing on objects; they are class-level methods. A static method with a method signature identical to that of the parent class can exist in a child class without causing a compilation error.
Method hiding is the term for the phenomenon described here, and overriding is not possible. Overriding a private method is impossible because the private method’s visibility is limited to the parent class. As a result, only hiding can be aided, rather than overridden.




7. What distinguishes a hashSet from a treeSet?

Despite the fact that both HashSet and TreeSet are not synchronised and ensure that no duplicates exist, there are some characteristics that distinguish a HashSet from a TreeSet.
The hash table is used to store elements in an unordered manner in a hash set. TreeSet, on the other hand, uses a red-black tree to store the elements in sorted order.

Complexity/Performance: A HashSet’s time-amortised complexity for adding, retrieving, and deleting elements is O (1). TreeSet has a slightly higher time complexity for performing the same operations, equal to O. (log n). In general, HashSet outperforms TreeSet in terms of performance.


Method: HashSet uses the methods hashCode () and equals () to make comparisons between objects. TreeSet, on the other hand, uses the compareTo() and compare() methods to make object comparisons easier. 


Object type: HashSet can be used to store heterogeneous and null objects of various types. A runtime exception occurs when inserting heterogeneous objects or null objects into a TreeSet.




8. Why is a character array preferred over a string for storing sensitive data?

A string in Java is basically immutable, which means it cannot be changed. It remains in the string pool after its declaration as long as it is not removed in the form of garbage. In other words, after string value processing, a string remains in the heap section of memory for an unregulated and unspecified time interval.
As a result, vital information can be stolen and used for malicious purposes by hackers if a memory dump is illegally accessed. Such risks can be avoided by storing any variable in mutable objects or structures such as character arrays. After the character array variable has completed its work, it can be set to blank at the same time. As a result, it helps to save heap memory while also making it impossible for hackers to extract vital data.





9. Consider the below program; identify the output, and also state the reason for that.

public class Main
main(String [] args)
System.out.println (“Hello. Main Method.”);
main(int [] args)
System.out.println (“Hello. Main Method2. “);
(
(
The above program’s output will be “Hello, Main Method.” This is due to the fact that the JVM will always invoke the main method based on the definition it already has. It makes no difference how many main methods we overload; the JVM will only execute one main method based on its declaration.





10. Which string or string buffer should be used when there are a lot of updates to be made to the data?

A StringBuffer is both mutable and dynamic, whereas a String is not. Every string update or modification generates a new string, clogging the string pool with unnecessary objects. As a result, in cases where there are a lot of updates, it is always preferable to use StringBuffer because it reduces the overhead of creating multiple string objects in the string pool.





11. Is it possible to exceed a program’s memory limit despite the presence of a garbage collector?

Yes, despite the presence of a garbage collector, the program can run out of memory. Garbage collection aids in identifying and removing objects that are no longer needed in the programme in order to free up the resources that they consume.

If an object in a program is unreachable, garbage collection is executed with respect to that object. If the amount of memory required to create a new object is insufficient, memory is released for objects that are no longer in scope by using a garbage collector. When the memory released is insufficient to create new objects, the program’s memory limit is exceeded.

Furthermore, if objects are created in such a way that they remain in scope and consume memory, the heap memory is exhausted. After the object’s work is completed, the developer must ensure that it is dereferenced. Despite the garbage collector’s best efforts to reclaim as much memory as possible, memory limits can still be exceeded.
Let’s take a look at the following example:


List example = new LinkedList();
while (true)
example add(new String (“Memory Limit Exceeded”));



We created the CustomException exception class and called the base exception function Object() { [native code] with the error message that we wanted to print. We also used the throws keyword in the method declaration to avoid handling exceptions in the main method.





12.In Java, how does the ‘new’ operator differ from the ‘newInstance ()’ operator?

To create objects, the ‘new’ and ‘newInstance ()’ operators are used. The difference is that we use a new operator when we already know the class name for which we need to create the object. But what if we don’t know the name of the class for which we need to create the object? Alternatively, we obtain the class name from a command-line argument, a database, or a file. Then we use the ‘newInstance()’ operator in that case.
The ‘newInstance()’ keyword raises an exception, which we must handle. It is because there is a possibility that the class definition does not exist and we obtain the class name at runtime. As a result, an exception will be made.





13. What is the most effective method for instilling dependency? Also, explain why you’re doing it.

There are no restrictions on using specific dependency injections. However, the recommended approach is –
Setters are generally preferred for injecting optional dependencies, while function Object () [native code] arguments are preferred for mandatory ones. This is because function Object () [native code] injection allows for the injection of values into immutable fields, making them easier to read.




14. Define a system. out.println function ().

The message is printed to the console using System.out.println(). Arrangement—It is a class in the java.lang package. Out is a static variable of the System class of type PrintStream. The PrintStream class includes a method called println().
So, if we justify the statement, we can say that if we want to print anything on the console, we must use the PrintStream class’s println() method. And we can do so by using the output object provided by the System class.





15. When is it appropriate to use a super keyword?

The super keyword is used to gain access to the secret fields and overridden methods or properties of the parent class.
This keyword is appropriate for the following situations:

  • Accessing data members of the parent class is possible when the member names of the parent class and its child subclasses are the same.
  • to invoke the default and parameterized function Object() [native code].
  • It is possible to access the parent class methods when the child classes have overridden them.

The following example shows how to utilise a super keyword in all three scenarios.


public class Parent
protected int num = 1;
Parent(();
         System.out.println(“Parent class default constructor.”);
Parent (String x)
         System.out.println(“Parent class parameterised constructor.”);
public void foo();
System.out.println (“Parent class foo!”);
()
public class Child extends Parent
private int num = 2;
child(
         System.out.println(“Child class default Constructor”);
super();  // to call default parent constructor
super(“Call Parent”);  // to call parameterised constructor.

void printNum()
System.out.println (num);
System.out.println (super.num); //prints the value of the num of the parent class
@Override
public void foo();
System.out.println (“Parent class foo!”);
super.foo();  //Calls foo method of Parent class inside the Overriden foo method of Child class.






16. What is the main objective of garbage collection?

The major goal of this operation is to free up the memory space used by superfluous and inaccessible objects during the execution of a Java application by eliminating those objects.
This assures that the memory resource is being used effectively, but it does not guarantee that there will be enough memory available for the program to run.





17. Why is the main method static in Java?

As static members are methods that belong to classes rather than individual objects, the main method is always static. So, if the main method is not static, it is available for all objects. The JVM does not approve of this. The main function is called by the JVM depending on the class name. Not by making the object in the first place.
Since the execution of the Java program begins with the main method, there can only be one main method. As a result, the main method is static. Certainly not by creating the object in the first place.
Since Java program execution begins with the main method, there can only be one main method. As a result, the primary method is fixed.





18. What is the purpose of synchronisation?

Synchronization enables the execution of multiple processes at the same time. When a resource is shared by multiple threads, it is possible that multiple threads will require the same shared resource.
Synchronization aids in the resolution of the problem, and the resource is shared by only one thread at a time. Let’s look at an example to help you understand it better. For example, suppose you have a URL and you need to know how many requests have been made to it. Two simultaneous requests can cause the count to fluctuate.




19. Using relevant properties draws attention to the distinctions between interfaces and abstract classes.

  • In interfaces, only abstract methods are available, whereas non-abstract methods can coexist with abstract methods in abstract classes.
  • Interfaces can only have static and final variables, whereas abstract classes can also have non-static and non-final variables.
  • Inheritance: Interfaces facilitate multiple inheritances, whereas abstract classes do not encourage multiple inheritances.
  • Data member accessibility: By default, interface class data members are of the public type. On the other hand, class members can be protected as well as private.
  • Implementation: With the help of an abstract class, the implementation of an interface is easily possible. However, the opposite is not true.



20. How does an exception spread through the code?

When an exception occurs, it first looks for the matching catch block. If the matching catch block is found, that block will be executed. Otherwise, the exception is propagated through the method call stack and into the caller method, where the process of matching the catch block is carried out. This process continues until a matching catch block is found. If no match is found, the program terminates in the main method.






This is the end of our topic. We hope we helped you in some way. The topics covered in this Core Java Interview Questions blog are among the most sought-after skill sets for a Java professional, according to recruiters. These Java Interview Questions will undoubtedly assist you in acing your job interview.


Best wishes for your interview!


If you still have any queries, please let us know in the comment section.