Top 25 Java Interview Questions With Example Programs

Top 25 Java Interview Questions With Example Programs: Here are 25 common Java interview questions with example programs:

Java Interview Questions For Freshers: –

Example 1

import java.util.Scanner;

public class A{
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		 int sum=0; int count=0;
		while (count<6) {
			  int num = sc.nextInt();
			sum += num;
			count++;
		}
		int mean = sum/count;
		System.out.println("Mean:"+ mean);
	}
}
Output: 
232
234
543
345
765
567
Mean:447

Example 2

Top 25 Java Interview Questions

public class B {
public static void main(String[] args) {
	try {
	int x=10;;
	int y=0;
	int z=x/y;
	System.out.println(101);
	System.out.println(z);
	System.out.println(102);
	}
	catch(ArithmeticException e) 
	{
	e.printStackTrace();	
	}
	System.out.println(103);
}
}
Output: 
java.lang.ArithmeticException: / by zero
	at B.main(B.java:6)
103

1.What is the difference between an abstract class and an interface?

Example program:
public abstract class Animal {
    public abstract void makeSound();
}

public interface Mammal {
    public void giveBirth();
}

2. Can you override a private or static method in Java?

Example program:
public class Parent {
    private static void foo() {}
}

public class Child extends Parent {
    // Compilation error: cannot override a private or static method
    // @Override
    // private static void foo() {}
}

3. What is the difference between final, finally, and finalize in Java?

Example program:
public class Example {
    final int constant = 10;
    
    public void method() {
        try {
            // Code that might throw an exception
        } catch (Exception e) {
            // Handle the exception
        } finally {
            // Code that always runs, even if an exception is thrown
        }
    }
    
    @Override
    protected void finalize() throws Throwable {
        // Code that runs when the object is garbage collected
    }
}

4. What is the difference between an exception and an error in Java?

Example program:
public class Example {
    public void method() {
        try {
            // Code that might throw an exception
        } catch (Exception e) {
            // Handle the exception
        }
        
        // Code that might throw an error
        if (someCondition) {
            throw new Error("Something went wrong");
        }
    }
}

5. What is the difference between a stack and a queue in Java?

Example program:
import java.util.Stack;
import java.util.LinkedList;
import java.util.Queue;

public class Example {
    public static void main(String[] args) {
        Stack<String> stack = new Stack<>();
        stack.push("first");
        stack.push("second");
        stack.push("third");
        System.out.println(stack.pop()); // third
        
        Queue<String> queue = new LinkedList<>();
        queue.offer("first");
        queue.offer("second");
        queue.offer("third");
        System.out.println(queue.poll()); // first
    }
}

6. What is the difference between ArrayList and LinkedList in Java?

Example program:
import java.util.ArrayList;
import java.util.LinkedList;

public class Example {
    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("first");
        arrayList.add("second");
        arrayList.add("third");
        System.out.println(arrayList.get(1)); // second
        
        LinkedList<String> linkedList = new LinkedList<>();
        linkedList.add("first");
        linkedList.add("second");
        linkedList.add("third");
        System.out.println(linkedList.get(1)); // second
    }
}

7. What is the difference between a HashMap and a TreeMap in Java?

Example program:
import java.util.HashMap;
import java.util.TreeMap;

public class Example {
    public static void main(String[] args) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("key1", "value1");
        hashMap.put("key2", "value2");
        hashMap.put("key3", "value3");
        System.out.println(hashMap.get("key2")); // value2
        
        TreeMap<String, String> treeMap = new TreeMap<>();
        treeMap.put("key1", "value1");
        treeMap.put("key2", "value2");
        treeMap.put("key3", "value3");
        System.out.println(treeMap.get("key2")); // value2
    }
}

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

An interface is a collection of abstract methods that can be implemented by any class that implements the interface, while an abstract class is a class that cannot be instantiated and can contain both concrete and abstract methods. Example:

  • Interface:
