Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS

Java Tutorial

Java HOME Java Intro Java Get Started Java Syntax Java Output Java Comments Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Math Java Booleans Java If...Else Java Switch Java While Loop Java For Loop Java Break/Continue Java Arrays

Java Methods

Java Methods Java Method Challenge Java Method Parameters Java Method Overloading Java Scope Java Recursion

Java Classes

Java OOP Java Classes/Objects Java Class Attributes Java Class Methods Java Class Challenge Java Constructors Java this Keyword Java Modifiers Java Encapsulation Java Packages / API Java Inheritance Java Polymorphism Java super Keyword Java Inner Classes Java Abstraction Java Interface Java Anonymous Java OOP Visuals Java Enum Java User Input Java Date

Java Errors

Java Errors Java Debugging Java Exceptions Java Multiple Exceptions Java try-with-resources

Java Problem Solving

Java Problem Solving Java Build the Logic Java Test Cases

Java Projects

Java Projects

Java File Handling

Java Files Java Create Files Java Write Files Java Read Files Java Delete Files

Java I/O Streams

Java I/O Streams Java FileInputStream Java FileOutputStream Java BufferedReader Java BufferedWriter

Java Data Structures

Java Data Structures Java Collections Java List Java ArrayList Java LinkedList Java List Sorting Java Set Java HashSet Java TreeSet Java LinkedHashSet Java Map Java HashMap Java TreeMap Java LinkedHashMap Java Iterator Java Algorithms

Java Advanced

Java Wrapper Classes Java Generics Java Annotations Java RegEx Java Threads Java Lambda Java Optional Java Advanced Sorting

Java Cert

Java Certificate

Java How To's

Java How Tos

Java Examples

Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Practice Problems Java Server Java Syllabus Java Study Plan Java Interview Q&A

Java Reference

Java Reference Java Keywords ArrayList Methods Arrays Methods BufferedReader BufferedWriter Character Methods Collections Methods Comparator Methods Date and Time Enum Methods Errors & Exceptions File Methods FileInputStream FileOutputStream FileReader FileWriter HashMap Methods HashSet Methods Integer Methods Iterator Methods LinkedHashMap Methods LinkedHashSet Methods LinkedList Methods Math Methods Optional Methods Output Methods Random Methods RegEx Methods Scanner Methods String Methods StringBuilder Methods System Methods Thread Methods TreeMap Methods TreeSet Methods


Java Interview Questions


Share

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.

Each answer links to the tutorial chapter where you can learn more. At the end of the page, you can test yourself with an interview quiz.

  • Core Java basics
  • Loops and switch
  • Strings and arrays
  • 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".

Learn more: Java Strings


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

Learn more: Java String equals() Method


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");
  }
}

Learn more: Java Syntax



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.

Learn more: Java Wrapper Classes


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";

Learn more: Java Variables


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.

Learn more: Java Data Types


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");
}

Learn more: Java If...Else


8. What is a loop in Java?

Answer:

  • A loop repeats the same block of code several times.
  • Java has for, while, and do...while loops.
for (int i = 1; i <= 5; i++) {
  System.out.println("Count: " + i);
}

Learn more: Java For Loop


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

Learn more: Java Type Casting


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

Learn more: Java Constants (Final)


11. What is the difference between JDK, JRE and JVM?

Answer:

  • The JVM (Java Virtual Machine) runs Java programs. It runs the compiled code (bytecode), so the same program can run on Windows, Mac and Linux.
  • The JRE (Java Runtime Environment) is the JVM plus the libraries that Java programs need to run.
  • The JDK (Java Development Kit) is the JRE plus the tools to make programs, like the compiler (javac). You need the JDK to write and compile Java code.

Learn more: Java Get Started


12. What is the difference between i++ and ++i?

Answer:

  • Both add 1 to i.
  • i++ uses the current value first, and then adds 1. ++i adds 1 first, and then uses the new value:
int i = 5;
int a = i++;   // a is 5, i is 6

int j = 5;
int b = ++j;   // b is 6, j is 6

Learn more: Java Arithmetic Operators


13. What does 7 / 2 give in Java?

Answer:

  • When both numbers are integers, the result is also an integer, and the decimals are removed.
  • If one of the numbers is a double, the result keeps the decimals:
System.out.println(7 / 2);     // 3
System.out.println(7 / 2.0);   // 3.5

Learn more: Java Arithmetic Operators


Loops and Switch

14. What is the difference between break and continue?

Answer:

  • break stops the loop completely.
  • continue skips the rest of the current round, and goes on with the next one:
for (int i = 1; i <= 5; i++) {
  if (i == 2) {
    continue;  // Skip 2
  }
  if (i == 4) {
    break;     // Stop at 4
  }
  System.out.println(i);
}
// Prints 1 and 3

Learn more: Java Break and Continue


