Top

Java Programming

1.

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

Ans:

This is a fundamental concept in Java.

  • JVM (Java Virtual Machine): It's an abstract machine that provides a runtime environment in which Java bytecode can be executed. It's platform-dependent, meaning there are different JVMs for Windows, macOS, and Linux. Its job is to load, verify, and execute code.
  • JRE (Java Runtime Environment): It's the software package that contains what is required to run a Java program. It includes the JVM, along with core Java libraries (like rt.jar) and other supporting files. You would provide the JRE to a user who only needs to run your Java application, not develop it.
  • JDK (Java Development Kit): It's the full-featured software development kit for Java. It contains everything the JRE has, plus development tools such as the compiler (javac), debugger (jdb), and archiver (jar). You need the JDK to write and compile Java code.

In short, the hierarchy is: JDK > JRE > JVM.

2.

What are the main principles of Object-Oriented Programming (OOP)?

Ans:

The four main principles of OOP are:

  1. Encapsulation: The practice of bundling the data (attributes) and the methods (functions) that operate on the data into a single unit, known as a class. It also involves restricting direct access to some of an object's components, which is known as information hiding (e.g., using private access modifiers).
  2. Abstraction: The concept of hiding complex implementation details and showing only the essential features of the object. For example, when you drive a car, you only need to know how to use the steering wheel and pedals (the interface), not how the engine works internally. In Java, this is achieved using abstract classes and interfaces.
  3. Inheritance: A mechanism where a new class (subclass or child class) derives attributes and methods from an existing class (superclass or parent class). It promotes code reusability. Java uses the extends keyword for class inheritance.
  4. Polymorphism: The ability of an object to take on many forms. It allows us to perform a single action in different ways. In Java, polymorphism is primarily achieved through method overloading (compile-time polymorphism) and method overriding (runtime polymorphism).

3.

Why is Java considered 'Platform Independent'?

Ans:

Java's platform independence is one of its most famous features, summed up by the slogan 'Write Once, Run Anywhere' (WORA).

This is achieved through the use of Java bytecode and the Java Virtual Machine (JVM).

  1. When a developer writes Java code (a .java file), the Java compiler (javac) compiles it not into machine code for a specific processor, but into an intermediate format called bytecode (a .class file).
  2. This bytecode is platform-neutral. It is not specific to Windows, macOS, or Linux.
  3. To run the program, the target machine needs to have a JVM installed. The JVM acts as a translator. It takes the platform-neutral bytecode and interprets or compiles it into native machine code that the specific operating system and processor can understand and execute.

Since there are specific JVMs available for almost all platforms, the same bytecode can be run on any of them without modification, making Java platform-independent.

4.

What is the difference between `String`, `StringBuilder`, and `StringBuffer`?

Ans:

This is a classic Java interview question that tests understanding of immutability and performance.

FeatureStringStringBuilderStringBuffer
MutabilityImmutable. Once a String object is created, it cannot be changed. Any modification creates a new String object.Mutable. It can be modified after it is created without creating a new object.Mutable. Same as StringBuilder.
Thread SafetyThread-safe, due to its immutability.Not thread-safe. It does not provide any synchronization.Thread-safe. Its methods are synchronized.
PerformanceSlower for frequent modifications because it creates a new object for every change, leading to garbage collection overhead.Faster than StringBuffer because it is not synchronized. It is the preferred choice for single-threaded applications.Slower than StringBuilder due to the overhead of synchronization.
When to UseFor fixed string values that won't change, or in multi-threaded environments where sharing is required.In single-threaded environments where you need to perform many string modifications (e.g., building a long string in a loop).In multi-threaded environments where a mutable string needs to be safely shared among threads.

5.

Why are Strings immutable in Java?

Ans:

String immutability is a deliberate design choice in Java for several important reasons:

  • String Constant Pool: Java maintains a special memory area called the String Pool. When you create a String literal, the JVM checks if that string already exists in the pool. If it does, it returns a reference to the existing string instead of creating a new object. If Strings were mutable, one reference changing the string would affect all other references pointing to it, which would be disastrous.
  • Security: String parameters are widely used in network connections, database URLs, file paths, etc. If Strings were mutable, these values could be changed after a security check has been performed, potentially leading to security vulnerabilities.
  • Thread Safety: Because a String object cannot be changed, it is inherently thread-safe. It can be safely shared among multiple threads without any need for external synchronization.
  • Caching `hashCode()`: The `hashCode()` of a String is frequently used in collections like `HashMap` and `HashSet`. Because String is immutable, its hash code can be calculated once and cached, making it very fast for subsequent lookups. If it were mutable, the hash code would have to be recalculated every time.