public interface Shape {
    double getArea();
    double getPerimeter();
}

class Rectangle implements Shape {
    private double length;
    private double width;

    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    @Override
    public double getArea() {
        return length * width;
    }

    @Override
    public double getPerimeter() {
        return 2 * (length + width);
    }
}
  • Abstract class:
public abstract class Animal {
    public abstract void makeSound();

    public void sleep() {
        System.out.println("Zzz");
    }
}

class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Meow");
    }
}

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

The == operator compares the references of two objects, while the equals() method compares the values of two objects. Example:

String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");

System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
System.out.println(s1.equals(s3)); // true

10. What is a constructor in Java?

A constructor is a special method that is used to initialize objects of a class. It has the same name as the class and no return type. Example:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

Person p = new Person("John", 25);
System.out.println(p.getName()); // "John"
System.out.println(p.getAge()); // 25

11. What is the difference between public, private, and protected access modifiers in Java?

  1. Public variables and methods can be accessed from any class, private variables and methods can only be accessed within the same class, and protected variables and methods can be accessed within the same package or subclass. Example:
public class Person {
    public String name;
    private int age;
    protected String address;

    public Person(String name, int age, String address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    private void setAge(int age) {
        this.age = age;
    }
}

class Student extends Person {
    public Student(String name, int age, String address) {
        super(name, age, address);
    }

    public void printAddress() {
        System.out.println(address);
    }
}

Person p = new Person("John", 25, "123 Main St.");
System.out.println(p.name); // "John"
System.out.println(p.age); // Error: age is private
System.out.println(p.address); // Error: address is protected

Student s = new Student("Jane", 20, "456 Main St.");
System.out.println(s.name); // "Jane"
System.out.println(s.age); // Error: age is private
System.out.println(s.address); // "456 Main St."
s.printAddress(); // "456 Main St

12. What is Java?

Java is a high-level, object-oriented programming language that was developed by Sun Microsystems (now owned by Oracle Corporation) in the mid-1990s. It is widely used for developing a variety of applications, including web applications, desktop applications, mobile applications, and enterprise software.

13. What are the main features of Java?

Some of the key features of Java are:

  • Object-oriented programming (OOP)
  • Platform independence
  • Automatic memory management (garbage collection)
  • Exception handling
  • Multi-threading
  • Standard libraries and APIs

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

JDK stands for Java Development Kit, which is a software development kit used for developing Java applications. It includes a set of development tools such as the Java compiler, debugger, and documentation.

JRE stands for Java Runtime Environment, which is a software environment used to run Java applications. It includes the JVM and a set of libraries and APIs.

JVM stands for Java Virtual Machine, which is an abstract machine that provides the runtime environment for executing Java code.

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

In Java, both interfaces and abstract classes are used to define abstract types. An interface is a collection of abstract methods (methods without a body), constants, and default methods. An interface can be implemented by any class that provides an implementation for all its methods.

An abstract class is a class that cannot be instantiated but can be subclassed. It can contain abstract and non-abstract methods, as well as fields and constructors. An abstract method is a method without a body, which must be implemented by any subclass that extends the abstract class.

16. What is the difference between a class and an object in Java?

In Java, a class is a blueprint or template for creating objects. It defines the properties and behavior of the objects that can be created from it. An object is an instance of a class that has its own set of properties and can execute its own set of methods.

For example, the class Person might have properties such as name, age, and gender, as well as methods such as getAge() and setAge(). An object of the Person class might be instantiated with a specific name, age, and gender, and can then execute its own methods to perform specific tasks.

17. What is method overloading in Java?

Method overloading is a feature in Java that allows a class to have multiple methods with the same name but different parameters. When a method is called, Java uses the number and types of the arguments to determine which version of the method to invoke.

For example, the following code defines two methods with the same name (add) but different parameter lists:

public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public double add(double a, double b) {
        return a + b;
    }
}

In this example, the Calculator class has

Leave a Comment