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 intdoubleboolean) store simple values directly.
  • Wrapper classes (like IntegerDoubleBoolean) 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: byteshortintlongfloatdoublecharboolean.
  • 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 forwhile, and do...while loops.
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 int to long). Java does this automatically.
  • Narrowing casting is when a bigger type is changed to a smaller type (for example double to int). 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:

  • final is used to make a variable that cannot be changed after it gets a value.
  • const is 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 default and static methods 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/catch or declared with throws. 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 Thread class and override the run() method.
  • Or implement the Runnable interface and pass the object to a Thread object.

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 call run() 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();
}

Advanced Java Programming Concepts and Projects (Related to Java Programming)


Number Guessing Game in Java:
This project teaches how to build a simple number guessing game using Java. It combines random number generation, loops, and conditional statements to create an interactive program where users guess a number until they find the correct answer.
Read more: https://macronepal.com/blog/number-guessing-game-in-java-a-complete-guide/


HashMap Basics in Java:
HashMap is a collection class used to store data in key-value pairs. It allows fast retrieval of values using keys and is widely used when working with structured data that requires quick searching and updating.
Read more: https://macronepal.com/blog/hashmap-basics-in-java-a-complete-guide/


Date and Time in Java:
This topic explains how to work with dates and times in Java using built-in classes. It helps developers manage time-related data such as current date, formatting time, and calculating time differences.
Read more: https://macronepal.com/blog/date-and-time-in-java-a-complete-guide/


StringBuilder in Java:
StringBuilder is used to create and modify strings efficiently. Unlike regular strings, it allows changes without creating new objects, making programs faster when handling large or frequently changing text.
Read more: https://macronepal.com/blog/stringbuilder-in-java-a-complete-guide/


Packages in Java:
Packages help organize Java classes into groups, making programs easier to manage and maintain. They also help prevent naming conflicts and improve code structure in large applications.
Read more: https://macronepal.com/blog/packages-in-java-a-complete-guide/


Interfaces in Java:
Interfaces define a set of methods that classes must implement. They help achieve abstraction and support multiple inheritance in Java, making programs more flexible and organized.
Read more: https://macronepal.com/blog/interfaces-in-java-a-complete-guide/


Abstract Classes in Java:
Abstract classes are classes that cannot be instantiated directly and may contain both abstract and non-abstract methods. They are used as base classes to define common features for other classes.
Read more: https://macronepal.com/blog/abstract-classes-in-java-a-complete-guide/


Method Overriding in Java:
Method overriding occurs when a subclass provides its own version of a method already defined in its parent class. It supports runtime polymorphism and allows customized behavior in child classes.
Read more: https://macronepal.com/blog/method-overriding-in-java-a-complete-guide/


The This Keyword in Java:
The this keyword refers to the current object in a class. It is used to access instance variables, call constructors, and differentiate between class variables and parameters.
Read more: https://macronepal.com/blog/the-this-keyword-in-java-a-complete-guide/


Encapsulation in Java:
Encapsulation is an object-oriented concept that involves bundling data and methods into a single unit and restricting direct access to some components. It improves data security and program organization.
Read more: https://macronepal.com/blog/encapsulation-in-java-a-complete-guide/

Leave a Reply

Your email address will not be published. Required fields are marked *


Macro Nepal Helper