6.

What is the difference between method overloading and method overriding?

Ans:

Both are forms of polymorphism in Java.

Method Overloading (Compile-time Polymorphism / Static Binding):

  • This occurs when two or more methods within the same class have the same name but different parameters (different number of arguments, different types of arguments, or both).
  • The compiler decides which method to call at compile time based on the method signature.
  • The return type can be different, but changing only the return type is not considered valid overloading.
class Calculator {
    int add(int a, int b) {
        return a + b;
    }

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

Method Overriding (Runtime Polymorphism / Dynamic Binding):

  • This occurs when a subclass (child class) has a method with the same name, same parameters, and same return type (or a covariant return type) as a method in its superclass (parent class).
  • The version of the method that gets executed is determined at runtime based on the type of the object.
  • It is used to provide a specific implementation of a method that is already provided by its superclass. The @Override annotation is used to indicate this.
class Animal {
    void makeSound() {
        System.out.println("Generic animal sound");
    }
}

class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Woof woof");
    }
}

7.

What is the difference between an `abstract class` and an `interface`?

Ans:

Both are used to achieve abstraction, but they have key differences.

FeatureAbstract ClassInterface
MethodsCan have both abstract (no body) and concrete (with body) methods.Before Java 8, could only have abstract methods. Since Java 8, can also have default and static methods with implementation.
VariablesCan have final, non-final, static, and non-static variables.Variables are implicitly public static final (constants).
InheritanceA class can extend only one abstract class (Java does not support multiple inheritance of classes).A class can implement multiple interfaces.
ConstructorCan have a constructor, which is called when an instance of a subclass is created.Cannot have a constructor.
Access ModifiersClass members can have public, protected, private, or default access.Methods are implicitly public.
When to UseUse when you want to provide a base class with some common implemented functionality and some methods that must be implemented by subclasses. Think 'is-a' relationship with shared code.Use when you want to define a contract of behavior that implementing classes must adhere to, without specifying any implementation. Think 'has-a' capability.

8.

Explain the `final` keyword in Java.

Ans:

The final keyword is a non-access modifier used to restrict a class, method, or variable.

  • final variable: When a variable is declared as final, its value cannot be changed once it has been assigned. It essentially becomes a constant. If a final variable is not initialized at the time of declaration, it is called a 'blank final variable' and must be initialized in the constructor.
  • final method: When a method is declared as final, it cannot be overridden by any subclass. This is used to prevent unexpected behavior from a subclass changing a core method's logic.
  • final class: When a class is declared as final, it cannot be extended (inherited) by any other class. For example, the String class in Java is a final class.

9.

Explain the `static` keyword in Java.

Ans:

The static keyword is used for memory management mainly. It indicates that the particular member belongs to the class itself, rather than to an instance of the class.

  • static variable (Class variable): There is only one copy of a static variable per class, regardless of how many instances of the class are created. It is shared among all instances. It is initialized when the class is loaded.
  • static method (Class method): A static method can be called without creating an instance of the class (e.g., ClassName.methodName()). It can only access static data members and can only call other static methods directly. It cannot use the this or super keywords. The main method is a common example.
  • static block: A block of code prefixed with the static keyword. It is executed only once, when the class is first loaded into memory by the JVM. It is used to initialize static variables.
  • static nested class: A nested class declared as static. It does not need an instance of the outer class to be instantiated.

10.

What is the difference between `==` and the `.equals()` method?

Ans:

  • The == operator is used for reference comparison (for non-primitive types). It checks if two object references point to the exact same object in memory. For primitive types (like int, char), it checks for value equality.
  • The .equals() method is used for content comparison. It is defined in the Object class, where it behaves exactly like the == operator. However, many classes (like String, Integer, etc.) override the .equals() method to provide a meaningful comparison of the object's actual contents rather than their memory location.

Example:

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

System.out.println(s1 == s2);
// false - they are two different objects in memory

System.out.println(s1.equals(s2));
// true - their content is the same

System.out.println(s1 == s3);
// true - both references point to the same object

It is a best practice to always override both .equals() and .hashCode() if you plan to use your custom objects in collections.

Loading…
Tags: Java Programming Interview Questions and Answers || Java Programming Sort Questions and Answers || Java Programming Detailed Questions and Answers || Java Programming Tutorial