LogIn
I don't have account.

Java Interview Questions and Answers Set 1

Code Crafter
170 Views

Discover the most commonly asked Java interview questions and their expert answers. This guide covers core Java concepts, OOP principles, and practical examples to help you crack interviews with confidence. Ideal for freshers and experienced developers preparing for Java developer roles in top tech companies.

What do you know about Java?

Java is a high-level programming language that was originally developed by Sun Microsystems and released in 1995. It is platform-independent and can run on various operating systems, including Windows, macOS and different versions of UNIX.

What is the difference between JDK, JRE and JVM?

  • JVM (Java Virtual Machine): It is an abstract machine that executes Java bytecode. It provides platform independence by converting bytecode into machine-specific code at runtime.
  • JRE (Java Runtime Environment): It includes the JVM and necessary libraries to run Java applications. It does not contain development tools
  • JDK (Java Development Kit): It is a complete package for Java development, including the JRE, compiler (javac), debugger and other development tools.

Is Java platform-independent? If yes, then why?

Yes, Java is platform-independent because of the Java Virtual Machine (JVM). When Java code is compiled, it is converted into bytecode, which is not specific to any platform. This bytecode can be executed on any device that has a compatible JVM, making Java programs run consistently across different operating systems.

What are the four main OOP principles in Java?

The four main Object-Oriented Programming (OOP) principles in Java are:

  1. Encapsulation – Bundling data and methods that operate on the data within a single unit (class) and restricting access using access modifiers.
  2. Inheritance – Allowing one class to inherit fields and methods from another class, promoting code reusability.
  3. Polymorphism – Allowing one interface to be used for different underlying data types, enabling method overloading and overriding.
  4. Abstraction – Hiding complex implementation details and showing only the necessary features to the user.

List any five features of Java?

  1. Platform Independence – Java programs can run on any device with a JVM, making them platform-independent.
  2. Object-Oriented – Java follows the OOP principles, promoting modular and reusable code.
  3. Multithreading – Java supports multithreading, allowing multiple tasks to run concurrently.
  4. Automatic Garbage Collection – Java automatically manages memory by cleaning up unused objects, freeing up resources.
  5. Security – Java provides a robust security model, including bytecode verification and a security manager, to prevent unauthorized access.

Why is Java Architectural Neutral?

Java is considered architectural neutral because its bytecode, generated by the Java compiler, can be executed on any platform with a compatible Java Virtual Machine (JVM). This ensures that Java programs can run on different hardware and operating systems without modification, making Java platform-independent and able to work across various architectures.

How Java enabled High Performance?

Java achieves high performance through several mechanisms:

  • Bytecode Compilation: Java code is compiled into bytecode, which is optimized for faster execution on the JVM.
  • Just-In-Time (JIT) Compiler: The JIT compiler compiles bytecode into native machine code at runtime, improving execution speed.
  • Efficient Garbage Collection: Java's automatic garbage collection helps manage memory efficiently, reducing memory leaks and fragmentation.
  • Multi-threading Support: Java's built-in multi-threading capabilities allow parallel execution of tasks, enhancing performance in concurrent applications.

Why is Java considered dynamic?

Java is considered dynamic because it supports runtime flexibility and adaptability in several ways:

  • Cross-Platform Execution: Java’s architecture-neutral design (via JVM) enables applications to run on any platform, making it adaptable to changing environments.
  • Automatic Garbage Collection: Java dynamically manages memory and performs garbage collection to ensure optimal memory usage without requiring explicit memory management.
  • Dynamic Class Loading: Java can load classes dynamically using class loaders. Classes can be loaded at runtime, which allows for more flexible and modular designs, such as those found in plug-in architectures.
  • Reflection : Java's Reflection API enables programs to examine and alter the runtime behavior of applications. This dynamic capability to inspect classes, methods, and fields during runtime is a key feature of Java's dynamic nature..

What is Java Virtual Machine (JVM), and how is it related to Java's platform-independent feature?

The Java Virtual Machine (JVM) is an abstract computing machine that enables a computer to run Java programs. It is a part of the Java Runtime Environment (JRE) that executes Java bytecode. When a Java program is compiled, it is not converted into platform-specific machine code. Instead, it is compiled into an intermediate form called bytecode, which is platform-independent.

This bytecode can be distributed across any system or over the web. The JVM on each platform (Windows, Linux, macOS etc.) interprets or compiles this bytecode into native machine code specific to that platform at runtime.

