Top-20 Java Interview Question

What is Variable ?

A Java variable is like a storage box in a computer program. It holds information that can change as the program runs. Imagine it as a labeled container where you can put different values, like numbers or words, and you can use these values later in your program. Variables help programs remember and manipulate data, making it easier to work with information in your code.

What is Class ?

In Java, a class is like a blueprint or a template for creating objects. An object is a real thing in your program, like a car or a person, and a class defines what that thing can do (its methods) and what information it stores (its attributes or fields). So, you use a class to create objects with specific characteristics and behaviors in your Java program. It helps organize and structure your code by grouping related functions and data together.

What is Package?

a Java package is like a folder that holds related things together in a computer program. These things, called classes, are like instructions for the program. By putting them in packages, we keep our instructions organized and make it easier for the program to find and use them. Think of a package as a labeled box that keeps similar sets of instructions neatly arranged.

What is String ?

a String in Java is a bunch of letters, numbers, or symbols all strung together. It’s like a line of text, such as words in a sentence. You can use Strings in your Java program to work with and manipulate text. Think of it as a way for the computer to understand and play around with words and sentences in your code.

What is String Buffer?

a StringBuffer in Java is like a special tool for handling and changing pieces of text, known as strings. It’s a bit like a workspace where you can easily add, remove, or modify words in a sentence. The cool thing about StringBuffer is that it’s designed to be good at making lots of changes to text without creating a whole bunch of new copies. So, when you need to do a lot of editing with words in your Java program, StringBuffer is there to help keep things efficient and smooth.

What is String Builder?

a StringBuilder in Java is a special tool that helps us work with and modify text (strings) more efficiently. It’s like a smart notepad where you can easily add, remove, or change words in a sentence without creating a bunch of new sentences. It’s useful when you need to edit text frequently in your Java program.

What is Array in Java?

In Java, an array is like a container that holds multiple values of the same type under one name. It’s like having a row of boxes where each box can store a piece of information, such as numbers, words, or other data types. Arrays make it convenient to work with collections of data, allowing you to access elements using an index (position). The index starts from 0, so the first element is at index 0, the second at index 1, and so on. Arrays help in organizing and managing data in a structured way, making it easier to handle large sets of information in a program.

What is Array List?

an ArrayList in Java is like a magical bag that can hold a bunch of things. The cool part? You can keep adding more stuff, and the bag will automatically adjust its size. So, it’s like having a bag that can change its size to fit all the items you want to carry. You can easily put things in, take them out, and even check what’s inside whenever you need. It’s a handy tool for managing lists of items in your Java programs without worrying too much about how much space you’ll need upfront.

What are those Primitive Data type?

In Java, primitive data types are basic building blocks for storing simple values. Here are the main primitive data types:

  1. int: Used for storing whole numbers (integer values), like 5 or -10.
  2. double: Used for storing decimal numbers (floating-point values), like 3.14 or -0.5.
  3. boolean: Used for storing true or false values.
  4. char: Used for storing a single character, like ‘A’ or ‘$’.
  5. byte: Used for storing small integers, typically used in file handling.
  6. short: Similar to int, but used for smaller integers.
  7. long: Used for storing large integer values, with a greater range than int.
  8. float: Used for storing decimal numbers (floating-point values), similar to double but with less precision.

These primitive data types are the basic elements for storing different kinds of values in Java programs.

Access Modifier:

An access modifier in Java is like a set of rules that determines how other parts of a program can interact with a particular class, method, or variable. It controls the visibility and accessibility of these elements. There are four main access modifiers in Java:

  1. Public: This is the least restrictive access level. Public elements can be accessed from any other class or package.
  2. Private: This is the most restrictive access level. Private elements can only be accessed within the same class. They are hidden from other classes.
  3. Protected: Protected elements can be accessed within the same class, as well as by subclasses and other classes in the same package.
  4. Default (Package-Private): If no access modifier is specified, it defaults to package-private. Elements with package-private access can be accessed only within the same package.

Access modifiers help in encapsulation, which is a key concept in object-oriented programming. They control how the internal details of a class are exposed to the outside world, providing a way to balance the need for flexibility and security in a program.


Final: In Java, final is like a rule you can set on things. When used with a variable, it means the value can’t change. If you mark a method as final, it can’t be changed by other parts of the program. When applied to a class, it says, “No one can make a new version of this class.”

Finally: In exception situations, finally is a safety net. It’s a block of code that will run no matter what, whether there’s an issue or not. It’s like saying, “I’ll clean up or finish this task, no matter what happens.”

Finalize: Finalize is like a special farewell party for objects in Java. When an object is no longer needed and is about to be removed from the program, the finalize method gets called. It’s the last chance for the object to tidy up or do any necessary chores before saying goodbye. However, it’s not the main way to clean up resources in modern Java; there are better methods like try-with-resources.

How to Handle Exception in Java?

Handling exceptions in Java is like having a backup plan for unexpected problems in your code. You use a try block for the risky code, and if something goes wrong, a catch block kicks in to manage the issue. This way, your program can handle surprises without crashing.

