All Java Interview Questions

What is the difference between Java and JavaScript?

Despite the name, they are two different languages.

PointJavaJavaScript
TypeCompiled, strongly typedInterpreted, dynamically typed
Runs inJVM (Java Virtual Machine)Browser and Node.js
Used forAndroid apps, backend, enterprise softwareWeb pages, web apps, servers with Node.js
Code styleClass-based alwaysPrototype-based, with classes as syntax

JavaScript got the name only because Java was very popular in 1995.

What is Java?

Java is a general purpose, object oriented programming language, first released by Sun Microsystems in 1995 and now looked after by Oracle and the OpenJDK community. You write the code once, and it runs on any system which has a Java Virtual Machine (JVM): “write once, run anywhere”.

It is used for web back ends, Android apps, enterprise software, big data tools and many other things. You can see the Java version on your computer with one command:

Terminal

$ java -version
openjdk version "25.0.5" 2026-10-20 LTS
OpenJDK Runtime Environment Temurin-25.0.5+8 (build 25.0.5+8-LTS)
OpenJDK 64-Bit Server VM Temurin-25.0.5+8 (build 25.0.5+8-LTS, mixed mode, sharing)

Read more in Java Introduction and What is Java? JDK, JRE and JVM.

What are the main features of Java?

  • Object oriented: code is organized in classes and objects (inheritance, polymorphism, encapsulation, abstraction).
  • Platform independent: the compiler makes bytecode, which runs on any JVM.
  • Strongly typed: every variable has a type and the compiler checks it.
  • Automatic memory management: the garbage collector frees the unused objects.
  • Multithreaded: a program can do many jobs at the same time.
  • Secure and robust: no pointer arithmetic, good exception handling and a security manager model.
  • Rich standard library: collections, files, networking, dates and much more.
  • Simple syntax: it looks like C and C++, but it is simpler and safer.

See What is Java? for more details.

What is the difference between JDK, JRE and JVM?

NameFull nameWhat it is
JVMJava Virtual MachineRuns the bytecode and manages memory (garbage collection)
JREJava Runtime EnvironmentThe JVM plus the class libraries, to run Java programs
JDKJava Development KitThe JRE plus tools to develop: javac, jar, javadoc and others

In short: JDK contains JRE, and JRE contains JVM. To write programs you need the JDK. Today the downloads of Java are JDKs, and a separate JRE is no longer given for new versions.

Terminal

$ javac -version
javac 25.0.5
$ java -version 2>&1 | head -1
openjdk version "25.0.5" 2026-10-20 LTS

Why is Java platform independent?

When you compile a Java file, javac does not make code for Windows or Linux. It makes bytecode in a .class file. Each operating system has its own JVM, which reads the same bytecode and runs it. So the same .class file works everywhere.

Note that the JVM is platform dependent (there is a different JVM for each system), but the bytecode is platform independent.

public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello");
    }
}
Terminal

$ javac Hello.java
$ ls
Hello.class
Hello.java

What is bytecode in Java?

Bytecode is the low level, compact code that javac makes from your source code. It is saved in .class files, and it is not machine code. The JVM runs it, by interpreting it and by compiling the hot parts to machine code with the JIT compiler.

You can look at the bytecode with the javap tool:

public class Add {
    static int add(int a, int b) {
        return a + b;
    }
}
Terminal

$ javac Add.java
$ javap -c Add | sed -n '1,14p'
Compiled from "Add.java"
public class Add {
public Add();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return

static int add(int, int);
Code:
0: iload_0
1: iload_1
2: iadd
3: ireturn

The lines like iload_0 and iadd are bytecode instructions. See What is Java?.

What are the primitive data types in Java?

TypeSizeDefault valueRange or values
byte8 bit0-128 to 127
short16 bit0-32,768 to 32,767
int32 bit0about -2.1 billion to 2.1 billion
long64 bit0Lvery big whole numbers
float32 bit0.0fdecimal, about 7 digits
double64 bit0.0decimal, about 15 digits
char16 bit‘\u0000’one Unicode character
booleannot definedfalsetrue or false
public class Main {
    public static void main(String[] args) {
        System.out.println(Integer.MAX_VALUE);
        System.out.println(Long.MAX_VALUE);
        System.out.println((int) Character.MAX_VALUE);
    }
}
Output

2147483647
9223372036854775807
65535

Every other type is a reference type. See Java Data Types.

What is the difference between == and equals() in Java?

For primitives, == compares the values. For objects, == checks if both variables point to the same object. The equals() method checks if the content is the same (if the class overrides it, like String does).

public class Main {
    public static void main(String[] args) {
        String a = "java";
        String b = "java";
        String c = new String("java");

        System.out.println(a == b);        // same object in the string pool
        System.out.println(a == c);        // different objects
        System.out.println(a.equals(c));   // same text
        System.out.println(5 == 5);
    }
}
Output

true
false
true
true

See Java Strings.

Why is String immutable in Java?

Immutable means the object can not be changed after it is created. Methods like toUpperCase() give a new String. The reasons Java designed it this way:

  • String pool: equal literals share one object, which saves memory.
  • Security: strings are used for file names, URLs and passwords, and nobody can change them after the check.
  • Thread safety: many threads can share a string without any lock.
  • Hash code caching: a string keeps its hash code, so it is fast as a key in a HashMap.
public class Main {
    public static void main(String[] args) {
        String s = "java";
        s.concat(" 25");              // the result is lost
        System.out.println(s);
        s = s.concat(" 25");          // keep the new object
        System.out.println(s);
    }
}
Output

java
java 25

What is the difference between String, StringBuilder and StringBuffer?

PointStringStringBuilderStringBuffer
ChangeableNo (immutable)YesYes
Thread safeYes (immutable)NoYes (synchronized)
SpeedSlow for many joinsFastestSlower than StringBuilder
Use forFixed textBuilding text in a loopOld code with many threads
public class Main {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Java");
        sb.append(" is").append(" fun");
        System.out.println(sb);
        System.out.println(sb.reverse());
    }
}
Output

