Java Interview Questions
Java Interview Questions with Answers
This page gives simple Java interview questions with short answers. The questions are made for beginners, so you can use them to study for tests and job interviews.
- Core Java basics
- Object-oriented programming
- Collections and generics
- Exceptions and error handling
- Multithreading and concurrency
- Java 8 and later features
- Practical coding and debugging
Core Java Basics
1. What is a String in Java?
Answer:
- A String is used to store text.
- Examples:
"Hello","Java".
2. What is the difference between == and equals()?
Answer:
==checks if two values come from the exact same object.equals()checks if two values have the same value.
String a = new String("Java");
String b = new String("Java");
System.out.println(a == b); // false, different objects
System.out.println(a.equals(b)); // true, same value
3. What is the purpose of the main() method in Java?
Answer:
- This is where the program starts running. Java looks for main() to begin executing the code.
- The method must look like this:
public static void main(String[] args).
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
4. What is the difference between primitive types and wrapper classes?
Answer:
- Primitive types (like
int,double,boolean) store simple values directly. - Wrapper classes (like
Integer,Double,Boolean) store these values inside objects. - Wrapper objects are often used when you work with collections such as
ArrayList.
5. What are variables in Java?
Answer:
- A variable is a name that stores a value in memory.
- In Java, you must write the type of the variable before the name.
int age = 35;
double price = 19.99;
String name = "Jenny";
6. What are Java data types?
Answer:
- Primitive types store simple values:
byte,short,int,long,float,double,char,boolean. - Reference types point to objects, for example
String, arrays, and your own classes.
7. How do conditionals (if/else) work in Java?
Answer: Conditional statements let your program choose what to do based on true or false tests.
int score = 85;
if (score >= 90) {
System.out.println("Excellent");
} else if (score >= 75) {
System.out.println("Good");
} else {
System.out.println("Needs Improvement");
}
8. What is a loop in Java?
Answer:
- A loop repeats the same block of code several times.
- Java has
for,while, anddo...whileloops.
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
9. What is type casting in Java?
Answer:
- Widening casting is when a smaller type is changed to a bigger type (for example
inttolong). Java does this automatically. - Narrowing casting is when a bigger type is changed to a smaller type (for example
doubletoint). You must write the cast yourself.
double x = 9.7;
int y = (int) x; // narrowing cast, y becomes 9
10. What is the difference between final and const in Java?
Answer:
finalis used to make a variable that cannot be changed after it gets a value.constis a reserved word in Java, but you do not use it.
final int MAX_LIMIT = 100;
// MAX_LIMIT = 200; // Error: you cannot change a final variable
Object-Oriented Programming
11. What are the four main OOP principles?
Answer:
- Encapsulation - Keep the data inside the class and use methods to work with it.
- Inheritance - One class can reuse code from another class.
- Polymorphism - The same method name can do different things depending on the object.
- Abstraction - Show only what the user needs, hide the details.
12. What is the difference between an abstract class and an interface?
Answer:
- An abstract class can have normal methods with code, abstract methods without code, and fields.
- An interface is mainly a list of methods that a class must implement. From Java 8, interfaces can also have
defaultandstaticmethods with code.
13. What is the difference between method overloading and method overriding?
Answer:
- Overloading - Same method name in the same class, but different parameters.
- Overriding - A child class replaces a method from the parent class with its own version.
class Animal {
void speak() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
@Override
void speak() {
System.out.println("Woof");
}
void speak(String name) {
System.out.println(name + " says Woof");
}
}
Collections and Generics
14. What is the difference between List, Set, and Map?
Answer:
- List - Keeps elements in order and can contain duplicates.
- Set - Does not allow duplicate elements.
- Map - Stores key and value pairs. Each key is unique and points to one value.
15. What is the difference between ArrayList and LinkedList?
Answer:
- ArrayList uses a growable array inside. It is fast for reading by index (like
list.get(0)). - LinkedList uses nodes that link to each other. It can be faster for adding and removing elements in the middle of the list.
16. Why do we use generics in Java?
Answer: Generics let you tell a collection what type it should hold. This helps you find type errors at compile time and removes many casts.
Exceptions and Error Handling
17. What is the difference between checked and unchecked exceptions?
Answer:
- Checked exceptions must be handled with
try/catchor declared withthrows. Example:IOException. - Unchecked exceptions happen while the program is running and do not need to be declared. Example:
NullPointerException.
18. What is the purpose of the finally block?
Answer: A finally block is used for code that should run at the end of a try block, whether there was an exception or not. It is often used to close files or release other resources.
Multithreading and Concurrency
19. How do you create a thread in Java?
Answer:
- Extend the
Threadclass and override therun()method. - Or implement the
Runnableinterface and pass the object to aThreadobject.
20. What is the difference between start() and run() in a thread?
Answer:
run()has the code that should be executed by the thread.start()tells the JVM to create a new thread and then callrun()in that new thread.- If you call
run()directly, the code runs in the current thread, not in a new one.
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start(); // starts a new thread
t.run(); // just calls run like a normal method
}
}
Java 8 and Later
21. What is a lambda expression?
Answer: A lambda expression is a short way to write a method as an expression. It is often used when you need to pass small pieces of code to methods, for example when working with streams.
22. What is the Java Stream API?
Answer: The Stream API lets you work with collections in a simple way. You can filter, sort, and change data step by step, instead of writing many loops by hand.
Practical Coding and Debugging
23. What is the purpose of printing debug messages?
Answer:
- Debug messages show you what the program is doing while it runs.
- They help you see the values of variables at different points in the code.
- In Java, you often print debug messages with
System.out.println().
int total = 50;
System.out.println("Debug: total = " + total);
24. What does the term syntax error mean?
Answer:
- A syntax error means the code does not follow the rules of the Java language.
- The compiler finds syntax errors before the program can run.
- Examples are missing semicolons or a missing closing brace.
// Syntax error: missing semicolon
int x = 10
25. What is a runtime error?
Answer:
- A runtime error happens when the program is running.
- The code compiles, but something goes wrong while it is running.
- Example: dividing by zero, or using an array index that is outside the array.
// Runtime error: division by zero
int x = 10 / 0; // causes ArithmeticException
26. What is the recommended way to close resources?
Answer: The recommended way is to use a try-with-resources block. Java will then close the resource for you when the block ends.
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}