try {
    // Risky code that might cause an exception goes here
    int result = 10 / 0; // This could cause an ArithmeticException
} catch (ArithmeticException e) {
    // Code to handle the exception goes here
    System.out.println("Oops! Something went wrong. We're fixing it!");

In this example, the try block contains code that might cause an ArithmeticException (dividing by zero, which is not allowed). If that happens, the program jumps to the catch block, where you handle the exception by printing a message. This way, your program doesn’t crash, and you can gracefully manage unexpected issues.

What is HashSet?

a HashSet in Java is like a special container for holding things, but it only keeps unique items. Imagine having a box for your favorite fruits. You can put apples, bananas, and oranges in it, but if you try to add another apple, it won’t let you because it’s smart enough to only keep one of each kind. It’s useful when you want a collection of items without any duplicates.

import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        // Creating a HashSet
        HashSet<String> fruitSet = new HashSet<>();

        // Adding elements to the HashSet

        // Adding a duplicate element (it won't be added)

        // Displaying the elements in the HashSet
        System.out.println("Fruits in the HashSet: " + fruitSet);
What is Link List?

a LinkedList in Java is like a chain of connected elements, where each element knows about the next one. Imagine a necklace where each bead is linked to the one next to it.

Suppose you want to make a list of your favorite fruits using a LinkedList:

import java.util.LinkedList;

public class LinkedListExample {
    public static void main(String[] args) {
        // Creating a LinkedList to store fruits
        LinkedList<String> fruitList = new LinkedList<>();

        // Adding elements to the LinkedList

        // Displaying the elements in the LinkedList
        System.out.println("Fruits in the LinkedList: " + fruitList);
What is HashTable?

A Hashtable in Java is like a smart organizer that links things together. Imagine you have a special notebook where you jot down student IDs (the keys) next to their names (the values). This way, when you want to find a student’s name, you just check the ID in your notebook. It’s handy because it’s quick and organized. Here’s a simple code example:

import java.util.Hashtable;

public class HashtableExample {
    public static void main(String[] args) {
        // Creating a smart notebook (Hashtable) for student IDs and names
        Hashtable<Integer, String> studentNotebook = new Hashtable<>();

        // Adding entries to the smart notebook
        studentNotebook.put(101, "John");
        studentNotebook.put(102, "Jane");
        studentNotebook.put(103, "Doe");

        // Finding a student's name based on their ID
        String studentName = studentNotebook.get(102);
        System.out.println("Student with ID 102: " + studentName);

        // Checking if a certain ID is in the notebook
        boolean containsID = studentNotebook.containsKey(104);
        System.out.println("Does the notebook have ID 104? " + containsID);

In this example, the Hashtable is like your smart notebook, helping you quickly find and organize student information using their IDs.

What is Encapsulation ?

In Java, encapsulation is a way of organizing code by bundling data (variables) and the methods (functions) that operate on the data into a single unit known as a class. The key idea is to keep the internal details of the class hidden from the outside and provide controlled access through methods. Encapsulation involves marking variables as private, meaning they can only be directly accessed within the same class. Access to these variables is then regulated by public methods, allowing for better control and maintenance of the code. This concept not only enhances security by preventing direct access to sensitive data but also promotes a modular and organized code structure.

What is Abstraction?

Abstraction in Java is like using a TV remote. You don’t need to know how each button works inside; you just press the buttons for volume, channels, or power, and the TV does its thing. Similarly, in programming, abstraction means focusing on what something does without worrying about the intricate details of how it works. It’s like hiding the complexity and using simple commands to interact with objects, making it easier to understand and use code.

What is Polymorphism ?

Polymorphism in Java is like having a superhero with different abilities depending on the situation. Imagine a superhero named “ShapeChanger” who can transform into various forms. Similarly, in programming, polymorphism lets you use a single method or name to perform different tasks. It’s like having one function that can do different things based on the context, making your code more adaptable and versatile.

What is Inheritance?

inheritance in Java is like passing down skills and traits from parents to children. If a parent knows how to ride a bike, the child can learn that too. Similarly, in programming, a new class can inherit, or learn from, an existing class. The new class gets the abilities of the old one and can add its own special skills. It’s a way to organize and reuse code, making it more efficient and easier to understand.

What is Constructor?

In Java, a constructor is like a special method that builds or constructs an object when it is created. It’s like a set of instructions for how to create something new. Imagine you’re making a robot, and the constructor is the guide on how to assemble it with all its parts. In code, a constructor is defined within a class and has the same name as the class itself.


public class Robot {
    // Properties or variables of the Robot class
    String name;
    int batteryLevel;

    // Constructor for the Robot class
    public Robot(String robotName, int initialBattery) {
        // Instructions for constructing a Robot
        name = robotName;
        batteryLevel = initialBattery;
        System.out.println("A new robot named " + name + " is created!");

    // Other methods (functions) of the Robot class can go here

public class Main {
    public static void main(String[] args) {
        // Creating a new Robot object using the constructor
        Robot myRobot = new Robot("RoboFriend", 100);

        // Now, myRobot has a name "RoboFriend" and a battery level of 100

In this example, the Robot class has a constructor that takes a name and an initial battery level as parameters. When you create a new Robot using new Robot("RoboFriend", 100), it follows the instructions in the constructor and sets the robot’s name to “RoboFriend” and its battery level to 100.