Java is fun
nuf si avaJ

Details: Java StringBuilder and Text Blocks.

What is a class and an object in Java?

A class is a blueprint which describes the data (fields) and the actions (methods). An object is a real thing made from the class with new. Many objects can be made from one class, each with its own data.

class Car {
    String model;
    int speed;

    void accelerate() {
        speed += 10;
    }
}

public class Main {
    public static void main(String[] args) {
        Car c1 = new Car();
        c1.model = "Swift";
        c1.accelerate();
        c1.accelerate();

        Car c2 = new Car();
        c2.model = "Creta";

        System.out.println(c1.model + " " + c1.speed);
        System.out.println(c2.model + " " + c2.speed);
    }
}
Output

Swift 20
Creta 0

See Java Classes and Objects.

What is a constructor in Java?

A constructor has the same name as the class and no return type. It runs automatically when you use new. If you do not write one, Java gives a default constructor with no parameters.

class Student {
    String name;
    int marks;

    Student(String name, int marks) {
        this.name = name;
        this.marks = marks;
    }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student("Riya", 88);
        System.out.println(s.name + " " + s.marks);
    }
}
Output

Riya 88

Types: default, parameterized and copy constructors. See Java Constructors.

What is the difference between a constructor and a method in Java?

PointConstructorMethod
NameSame as the classAny name
Return typeNone (not even void)Required (or void)
CalledAutomatically with newBy you, with the dot
PurposeSet up the objectDo a job
InheritedNoYes
Default oneJava gives it if you write noneNo

A constructor is not a method and is not inherited, but a subclass constructor calls the parent constructor with super().

What is the this keyword in Java?

this is a reference to the object whose method or constructor is running.

  • this.name = name; separates a field from a parameter of the same name.
  • this(...) calls another constructor of the same class.
  • return this; allows method chaining.
class Point {
    int x, y;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    Point move(int dx) {
        this.x += dx;
        return this;
    }
}

public class Main {
    public static void main(String[] args) {
        Point p = new Point(1, 2).move(5).move(10);
        System.out.println(p.x + "," + p.y);
    }
}
Output

16,2

See Java static and this.

What is the static keyword in Java?

A static member belongs to the class. You use it with the class name and no object is needed.

  • Static field: one copy shared by all the objects (like a counter).
  • Static method: can not use this or instance fields (main is static).
  • Static block: runs once when the class is loaded.
  • Static nested class: a class inside a class, without a link to the outer object.
class Counter {
    static int total = 0;
    Counter() { total++; }
}

public class Main {
    public static void main(String[] args) {
        new Counter();
        new Counter();
        System.out.println(Counter.total);
    }
}
Output

2

See Java static and this.

What is the final keyword in Java?

Used onMeaning
VariableThe value can be set only once (a constant)
MethodCan not be overridden in a subclass
ClassCan not be extended (for example String is final)
ParameterCan not be changed inside the method
public class Final {
    public static void main(String[] args) {
        final int max = 10;
        max = 20;
    }
}
Output

Final.java:4: error: cannot assign a value to final variable max
max = 20;
^
1 error
error: compilation failed

A final reference can not point to another object, but the object itself can still change. See also final, finally and finalize.

What are the four pillars of OOP in Java?

PillarMeaningIn Java
EncapsulationHide data, give controlled accessprivate fields with getters and setters
InheritanceA class gets the features of anotherextends
PolymorphismOne call, many behaviorsOverriding and overloading
AbstractionShow only what is needed, hide the detailsAbstract classes and interfaces

Read the chapters: Encapsulation, Inheritance, Polymorphism and Abstract Classes.

What is the difference between method overloading and overriding in Java?

PointOverloadingOverriding
WhereSame class (or subclass)Subclass and parent class
ParametersMust be differentMust be the same
Return typeCan be differentSame (or a subtype)
DecidedAt compile timeAt run time
Also calledCompile time polymorphismRun time polymorphism
class Animal {
    void sound() { System.out.println("..."); }
}

class Dog extends Animal {
    @Override
    void sound() { System.out.println("Woof"); }       // overriding
    void sound(int times) {                              // overloading
        for (int i = 0; i < times; i++) System.out.print("Woof ");
        System.out.println();
    }
}

public class Main {
    public static void main(String[] args) {
        Animal a = new Dog();
        a.sound();
        new Dog().sound(2);
    }
}
Output

Woof
Woof Woof

See Overloading and Inheritance.

Why does Java not support multiple inheritance of classes?

If a class could extend two classes with the same method, Java would not know which one to use. This is the diamond problem. So a class can extend only one class.

But a class can implement many interfaces. Since interfaces can have default methods now, a clash must be solved by the class:

interface A { default String hi() { return "A"; } }
interface B { default String hi() { return "B"; } }

class C implements A, B {
    public String hi() {
        return A.super.hi() + B.super.hi();      // you choose
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(new C().hi());
    }
}
Output

AB

See Java Interfaces.

What is the difference between an abstract class and an interface in Java?

PointAbstract classInterface
InheritanceA class extends only oneA class implements many
FieldsAny kind of fieldsOnly constants (public static final)
ConstructorsYesNo
MethodsAbstract and normalAbstract, default, static and private
Use whenRelated classes share code and stateDifferent classes share a behavior

A good rule: use an interface to say what something can do, and an abstract class to share code between closely related classes. See Abstract Classes and Interfaces.