Java is still the most powerful tool in the tech world due to its versatility, platform independence and sturdiness. Java continues to be the favorite language for developers and organizations, both large and small alike, from enterprise solutions to mobile apps.
This comprehensive Java interview guide will help if you are preparing for a Java interview. It is divided into basic, intermediate & advanced levels. You will also have a quiz section in which you will answer multiple-choice questions to test your understanding.
Basic Java Interview Questions and Answers
1. What are the features of Java?
Java offers features such as:
- Platform Independence: Memory and I/O independence, also known as the write once, run anywhere capability.
- Object-Oriented: It focuses on the modular design of objects and classes.
- Robust: It has run-time errors that have been dealt with by exception handling and garbage collection.
- Multithreading: It supports concurrent execution of threads.
- Secure: Can do features such as bytecode verification and runtime checks.
2. What is the key difference between JRE, JVM, and JDK?
JDK | JRE | JVM |
A toolkit for developing Java applications. It includes the compiler, JRE, and development tools. | Provides the environment to run Java applications and contains the JVM. | Executes Java bytecode on different machines. |
Check out our free courses on Java applications
3. What is the main method in Java?
The main method is the starting point of any Java Program, which is used by the compiler to tell where the program starts. The syntax is:
public static void main(String[] args)
4. What is a Constructor in Java?
When it gets created, an object is initialized by a constructor. It neither returns any type nor has a return type. There are two types:
- Default Constructor: No parameters.
- Parameterized Constructor: Parameters to initialize fields are accepted
5. What is the difference between == and .equals()?
==: Compares memory addresses (reference equality).
.equals(): Compares the content of objects (value equality).
6. What are the different types of variables in Java?
- Local Variables: Defined within a method or block and only available there.
- Instance Variables: Outside of methods, within a class.
- Static Variables: Can be declared using the keyword static and shared among all objects of the class.
7. What are Java Data Types?
Java mainly has two types of data types, primitive and non-primitive/reference types. primitive data types are int, float, char, boolean, etc. non primitive data types include Arrays, objects, and interfaces.
8. What is the role of the final keyword in Java?
- final variable: Makes the variable constant.
- final method: Prevents method overriding.
- final class: Prevents class inheritance.
9. What is the difference between break and continue?
The break is used to exit a loop entirely, whereas continue is used to skip the current iteration and continue with the next iteration.
10. What is a package in Java?
A package is a namespace which groups related classes, interfaces, and other types together. There are two types of packages: built-in and user-defined packages.
11. What is garbage collection in Java?
Garbage collection automatically deallocates unused objects in memory. The JVM handles it using a garbage collector.
12. What are access modifiers in Java?
Access modifiers control the scope of a class, method, or variable.
- Public: Accessible everywhere.
- Protected: Accessible within the package and subclasses.
- Private: Accessible only within the class.
- Default: Accessible within the package.
If you want to learn more about data structures in Java, then you can check out the “Data Structures in Java: Beginner’s Guide.”
You can also get started with our free courses
Intermediate Java Interview Questions and Answers
13. What are the principles of Object Oriented Programming (OOP)?
OOP is based on four principles:
- Encapsulation: Wrapping up data and methods in a single chunk (a class).
- Inheritance: Take the properties and methods from a parent class and reuse them using inheritance.
- Polymorphism: Objects can take multiple forms (method overloading and overriding).
- Abstraction: It hides the implementation details and exposes the least functionality that is required.
14. Determine the difference between method overriding and method overloading.
- Overriding: Overriding a method in a subclass with the same name, return type and parameters.
- Overloading: Functions of multiple methods in the same class with the same but different function parameters.
15. What are abstract classes and interfaces?
- Abstract Class: A class that can contain both abstract and concrete methods that cannot be instantiated.
- Interface: A class that describes just abstract methods (before Java 8). Starting Java 8+, interfaces can have default and static methods.
Learn more about classes in Java with our free course
16. What are the differences between ArrayList and LinkedList?
- ArrayList: Faster (random access) uses a dynamic array.
- LinkedList: Underused, better for insertions and deletions, uses doubly linked nodes.
17. What is the Java Collections Framework?
A company that stores and processes data in an efficient manner is represented
by different classes and interfaces as a Collections Framework. Key interfaces include:
- List: ArrayList, LinkedList.
- Set: Elements specific in some way (HashSet, TreeSet).
- Map: Examples include key-value pairs (HashMap, TreeMap).
Learn more about Java Collections for free
18. Describe Java’s exception handling.
It is the process of managing errors by using try, catch, finally, throw, and throws keywords, which developers cause errors or unexpected events during program execution.
- Try: This code, which may cause an exception, gets enclosed.
- catch: Handles the exception.
- Finally, It will execute the code after try-catch even if an exception occurs.
- throw: I use it to explicitly throw an exception.
- Throws: Defines what exceptions a method may throw.
Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} finally {
System.out.println("Execution complete.");
}
19. What are checked and unchecked exceptions?
- Checked Exceptions: Although it is not required, it must be declared or handled (IOException).
- Unchecked Exceptions: They occur at runtime and don’t have to be declared (For example NullPointerException).
20. What is going to happen in HashMap in Java?
HashMap utilizes hashing to store key value pairs. Key hashed and mapped to a bucket, where value is stored. Collision is handled by using a linked list or binary tree.
21. Do you know the major difference between Hashtable and HashMap?
- Thread Safety: Hashtable is synchronized, but HashMap is not.
- Null Keys/Values: Hashtable doesn’t support null keys or null values, and HashMap supports one null key and multiple null values.
22. Explain the difference between throw and throw.
- throw: It used to be used to explicitly throw an exception.
- throws: Tells the exceptions that a method can throw in its signature.
Example:
void method() throws IOException {
throw new IOException("Exception occurred");
}
23. What’s the difference between Iterator and ListIterator?
- Iterator: Forward traverses Set and List.
- ListIterator: It extends the Iterator and traverses both from forward and reverse directions.
24. What is transient in Java?
The concept of the transient keyword allows you to prevent a variable from being serialized. For example:
class Example implements Serializable {
transient int id; // This field will not be serialized
}
25. Explain the concept of multithreading in Java.
Multithreading allows multiple threads to execute simultaneously, improving performance. Threads can be created by:
Extending the Thread class or implementing the runnable interface.
Example by using Runnable:
class MyThread implements Runnable {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
Thread t = new Thread(new MyThread());
t.start();
}
}
Exception handling is one of the main concepts in Java which is asked in interviews. You can learn more about it in this blog “Exception handling in Java.”
Advanced Java Interview Questions and Answers
26. How is notify() different from notifyAll() in Java?
- notify(): Notifies all the waiting readers and wakes up the single thread waiting on the object’s monitor.
- notifyAll(): Awakens all threads which are waiting on the object’s monitor.
27. What is a Callable in Java?
Java.util.concurrent contains an interface that is called callable, this interface allows for threads to return a value and throw checked exceptions. The ExecutorService is used with this.
Example:
Callable<Integer> task = () -> {
return 123;
};
28. What is the Fork/Join Framework exactly?
Java’s Fork/Join Framework divides work into smaller work, runs them in parallel and
then combine the result. The ForkJoinPool class is used for implementation.
29. What is the difference between HashMap and ConcurrentHashMap?
- Thread Safety: HashMap is not thread-safe, but ConcurrentHashMap is.
- Performance: Other than that, ConcurrentHanswerMap provides concurrent reads and updates.
30. What is the difference between final, finally, and finalize?
- final: It’s a keyword to declare constant, override methods and inheritance.
- finally: A block that is run in exception handling, always.
- finalize: Garbage collector calls a method before an object is destroyed.
31. What are the important aspects of Java 8?
- Lambdas and Streams.
- Interfaces and interface methods – default and static methods.
- A null value class that is optional.
- Easy data handling with Date and Time API.
32. What good does the volatile keyword serve?
It is volatile, so it guarantees the visibility of changes that vary across threads. Oblivious
to caching of variables by threads.
33. What happens when we don’t concern ourselves with garbage collection?
Garbage collection is an automatic process in java that reclaims the memory that is occupied by unused objects. The JVM uses algorithms like:
- Mark and Sweep: It marks objects for deletion and reclaims memory.
- Generational GC: It organizes memory into three generations of young, old and permanent, which makes it efficient to manage.
34. What is immutability in Java, and how do I explain it?
Once created, an immutable object’s state cannot be changed. For example, Stack is immutable.
To make a class immutable:
- Declare the class as final.
- Change all fields to be private and final.
- Provide no setters.
35. What is the difference between Comparable and Comparator?
- Comparable: Natural ordering of objects is defined using compareTo() and implemented.
- Comparator: It defines custom ordering and is implemented using compare().
36. What is ExecutorService in Java?
ExecutorService is part of the Java.util.concurrent package, managing thread pools and simplifying thread execution.
Example:
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> System.out.println("Task executed"));
executor.shutdown();
37. Explain Java 8 streams.
Java 8 has Streams, which give us functions in a collection. Intermediate operations take
the form of filter() and map(), and terminals take the form of collect() for each ().
Example:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.stream().filter(name -> name.startsWith("A")).forEach(System.out::println);
Also, get hands on experience in Java with Java Projects Free Course
Java Exercise: MCQs
Q. Which of the following is not a Java feature?
Q. The default value of a boolean variable in Java is?
Q. Which method is called to start a thread in Java?
Q. Which of these is used to handle exceptions in Java?
Q. What is the size of an int in Java?
Q. Which keyword is used to prevent method overriding?
Q. Which of these is not a wrapper class in Java?
Q. What does the hashCode() method return?
Q. What is the default access modifier for a class in Java?
Q. Which package contains the Scanner class?
To learn more about terms like Polymorphism, Inheritance, and access modifiers you can check out these “Polymorphism in Java”, ”Inheritance in Java”, and ”Access Modifiers in Java”.
Conclusion
Java is still a must-have skill for any aspiring developer who would like to catch up with all the current trends. If you want to stand out in the competitive tech industry, mastering Java concepts at every level—basic, intermediate, and advanced—is essential whether you are preparing for interviews, and it’s always great to improve your knowledge.
This is a blog that discusses the most early-on common Java interview questions and their thorough answers. It also has a quiz to evaluate your understanding of yours. Covering underlying Jvm, JRE, and JDK, as well as cutting-edge concepts like multithreading and Java 8 features, this material is guaranteed to build you up to pass the interview confidently.
FAQs
For better preparation, you must ensure you start from the basics of Java including its syntax, JVM, JRE & JDK. Proceed gradually with intermediate topics such as OOP principles, exception handling, collections. Last but not least, dive into more complex stuff such as multithreading, Java 8 goodies, and performance tuning. Practice coding problem solving and mock interviews.
Java fundamentals (e.g., JVM, data types), OOP concepts, collections, framework, exception handling etc. are covered most of the time in interview questions and Java 8 (Streams and lambdas) features are also often asked in Java interviews. Multithreading, concurrency, and design patterns are part of these advanced topics. Thoroughly reviewing such topics will make you confident while dealing with most interviews.
Java interviews do need coding skills. Often, employers want to test your code writing skills to solve problems in an efficient and clean manner. Do practice coding exercises for data structures, algorithms and Java specific implementations on platforms LeetCode/HackerRank to stand up a better chance distinguishing yourself.