Essential Java Programming Concepts and Frameworks

Java Fundamentals: JDK, JRE, and JVM

(a) Differentiate between JDK, JRE, and JVM.

  • JVM (Java Virtual Machine): An abstract machine that runs Java bytecode. It converts .class files into machine code and is platform-dependent.
  • JRE (Java Runtime Environment): Provides the environment to run Java programs. It contains the JVM, libraries, and supporting files, but does not include development tools.
  • JDK (Java Development Kit): Used to develop Java programs. It contains the JRE plus development tools (compiler javac, debugger, jar, etc.).
  • Relationship: JDK ⊃ JRE ⊃ JVM

Understanding the Main Method

(b) Explain public static void main(String args[]) in Java.

  • public: Access modifier; allows the JVM to call main from outside the class.
  • static: The main method can be called without creating an object of the class.
  • void: The main method does not return any value.
  • main: The name of the method; the JVM searches for this exact name as the program’s entry point.
  • String args[]: An array of String to hold command-line arguments.

Equality in Java: == vs .equals()

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

  • ==: Compares references (memory addresses) for objects; for primitives, it compares values.
  • .equals(): Compares the actual content/value of the objects. It is defined in the Object class and overridden in classes like String and Integer.
String a = new String("hi");
String b = new String("hi");
a == b // false (different references)
a.equals(b) // true (same content)

Data Encapsulation

(d) What is data encapsulation? Why is it important?

  • Definition: Wrapping data (variables) and methods together inside a single unit (class).
  • Implementation: Achieved by declaring variables as private and providing public getter/setter methods.
  • Importance: Data hiding protects data from outside misuse, promotes modular and maintainable code, and enables controlled access through validation in setters.

Checked vs Unchecked Exceptions

(e) Differentiate between checked and unchecked exceptions.

  • Checked Exceptions: Checked at compile time. Must be handled using try-catch or declared with throws. Examples: IOException, SQLException.
  • Unchecked Exceptions: Occur at runtime; the compiler does not force handling. These are subclasses of RuntimeException. Examples: ArithmeticException, NullPointerException.

Java List and forEach

(f) Write a Java program to create a List with numbers 1 to 5 and print them using forEach.

import java.util.*;
public class Demo {
    public static void main(String[] args) {
        List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5);
        nums.forEach(n -> System.out.println(n));
    }
}

Local Variable Type Inference

(g) What is local variable type inference (var) in Java?

  • Introduced in Java 10, it allows declaring a local variable without explicitly specifying its type.
  • The compiler infers the type from the initializer expression.
  • Works only for local variables, not for fields, method parameters, or return types.
var name = "Hello"; // inferred as String
var list = new ArrayList<>(); // inferred as ArrayList

Inheritance in Java

(a) Explain inheritance in Java and demonstrate multilevel inheritance.

Inheritance is an OOP feature where a subclass acquires the properties and behavior of a parent class using the extends keyword. It promotes code reusability.

  • Types: Single, Multilevel, Hierarchical (Supported); Multiple, Hybrid (Supported via interfaces only).
class Animal { void eat() { System.out.println("Animal eats"); } }
class Dog extends Animal { void bark() { System.out.println("Dog barks"); } }
class Puppy extends Dog { void weep() { System.out.println("Puppy weeps"); } }

Abstract Class vs Interface

(b) Differentiate between abstract class and interface.

  • Abstract Class: Declared with abstract; can have abstract and concrete methods, instance variables, and constructors. A class can extend only one.
  • Interface: Declared with interface; all methods are abstract by default (Java 7+). Variables are public static final. A class can implement multiple interfaces.

Thread Life Cycle

(a) Explain the life cycle of a thread in Java.

  • New: Thread object created but start() not called.
  • Runnable: start() called; ready but waiting for CPU.
  • Running: Thread scheduler picks the thread; run() executes.
  • Waiting/Blocked: Alive but temporarily ineligible to run (e.g., sleep(), wait()).
  • Terminated: run() completes; cannot be restarted.

ArrayList vs LinkedList

(a) Compare ArrayList and LinkedList.

  • ArrayList: Dynamic array; O(1) random access; O(n) insertion/deletion. Best for read-heavy operations.
  • LinkedList: Doubly linked list; O(n) random access; O(1) insertion/deletion. Best for frequent modifications.

Spring Framework Overview

(a) Explain the Spring framework, its advantages, and modules.

Spring is a lightweight, open-source Java framework for enterprise applications, promoting loose coupling via Dependency Injection (DI) and Aspect-Oriented Programming (AOP).

  • Advantages: Lightweight, easy testing, modular, and powerful abstractions.
  • Modules: Spring Core, AOP, JDBC, ORM, Web MVC, Boot, and Security.

Polymorphism in Java

(a) Illustrate polymorphism: Compile-time vs Run-time.

  • Compile-time (Overloading): Multiple methods with the same name but different parameters in the same class.
  • Run-time (Overriding): Subclass provides a specific implementation of a method defined in the parent class.

Constructors in Java

(a) Illustrate constructors and their types.

  • Default: No parameters; provided automatically if none defined.
  • Parameterized: Accepts arguments to initialize objects.
  • Copy: Creates an object by copying another.

Exception Handling

(a) Explain exception handling keywords.

  • try: Encloses code that may throw an exception.
  • catch: Handles the exception.
  • finally: Always executes; used for cleanup.
  • throw: Explicitly throws an exception.
  • throws: Declares exceptions in method signatures.

Streams and IO

(a) Differentiate Character Streams vs Byte Streams and wait() vs notify().

  • Byte Streams: Handle 8-bit data (binary files).
  • Character Streams: Handle 16-bit Unicode data (text files).
  • wait(): Releases lock and waits.
  • notify(): Wakes up a waiting thread.

Java Stream API

(a) Describe Java Stream API operations.

  • Intermediate: Lazy operations like filter(), map(), sorted().
  • Terminal: Trigger execution, e.g., forEach(), collect(), sum().

Switch Statements

(b) Compare switch-case statement with switch-expression.

  • switch-case: Traditional statement; requires break; cannot return values.
  • switch-expression: Java 14+; returns values; uses ->; no break needed.

HashMap

(a) Describe HashMap and its methods.

  • Stores unique keys and duplicate values.
  • Allows one null key and multiple null values.
  • Methods: put(), get(), remove(), containsKey(), size().

Comparable vs Comparator

(b) Differentiate between Comparable and Comparator.

  • Comparable: Natural ordering; compareTo(); inside the class.
  • Comparator: Custom ordering; compare(); external class or lambda.

Spring Boot and REST

(b) Describe Spring Boot and RESTful APIs.

  • Spring Boot: Simplifies development with auto-configuration, embedded servers, and starter dependencies.
  • REST API: Uses HTTP methods (GET, POST, PUT, DELETE) for CRUD operations.