Because every platform has its own JVM implementation that understands the same bytecode, Java achieves platform independence.

List two Java IDE's?

Two popular Java IDEs are Eclipse and IntelliJ IDEA.

What do you mean by Object in Java?

In Java, an object is an instance of a class. It is a real-world entity that contains both state (data/fields) and behavior (methods/functions). Objects are created using the new keyword and are the foundation of object-oriented programming.

For example, a Car object may have properties like color and speed, and behaviors like drive() or brake().

Define class in Java.

In Java, a class is a blueprint or template for creating objects. It defines the attributes (fields/variables) and behaviors (methods) that the objects created from it will have. A class does not occupy memory until an object is created from it using the new keyword.

class Car {
    String color;
    void drive() {
        System.out.println("The car is driving.");
    }
}

Here, Car is a class. When you create an object from it, like Car myCar = new Car(); you're creating an actual entity based on the blueprint.

What kind of variables can a class consist of in Java?

A class in Java can consist of the following types of variables

  • Instance Variables – Defined without the static keyword, these belong to each instance (object) of the class.
  • Class Variables (Static Variables) – Declared using the static keyword, these belong to the class itself rather than any object.
  • Local Variables – Declared inside methods or blocks and accessible only within them.
  • Parameters – Variables passed to methods or constructors as input.

What is Singleton class?

A Singleton class in Java is a class that allows only one instance of itself to be created. It provides a global point of access to that instance, ensuring that there is only a single object of the class throughout the application's lifecycle. This is typically used for managing shared resources, like database connections.

To implement a Singleton class, the constructor is made private, and a static method is provided to get the instance.

class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

When should we use a Singleton class?

1. Resource Management If your application requires a single instance to manage a resource, such as a database connection, configuration settings or logging, the Singleton pattern ensures that multiple instances don’t waste resources or create conflicts.

2. Global Access Point : When you need a global access point to an object but want to ensure that the object is instantiated only once, the Singleton class offers a controlled way to manage this instance.

3. Consistency Across the Application :A Singleton is useful when the system needs consistent behavior or values shared by all classes that use the Singleton instance. Since there's only one instance, you ensure the same values are accessed consistently.

Why should we use a Singleton Class?

1. Memory Efficiency:The Singleton pattern reduces memory usage by allowing only one instance of the class to exist throughout the lifecycle of the application, avoiding the overhead of creating multiple objects of the same class.

2. Control Over Instance Creation :By controlling the instance creation via a private constructor, the Singleton pattern ensures that objects can’t be directly instantiated elsewhere, offering more precise control over how and when the instance is created.

3. Thread-Safety (with precautions) :In a multithreaded environment, ensuring only one instance is created is critical. With appropriate thread-safe techniques (like using synchronized or volatile), you can prevent race conditions when the Singleton instance is accessed simultaneously by multiple threads.

What do you mean by Constructor in Java?