15. What happens if you forget break in a switch?

Answer:

  • Without break, the program goes on and runs the code in the next case too. This is called fall-through:
int day = 1;

switch (day) {
  case 1:
    System.out.println("Monday");
  case 2:
    System.out.println("Tuesday");
    break;
}
// Prints Monday and Tuesday

Learn more: Java Switch


Strings and Arrays

16. What is the difference between String and StringBuilder?

Answer:

  • A String cannot be changed after it is created. When you add text, Java creates a new string.
  • A StringBuilder can be changed, so it is faster when you add text many times, for example in a loop:
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb);   // Hello World

Learn more: Java StringBuilder


17. What is the difference between length, length() and size()?

Answer:

  • Arrays use length (with no parentheses), strings use length(), and collections like ArrayList use size():
int[] numbers = {1, 2, 3};
String name = "Liam";
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");

System.out.println(numbers.length);   // 3
System.out.println(name.length());    // 4
System.out.println(cars.size());      // 1

Learn more: Java Arrays


18. What is the difference between an array and an ArrayList?

Answer:

  • An array has a fixed size. You cannot add more elements after it is created.
  • An ArrayList can grow and shrink. Use add() and remove() to change it.
  • An array can store primitive types like int. An ArrayList stores objects, so you use wrapper classes like Integer.

Learn more: Java ArrayList


Object-Oriented Programming

19. What is the difference between a class and an object?

Answer:

  • A class is a template (a blueprint) for objects.
  • An object is created from a class, and has its own values:
class Car {
  String color;
}

Car myCar = new Car();   // An object of the Car class
myCar.color = "Red";

Learn more: Java Classes and Objects


20. What is a constructor?

Answer:

  • A constructor is a special method that runs when you create an object. It is often used to give the attributes their first values.
  • It has the same name as the class, and no return type:
class Car {
  String color;

  Car(String c) {
    color = c;
  }
}

Car myCar = new Car("Red");

Learn more: Java Constructors


21. What does the this keyword do?

Answer:

  • this refers to the current object.
  • It is often used when a parameter has the same name as an attribute:
class Car {
  String color;

  Car(String color) {
    this.color = color;   // this.color is the attribute
  }
}

Learn more: Java this Keyword


22. What does static mean?

Answer:

  • A static method or attribute belongs to the class, not to one object.
  • You can use it without creating an object, and a static attribute is shared by all the objects:
class Counter {
  static int count = 0;

  Counter() {
    count++;
  }
}

new Counter();
new Counter();
System.out.println(Counter.count);   // 2

Learn more: Java Class Methods


23. What is the difference between public, private and protected?

Answer:

  • public - the code can be used from any class.
  • private - the code can only be used inside its own class.
  • protected - the code can be used in the same package, and in subclasses (classes that inherit from it).
  • With no modifier, the code can only be used in the same package.

Learn more: Java Modifiers


24. 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.

Learn more: Java OOP


25. 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.

Learn more: Java Abstraction and Java Interface


26. 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");
  }
}

Learn more: Java Method Overloading and Java Polymorphism


Collections and Generics

27. 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.

Learn more: Java Collections


28. 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.

Learn more: Java LinkedList


29. 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.

Learn more: Java Generics


30. What is the difference between Comparable and Comparator?

Answer:

  • Comparable is implemented by the class itself, with a compareTo() method. It gives the objects one natural order, for example by name.
  • A Comparator is a separate object with a compare() method. You can make many comparators, to sort the same objects in different ways.

Learn more: Java Advanced Sorting


Exceptions and Error Handling

31. 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.

Learn more: Java Exceptions


32. 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.

Learn more: Java Exceptions


33. What is the difference between throw and throws?

Answer:

  • throw creates an exception, and stops the method.
  • throws is written after the method name, to tell that the method can throw an exception:
static void checkAge(int age) throws Exception {
  if (age < 18) {
    throw new Exception("Access denied");
  }
}

Learn more: Java throw Keyword and Java throws Keyword


34. What is a NullPointerException?

Answer:

  • It happens when you use a variable that points to null (no object), for example when you call a method on it.
  • To avoid it, check for null before you use the object:
String name = null;

if (name != null) {
  System.out.println(name.length());
}
  • You can also use Optional for values that can be missing.

Learn more: Java Optional


Multithreading and Concurrency

35. 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.

Learn more: Java Threads


36. 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
  }
}

Learn more: Java Threads


Java 8 and Later

37. 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.

Learn more: Java Lambda


38. 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

39. 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);

Learn more: Java Debugging


40. 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

Learn more: Java Errors


41. 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

Learn more: Java Errors


42. 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();
}

Learn more: Java try-with-resources


Test Yourself: Interview Quiz

Ready for the interview? Choose your answer to each question, and read the explanation:

Question

Code


Explanation


Prepare for Your Interview


Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.