This post brings the 50 most essential Java interview questions that every programmer or tester working in Java must know. Let’s begin with the first 20 questions on basic Java concepts.
Out of the 50 Java interview questions and answers, first, begin with the 20 most basic Java questions. It is important that you have their answers to your tips. It will make you feel more confident while facing the interviewer.
20 Must-know Java Basics Interview Questions
In this section, we’ve covered some of the key fundamental Java interview questions. It’s almost certain that the Interviewer will ask you 3-4 questions from this section to check your understanding of Java as a programming language.
Q-1: What is JRE, and why is it required?
Ans. JRE stands for “Java Runtime Environment” which you usually download as Java software. The JRE comprises the Java Virtual Machine, Java platform classes, and supporting libraries. The JRE is the runtime component of Java software and is all you need to run any Java application.
Q-2: What is JDK, and why is it required?
Ans. The JDK is a superset of the JRE and includes everything that the JRE contains. Additionally, it comes with the compilers and debugger tools required for developing Java applications.
Q-3: What is JVM, and why is it required?
Ans. JVM stands for Java Virtual Machine. It translates and executes the Java bytecode. It’s the entity that transforms Java to become a “portable language” (i.e., write once, run anywhere). However, each platform has its implementation of JVM. Windows, Linux, macOS, etc. have their target version of JVM to run bytecode.
Q-4: Distinguish between Java Path and Classpath.
Ans. The <Path> and <Classpath> are OS-level environment variables. Path defines the location where the system can look up the executables (.exe) files, and classpath specifies the location of the Java class files.
Q-5: Distinguish between a constructor and a method.
Ans. A constructor gets automatically invoked to create an object, whereas the method gets called explicitly.
Q-6: Is it permissible for a constructor to have a different name than its class name in Java?
Ans. No, constructors in Java should have the same name as their classes. If the name is different, then it would behave like a standard method.
Q-7: Is there any difference between an argument and a parameter?
Ans. While defining methods, you pass variables that you refer to as parameters. And, when you call these methods and supply values for the variables, then they are phrased as arguments.
Q-8: How your program would behave if you declare the main method as private?
Ans. It would get compiled correctly but will throw the error “Main method not public.” at runtime.
Q-9: What if an application gets multiple classes having main() methods?
Ans. It’s certainly possible to have multiple main methods in different classes. When you start the application, you’ve to provide the startup class name for execution. The JVM then looks up the main method only in the class whose name you’ve supplied. Hence, you won’t observe any conflict with the multiple classes having the <main()> definition.
Q-10: What difference do you see between pass-by-reference and pass-by-value in Java?
Ans. Pass by reference indicates, passing the address itself rather than passing the value. Pass by value means giving a copy of the value.
Q-11: What do you understand by Byte Code?
Ans. Java compiler generates bytecode for all the Java code and converts it into class files. The bytecode is platform-independent and needs the platform-specific JVM for the execution.
Q-12: What do you make of each keyword in public static void main(String args[])?
Ans.
- Public- <main()> is the entry point method that the JVM calls when a program starts. So it is mandatory to be accessible from the Java environment. Hence, the access specifier has to be public.
- Static- JVM must be capable of calling this method w/o creating an instance of the class. So the method has to be declared as static.
- Void- <main()> doesn’t return anything, so its return type must be void.
- The argument string represents the argument type passed from the console, and the <args> is an array of strings specified at the command line.
Also Read: How to format strings in Java
Q-13: Why do we use <final>, <finally>, and <finalize> keywords?
Ans.
- final– It’s used to declare a constant.
- Variables defined in an interface are implicitly final.
- You can’t extend a final class.
- finally– It makes you handle exceptions.
- It’s a keyword used for exception handling. The code under the <finally> block gets executed apparently.
- finalize– It helps in garbage collection.
- The <finalize()> method is used just before an object is destroyed and garbage collected.
Q-14: Can you compile a Java class successfully without having the “main” method?
Ans. Yes, we can compile, but it won’t run. The “main” method works as the startup function for a Java class, and the JVM calls it for the program execution.
Q-15: What do you make of System, out and <println> in the function System.out.println()
?
Ans.
- System -> A predefined final class,
- out -> PrintStream object and,
- The <println> -> built-in overloaded method of the out object.
Q-16: What do you understand by explicit casting?
Ans. It’s a process that instructs the compiler about transforming the object into a different type.
e.g. long no = 99999;
int new_no = (int) no; // Explicit casting
Q-17: Would a Java program compile/run if we use <static public void> instead of <public static void>?
Ans. Yes, the program will compile and run as usual.
Q-18: How would you prove that an array is not null but is empty?
Ans. Call the <Print array.length>. It will print 0. That suggests that the array is empty. If it would’ve been null then, it would’ve thrown a NullPointerException on calling the <Print array.length>.
Q-19: What do you understand of Garbage Collection and how to call it explicitly?
Ans. If the object no longer belongs to any variable, Java automatically reclaims the memory. This process is known as garbage collection. You can use the <System.gc()> method to call it explicitly.
Q-20: How does an unreachable object become reachable again, is it at all possible?
Ans. Yes, an unreachable object may get to a reachable state. It can happen if the object <finalize> method gets called during the garbage collection, and there you have set an object referring to it. This situation would cause the garbage collection to skip and make the object reachable again.
10 Java Classes Questions & Answers
The concept of Java classes is a very vast and complex area. You can read the below set of Java interview questions on classes specially prepared for Software test engineers.
Q-1: What is an interface, and why is it used?
Ans. An interface is similar to a class which may contain the method signature only but not bodies. And, it is a formal set of methods and constant declarations that must be defined by the class that implements it.
Interfaces are useful for:
1- Declaring methods that one or more classes are expected to implement.
2- Capturing similarities between unrelated classes without forcing a class relationship.
3- Determining an object’s programming interface without revealing the actual body of the class.
Q-2: What is an abstract class, and why is it used?
Ans. The abstract class serves as a template, and you can’t instantiate it. It may contain static data, and you’ve to extend it to make it functional.
Also, you must note that any class that has an abstract method automatically turns itself abstract.
Q-3: What difference do you see between an Abstract class and an Interface?
Ans. An interface by definition has all public members without any implementation. While an abstract class may group different flavors of class members like private, protected, etc. but has at least one abstract method.
Every abstract class must provide an instance method that defines its default behavior. While in an Interface, only the declaration of constants and instance methods is permissible, you can’t implement the default behavior, and all methods are abstract by default.
Q-4: Are there any performance implications of Interfaces over abstract classes, if yes, then specify.
Ans. Interfaces require additional indirections to find methods in the implementing class. This behavior makes them slower than in abstract classes. Another fact that a QA engineer should know is that a class can only extend a single abstract class whereas it can implement multiple interfaces.
Also, with interfaces, one has to address all of its methods, which leads to extra efforts during the development.
Q-5: What if you declare a class w/o any access modifiers, where can you use this class in your program?
Ans. When we don’t specify any access modifier for a class, then Java assigns package-level access to it. It implies that you can access such a class from other classes and interfaces within the boundary of that package.
Q-6: Explain the difference between function overloading and overriding.
Ans.
- Method Association: Overloading pertains to methods within the same class, whereas overriding concerns the relationship between a superclass method and its counterpart in a subclass.
- Inheritance Impact: Overloading does not affect inheritance from the superclass, whereas overriding can modify or restrict inheritance from the superclass.
- Method Names: In overloading, different methods within the same class can share the same name, while in overriding, methods in subclasses replace the versions inherited from the superclass.
- Parameter Distinction: Overloading requires methods to have distinct parameter signatures while overriding necessitates the use of the same method name and parameters as defined in the superclass.
Q-7: How would you describe the difference between this() and super()?
Ans. You can use this() for invoking the constructor of the class while super() helps to call the superclass constructor.
Q-8: What difference do you see between superclass and subclass?
Ans. A superclass is the one that you inherit, whereas the subclass is a class that makes the inheriting.
Q-9: What do you know about anonymous and inner classes?
Ans.
Inner classes- are the ones having their definition within other classes, including those defined in methods. These can assume any accessibility, including private, public, etc.
Anonymous class- It is a class that has its definition inside a method with no name. You can instantiate or declare it in the same place, and it doesn’t support explicit constructors.
Q-10: Describe the difference between a Sub-Class and an Inner Class.
Ans.
A subclass is a class that gets inherited from another class which is a superclass. It can easily access all public/protected methods and fields of its superclass.
The inner class is a class that gets cradled within another class. An Inner class can access all variables and methods provided by the outer class.
10 Java String Interview Questions
Java Strings are one of the most preferred topics for the Interviewers. Read the most frequently asked Java interview questions on strings.
Q-1: Is String a primitive data type in Java?
Ans. The String is amongst the core Java classes, and it’s not related to any basic Java data types like int, long, or float. It’s a derived class that comes with the <java.lang> Package. It makes use of a character array to manage its content.
Q-2: Is String in Java final by default, if yes then why?
Ans. Yes, the Java designers kept it as final to enable security, optimization, and managing the string pool.
Q-3: What difference do you see between String and String Buffer classes in Java?
Ans. You must note that both the String and String Buffer are two distinct classes. The most important difference between them is that every change in a String causes the creation of a new String; the String Buffer eliminates this bottleneck. String Buffer is mainly used to support the concatenation of Strings.
Q-4: What do you understand by the string constant pool?
Ans. It belongs to a section of the memory that holds the string objects created using string literals. This pool doesn’t allow any two string objects to point to the same content.
JVM ensures no two string objects have duplicate content. If it receives any such request, it returns the reference of the object matching the content instead of creating a new one.
Q-5: Explain the difference between mutable and immutable objects.
Ans. Immutable objects work like constants. It means that they don’t accept any changes once created.
They are final by design. On the contrary, the mutable objects allow modifications to them.
Q-6: Which of these classes are final?
String, StringBuffer, and StringBuilder.
Ans. All of these classes are final.
Q-7: What is the number of objects getting created in the below Java code snippet?
String first = "TechBeamers"; String second = "TechBeamers";
Ans. The above code would only lead to the creation of one String object in the String constant pool as both the strings are referring to the same content.
Q-8: How would you create mutable string objects?
Ans. We can use String Buffer and String Builder classes for creating the mutable strings.
Q-9: What do you understand string intern?
Ans. Every string object in the string constant pool is known as the string Intern. You can create a replica of objects lying in a string constant pool. We call this process interning. Java provides <intern()> method for this purpose.
Q-10: What difference do you see between String and StringBuffer classes?
Ans. First, let’s see the similarity, which is both the String and StringBuffer classes are thread-safe. Next, the primary difference between them is that String objects are immutable while the String Buffer objects are mutable.
10 Java Multi-Threading Interview Questions
Java threading/synchronization are the most complex areas for Software testers. We recommend going through the below list of 10 essential Java interview questions for QA engineers.
Q-1: How do you define a Thread in Java?
Ans. The thread is the smallest unit of execution in a program. It optimally consumes the CPU and improves the performance of the application. Some of the characteristics of Java threads are as follows.
- These are lightweight Java processes.
- The thread class is a part of the <java.lang> package.
- You can create many threads in Java, and even the “main” method runs on a thread.
- Java supports the concurrent execution of multiple threads.
- Threads manage their stack.
Q-2: What difference do you see between Process and Thread in Java?
Ans.
- A single process can own multiple threads.
- Threads are the smaller execution units of a Process.
- Processes possess their copy of the data segment of the parent process while the threads share the data portion of its process.
- Threads share the address space of the process, whereas processes have their respective addresses.
- Processes can easily communicate with child processes using IPC (interprocess communication). While the threads communicate with other threads of the same process using the wait(), notify(), and notifyAll() methods.
Q-3: What are the different ways to create Threads in Java?
Ans. There are two ways to create Threads, i.e., by implementing the <java.lang.Runnable> interface or by extending the <java.lang.Thread> class and then define the run method.
E.g. Java code example.
public class ImplementThreadByExtend extends Thread{ public void run(){ // Write your code here. // Your code will get run by a new thread. } public static void main(String [] args){ ImplementThreadByExtend th = new ImplementThreadByExtend(); th.start(); } }
public class ImplementThreadByRunnable implements Runnable{ public void run(){ //... } public static void main(String [] args){ ImplementThreadByRunnable th = new ImplementThreadByRunnable(); Thread thread = new Thread(th); thread.start(); } }
Q-4: How would you differentiate between a thread starting with the run() and start() method?
Ans.
- While using the start() method, the main thread internally invokes the run() method to launch the newly created Thread.
- When you invoke the run() method, the main thread starts the run() method by itself.
Q-5: What is the significance of using the <volatile> keyword?
Ans. Java permits threads to retrieve shared variables. If you declare a field as volatile, the Java memory model ensures that all threads see a consistent value of the variable.
Q-6: Does Java support the <volatile> methods?
Ans. No, <volatile> is a standard keyword that you can only use for variables.
Q-7: Does Java enables support of synchronized variable?
Ans. No, the synchronized keyword can be used only with methods, i.e., in the method declaration.
Q-8: Is it permissible to restart a Thread?
Ans. No, you can’t start a thread again. If you do so, the system will throw the runtimeException <java.lang.IllegalThreadStateException>. It occurs because the thread goes into the absolute state after executing the run() method.
Q-9: What do you make of the daemon threads?
Ans. These are low-priority threads that run intermittently in the background for the purpose of garbage collection.
Q-10: What is the process of Synchronization, and why is it used?
Ans. Synchronization is a way of managing the access of shared resources in such a manner that not more than one thread could lock a particular resource at a given time.
It helps protect your application resources when multiple threads are accessing them and may change their state which could lead to data corruption. Java supports it using the <synchronized> construct.
Java Interview Questions – Final Review
We’ve now come to the end of this post, and we would certainly like to know your feedback on the above Java interview questions. It’ll be great to hear from all of you because we write and share what we know and what could be useful for our readers. When someone leaves his/her response that instantly raises the motivation level and encourages us to continue delivering quality content.
You are also welcome to add your experience to this post. Do provide us with more quality Java interview questions, and we’ll review and include them in the above list. It would immensely help the rest of us as they may get asked similar questions during their job interviews.
Lastly, don’t forget to participate in this skill enhancement drive by sharing this fantastic list of the best Java interview questions on social media to help a large number of buddying test engineers around the globe.
All the very best,
TechBeamers