A constructor in Java is a special type of method used to initialize objects when they are created. It has the same name as the class and does not have a return type. Constructors are called automatically when an object of a class is instantiated using the new keyword. They can be default constructors (no parameters) or parameterized constructors (with parameters to initialize the object's state).

List the three steps for creating an Object for a class?

  1. Declare: Declare a reference variable of the class type.
  2. Instantiate: Use the new keyword to create an object.
  3. Initialize: Initialize the object using a constructor or set values for its fields.

What is the default value of byte datatype in Java?

The default value of the byte datatype in Java is 0.

What is the default value of float and double datatype in Java?

The default value of float is 0.0f and the default value of double is 0.0 in Java.

When a byte datatype is used?

The byte datatype in Java is used when you need to store small integer values, specifically in the range of -128 to 127, and when memory efficiency is a concern, as it consumes only 1 byte of memory. It is often used in situations like file I/O, network communication or handling raw binary data.

What is a static variable?

A static variable in Java is a class-level variable declared with the static keyword, outside methods, constructors or blocks. It is shared by all instances of the class, meaning all objects refer to the same variable.

What do you mean by Access Modifier?

An access modifier in Java is a keyword used to set the visibility or accessibility of classes, variables, methods, and constructors. It defines who can access these members within and outside the class. Java provides four types of access modifiers:

  1. public – The class, method or variable is accessible from any other class.
  2. private – The class, method or variable is accessible only within the same class.
  3. protected – The class, method or variable is accessible within the same package or by subclasses.
  4. Default (no modifier) – If no access modifier is specified, the class, method or variable is accessible only within the same package.

What is protected access modifier?

The protected access modifier in Java allows variables, methods, and constructors to be accessed within the same package and by subclasses in other packages. This means protected members are visible to all classes in the same package and to subclasses regardless of their package, providing a balance between package-level and public access.

1. Access from a Class in the Same Package

// File: animals/Animal.java
package animals;

public class Animal {
    protected void makeSound() {
        System.out.println("Animal makes a sound");
    }
}
// File: animals/Zoo.java
package animals;

public class Zoo {
    public void showAnimalSound() {
        Animal animal = new Animal();
        animal.makeSound();  // Allowed: same package access
    }
}
2. Access from Subclass in a Different Package java
// File: animals/Animal.java
package animals;

public class Animal {
    protected void makeSound() {
        System.out.println("Animal makes a sound");
    }
}
// File: pets/Dog.java
package pets;

import animals.Animal;

public class Dog extends Animal {
    public void bark() {
        makeSound();  // Accessing protected method from superclass
        System.out.println("Dog barks");
    }
}

What do you mean by synchronized non-access modifier in Java?

The **synchronized** non-access modifier in Java is used to control thread access to methods or blocks. When a method or block is declared synchronized, only one thread can execute it at a time for a given object. This prevents race conditions and ensures thread safety in multi-threaded applications. It's commonly used in scenarios involving shared resources or data.

  • It can be applied to methods or code blocks, not classes or variables.
  • It locks the object (or class, if static) so no other thread can access the synchronized part until the lock is released.
public class Counter {
    private int count = 0;
    public synchronized void increment() {
        count++;
    }
    public int getCount() {
        return count;
    }
}

In the above example, the increment() method is synchronized, so only one thread can execute it at a time, preventing inconsistent updates to count.

According to Java Operator precedence, which operator is considered to be with highest precedence?

In Java, the postfix operators (), [] and . have the highest precedence.

Which data types can be used with variables in a switch statement?

In Java, the variable used in a switch statement (known as the switch expression) must be of a compatible type. Valid data types include the primitive types byte, short, char and int, as well as their corresponding wrapper classes Byte, Short, Character and Integer. Starting from Java 5, enum types are also supported in switch statements, providing a type-safe way to handle fixed sets of constants. From Java 7 onward, String values can also be used in switch expressions, allowing developers to write more readable and expressive code. Other data types like float, double, long or objects not listed above are not allowed in switch statements.

When parseInt() method can be used?

The parseInt() method in Java is used to convert a String representing a number into its corresponding integer value (int). It is a static method of the Integer class. This method can be used when you have a string that represents a valid integer and you need to perform numeric operations with it. If the string cannot be parsed as an integer (e.g. it contains non-numeric characters), the method throws a NumberFormatException.

String number = "123";
int result = Integer.parseInt(number);  // Converts the string to an integer
System.out.println(result);  // Outputs 123

Why is String class considered immutable?

The String class in Java is considered immutable because once a String object is created, its value cannot be changed. Any modification to a String creates a new object. This immutability makes Strings thread-safe, as they can be shared across multiple threads without risk of data inconsistency, which is crucial in multithreaded programming.

Why is StringBuffer called mutable?

The StringBuffer class in Java is called mutable because its contents can be modified after creation. Unlike the String class (which is immutable), StringBuffer allows for efficient manipulation of characters, such as appending, deleting, or modifying characters without creating new objects. It's ideal for scenarios requiring frequent modifications to string data.

What is the difference between StringBuffer and StringBuilder class?

StringBuffer and StringBuilder are both used to create mutable strings in Java, but there are key differences between them:

1. Thread Safety :
  • StringBuffer is synchronized, meaning it is thread-safe and can be used in multi-threaded environments without worrying about concurrency issues.
  • StringBuilder is not synchronized, making it faster than StringBuffer in single-threaded scenarios, but not suitable for multi-threaded applications where thread safety is required.
2. Performance :
  • StringBuilder is generally faster than StringBuffer because it doesn't have the overhead of synchronization. It is ideal for single-threaded applications.
  • StringBuffer has slightly slower performance due to its synchronized methods.

Conclusion, use StringBuilder whenever possible because it is faster than StringBuffer. But, if thread safety is necessary then use StringBuffer objects.

Which package is used for pattern matching with regular expressions?

java.util.regex package is used for pattern matching with regular expressions.

What is finalize() method?

The finalize() method in Java is called by the garbage collector just before an object is removed from memory. It allows the object to perform cleanup operations, such as releasing resources.