Top Java Interview Questions & Answers (2026)

πŸ“˜ Beginner 36 Questions 🎯 Fresher Friendly πŸ•’ Updated Mar 2026

  • Arithmetic β†’ + - * / % (basic math)

  • Unary β†’ ++ -- + - ! (increment, decrement, negate, NOT)

  • Assignment β†’ = += -= *= /= %= (assign values)

  • Relational β†’ == != > < >= <= (comparisons β†’ true/false)

  • Logical β†’ && || ! (AND, OR, NOT for conditions)

  • Bitwise β†’ & | ^ ~ << >> >>> (operations on bits)

  • Conditional (Ternary) β†’ ? : (shorthand if-else)

  • Type Cast β†’ (type) (convert data type)

  • instanceof β†’ check object type

  • new β†’ create objects

  • πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects, which combine data (fields/attributes) and methods (functions/behaviors) into a single unit.

    Advantages of OOP:

    1. Reusability – Code can be reused using inheritance.

    2. Modularity – Programs are divided into objects, making them easier to manage.

    3. Flexibility & Maintainability – Easy to update or modify without affecting the whole system.

    4. Security – Data hiding using encapsulation.

    5. Real-world modeling – Programs are designed closer to real-life entities.


    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

  • Java is called platform independent because Java programs are compiled into bytecode (not machine-specific code).

  • This bytecode runs on the Java Virtual Machine (JVM), which is available on different operating systems (Windows, Linux, Mac, etc.).

  • So, the same Java program can run anywhere without modification β€” β€œWrite Once, Run Anywhere (WORA)”.


  • πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    A class is a blueprint or template in Java that defines the structure and behavior of objects.

    • It contains fields (data/variables) and methods (functions/behaviors).

    • But a class itself does not occupy memory until an object is created.

    Example:

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

    Difference between Class and Object

    ClassObject
    Blueprint or templateInstance of a class
    Defines properties & methodsRepresents real entity with actual values
    Does not occupy memory (only definition)Occupies memory when created
    Example: Car (general idea)Example: Car myCar = new Car();

    In short:

    • Class = Design / Blueprint

    • Object = Real thing created from that blueprint


    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    Need of private Access Specifier in Java

    • private is the most restrictive access specifier in Java.

    • When a variable, method, or constructor is declared private, it can be accessed only within the same class.

    • It is used for data hiding (a key principle of encapsulation in OOP).

    • Helps in security and prevents unauthorized access to sensitive data.


    Example Program: Using private

    class BankAccount { // private data - cannot be accessed directly outside class private double balance; // constructor BankAccount(double amount) { balance = amount; } // public method to access private data safely public double getBalance() { return balance; } public void deposit(double amount) { if(amount > 0) { balance += amount; } } } public class Main { public static void main(String[] args) { BankAccount acc = new BankAccount(1000); // System.out.println(acc.balance); ❌ ERROR (balance is private) acc.deposit(500); // modify through public method System.out.println("Current Balance: " + acc.getBalance()); // βœ… Safe access } }

    Explanation of Example

    • balance is private, so it cannot be accessed directly from outside the class.

    • Access is only through public methods (getBalance(), deposit()), ensuring security and control.


    In short:

    The private specifier is needed for data hiding and encapsulation, allowing safe and controlled access to class members.


    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    Abstract Class in Java

    • An abstract class is a class that cannot be instantiated (you cannot create objects of it).

    • It is used to provide a common base for other classes.

    • An abstract class can have:

      • Concrete methods (with body)

      • Abstract methods (without body)

    Use:

    • To define a common template for subclasses.

    • Allows partial implementation which must be completed by subclasses.


    Abstract Method

    • An abstract method is a method without a body (no implementation).

    • It is declared using the keyword abstract and must be overridden by a subclass.

    Syntax:

    abstract void methodName();


    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    String Class in Java

    • The String class in Java represents a sequence of characters.

    • Strings are objects in Java, not primitive types.

    • Strings are immutable, meaning once created, their values cannot be changed.

    • Declared as:

    String s = "Hello";

    Four Useful Methods of String Class

    MethodDescriptionExample
    length()Returns the number of characters in the string"Hello".length() β†’ 5
    charAt(int index)Returns character at specified index (0-based)"Hello".charAt(1) β†’ 'e'
    substring(int start, int end)Returns a part of string from start index to end-1"Hello".substring(1,4) β†’ "ell"
    equals(String s)Compares two strings for content equality"Hello".equals("hello") β†’ false


    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    What is Inheritance?

    • Inheritance is an OOP concept where one class (subclass/child class) acquires the properties and methods of another class (superclass/parent class).

    • It allows code reuse and establishes a hierarchical relationship between classes.

    Syntax in Java:

    class Parent { // parent class members } class Child extends Parent { // child class inherits Parent's members }

    Advantages of Inheritance

    1. Code Reusability – Reuse existing code without rewriting.

    2. Method Overriding – Allows child class to provide specific implementation for parent’s methods.

    3. Extensibility – Easier to add new features without modifying existing code.

    4. Maintenance – Code is easier to maintain and organize.

    5. Hierarchical Modeling – Represents real-world relationships in a clear manner.


    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    Multilevel Inheritance

    • In multilevel inheritance, a class is derived from a child class, which is already derived from a parent class.

    • The hierarchy looks like:

    Grandparent β†’ Parent β†’ Child
    • It allows properties and methods to be passed down multiple levels.


    Example Program

    // Grandparent class class Animal { void eat() { System.out.println("Animal eats food"); } } // Parent class class Mammal extends Animal { void walk() { System.out.println("Mammal walks"); } } // Child class class Dog extends Mammal { void bark() { System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Dog d = new Dog(); d.eat(); // inherited from Animal d.walk(); // inherited from Mammal d.bark(); // own method } }

    Output:

    Animal eats food Mammal walks Dog barks

    Explanation

    1. Animal is the grandparent class.

    2. Mammal extends Animal β†’ inherits eat() method.

    3. Dog extends Mammal β†’ inherits both walk() and eat() methods.

    4. Dog can also have its own methods like bark().


    Β In short:
    • Multilevel inheritance = chain of inheritance (grandparent β†’ parent β†’ child).

    • It allows reusability and hierarchical modeling in programs.


    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    What is an Interface in Java?

    • An interface is a reference type in Java, similar to a class, that can contain only abstract methods (before Java 8) and constants.

    • From Java 8 onwards, interfaces can also have default and static methods.

    • Interfaces are used to achieve 100?straction and multiple inheritance in Java.

    Key points:

    1. Cannot create objects of an interface.

    2. A class implements an interface using implements keyword.

    3. Must provide implementation for all abstract methods of the interface.


    Example Program

    // Interface interface Animal { void eat(); // abstract method void sleep(); } // Class implementing interface class Dog implements Animal { public void eat() { System.out.println("Dog eats food"); } public void sleep() { System.out.println("Dog sleeps"); } } public class Main { public static void main(String[] args) { Dog d = new Dog(); d.eat(); // implemented method d.sleep(); // implemented method } }

    Output:

    Dog eats food Dog sleeps

    Uses of Interface

    1. Achieves 100?straction.

    2. Supports multiple inheritance (a class can implement multiple interfaces).

    3. Provides loose coupling between classes.

    4. Helps in polymorphism, as objects can be referred by interface type.


    In short:
    • Interface = fully abstract blueprint for classes.

    • Classes implement interfaces to define behavior.


    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    What is Polymorphism?

    • Polymorphism is a fundamental concept of Object-Oriented Programming (OOP).

    • Definition: Polymorphism means the ability of an object to take many forms.

    • In Java, it allows a single method or object to behave differently in different contexts.

    • Helps in code reusability, flexibility, and maintainability.


    Types of Polymorphism in Java

    Java supports two types of polymorphism:

    1. Compile-Time Polymorphism (Static Polymorphism)

    • Achieved using method overloading or operator overloading (Java supports only method overloading).

    • Method Overloading: Multiple methods in the same class with the same name but different parameters (number or type).

    • Resolved at compile time, hence called compile-time polymorphism.

    Example:

    class Calculator { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } } public class Main { public static void main(String[] args) { Calculator calc = new Calculator(); System.out.println(calc.add(5, 10)); // calls int method System.out.println(calc.add(5.5, 2.3)); // calls double method } }

    Output:

    15 7.8

    2. Runtime Polymorphism (Dynamic Polymorphism)

    • Achieved using method overriding.

    • Method Overriding: A subclass provides a specific implementation for a method already defined in its parent class.

    • Resolved at runtime, hence called runtime polymorphism.

    Example:

    class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Animal a = new Dog(); // reference of parent class a.sound(); // calls overridden method at runtime } }

    Output:

    Dog barks

    Summary Table

    TypeAchieved byWhen resolvedExample
    Compile-Time PolymorphismMethod OverloadingCompile Timeadd(int,int) & add(double,double)
    Runtime PolymorphismMethod OverridingRuntimeParent ref β†’ Child object calling overridden method

    Advantages of Polymorphism

    1. Code Reusability – Same method name can perform different tasks.

    2. Flexibility – Objects can be treated in multiple ways.

    3. Maintainability – Easier to modify behavior without changing interface.

    4. Extensibility – New functionality can be added with minimal changes.


    Β In short:
    • Polymorphism = ability of a method/object to take many forms.

    • Two types in Java:

      1. Compile-time (method overloading)

      2. Runtime (method overriding)


    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    What is an Exception?

    • An exception is an event that occurs during the execution of a program which disrupts the normal flow of instructions.

    • In Java, exceptions are objects that describe unexpected conditions that occur during program execution.

    • Handled using try, catch, finally blocks to prevent program crash.


    Causes of Exceptions in Java

    Exceptions can occur due to various reasons. Some common causes are:

    1. Division by zero

    int a = 10, b = 0; int c = a / b; // ArithmeticException
    1. Invalid array access

    int[] arr = {1,2,3}; System.out.println(arr[5]); // ArrayIndexOutOfBoundsException
    1. Null reference access

    String s = null; System.out.println(s.length()); // NullPointerException
    1. Invalid type casting

    Object obj = "Hello"; Integer i = (Integer) obj; // ClassCastException
    1. File not found

    FileReader fr = new FileReader("abc.txt"); // FileNotFoundException
    1. Out of memory

    • When program consumes more memory than available β†’ OutOfMemoryError.

    1. User input errors

    • For example, reading an integer but user enters a string β†’ InputMismatchException.


    Summary

    • Exception: An event that interrupts normal program flow.

    • Causes: Arithmetic errors, array index errors, null references, type casting issues, file errors, memory issues, invalid input, etc.


    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    How Exceptions are Handled in Java

    Java provides a robust mechanism to handle runtime errors using Exception Handling.
    The main idea is to catch exceptions and take corrective action instead of letting the program crash.

    Keywords Used:

    1. try – Block of code to monitor for exceptions.

    2. catch – Block to handle the exception.

    3. finally – Block that always executes (used for cleanup).

    4. throw – Used to explicitly throw an exception.

    5. throws – Declares exceptions that a method may throw.

    Example:

    public class Main { public static void main(String[] args) { try { int a = 10, b = 0; int c = a / b; // may cause ArithmeticException } catch (ArithmeticException e) { System.out.println("Error: Division by zero!"); } finally { System.out.println("This block always executes."); } } }

    Output:

    Error: Division by zero! This block always executes.

    Concept of Exception Hierarchy in Java

    • All exception classes in Java are subclasses of Throwable.

    • Throwable has two main subclasses:

      1. Error – Serious problems not meant to be handled (e.g., OutOfMemoryError).

      2. Exception – Conditions that programs can handle.

    Exception class is further divided into:

    1. Checked Exceptions

      • Checked at compile-time.

      • Must be either handled or declared using throws.

      • Example: IOException, SQLException.

    2. Unchecked Exceptions (Runtime Exceptions)

      • Checked at runtime.

      • Optional to handle.

      • Example: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException.

    Hierarchy Diagram (Simplified):

    Throwable β”œβ”€β”€ Error └── Exception β”œβ”€β”€ Checked Exceptions (IOException, FileNotFoundException) └── Unchecked Exceptions (RuntimeException) β”œβ”€β”€ ArithmeticException β”œβ”€β”€ NullPointerException └── ArrayIndexOutOfBoundsException

    Summary

    • Exception Handling: Use try, catch, finally to prevent program crash.

    • Exception Hierarchy: All exceptions derive from Throwable.

      • Checked = compile-time, must handle.

      • Unchecked = runtime, optional to handle.


    πŸ’‘ Interview Tip: Keep answers structured and give real examples.


    Multithreading is a process of executing multiple threads simultaneously. A thread is the smallest unit of a process that can be scheduled for execution.

    • In simple terms: A program can do multiple tasks at the same time.

    • Example: In a music app, you can play music while also downloading songs simultaneously. Each of these tasks can run on a separate thread.

    Advantages of Multithreading:

    1. Faster execution – Multiple tasks run in parallel.

    2. Better resource utilization – CPU idle time is reduced.

    3. Responsive programs – GUI applications remain responsive while performing background tasks.

    4. Simplifies code – Tasks that logically run in parallel can be separated.


    How Threads Are Created in Java

    In Java, there are two ways to create a thread:

    A. By Extending Thread Class

    // Step 1: Create a class that extends Thread class MyThread extends Thread { public void run() { // run() method contains the code executed by the thread for (int i = 1; i <= 5; i++) { System.out.println("Thread A: " + i); } } } public class ThreadExample { public static void main(String[] args) { MyThread t1 = new MyThread(); // Create thread object t1.start(); // Start the thread } }

    Key Points:

    • You override run() method.

    • Use start() to begin execution (not run() directly).


    B. By Implementing Runnable Interface

    class MyRunnable implements Runnable { public void run() { for (int i = 1; i <= 5; i++) { System.out.println("Thread B: " + i); } } } public class RunnableExample { public static void main(String[] args) { MyRunnable r = new MyRunnable(); Thread t2 = new Thread(r); // Pass Runnable object to Thread t2.start(); } }

    Key Points:

    • Use this method when the class already extends another class (since Java supports only single inheritance).

    • The Runnable interface has only one method: run().


    Summary Table

    MethodHow to UseAdvantage
    Extend ThreadCreate class β†’ Override run() β†’ start()Simple to implement
    Implement RunnableImplement Runnable β†’ Override run() β†’ Thread t = new Thread(r) β†’ start()Allows extending another class


    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    What is the Map Interface in Java?

    The Map interface in Java is part of the java.util package and represents a collection of key-value pairs.

    • Each key is unique, and it maps to exactly one value.

    • A value can be duplicated, but keys cannot.

    • Map does not extend the Collection interface, but it is considered part of the Collections Framework.

    Common implementations of Map:

    • HashMap – Stores key-value pairs, no order guaranteed.

    • LinkedHashMap – Maintains insertion order.

    • TreeMap – Stores keys in sorted order.

    • Hashtable – Synchronized version (legacy class).


    Why Use Map?

    • To store and access data efficiently using a key.

    • To avoid duplicates in keys.

    • To quickly search, update, or delete values by key.


    Common Methods in Map Interface
    MethodDescription
    put(K key, V value)Adds a key-value pair
    get(Object key)Returns the value for the specified key
    remove(Object key)Removes the key-value pair
    containsKey(Object key)Checks if a key exists
    containsValue(Object value)Checks if a value exists
    keySet()Returns a set of all keys
    values()Returns a collection of all values
    entrySet()Returns a set of key-value pairs (Map.Entry objects)

    Example Program Using Map
    import java.util.*; public class MapExample { public static void main(String[] args) { // Create a HashMap Map map = new HashMap<>(); // Add key-value pairs map.put(101, "Alice"); map.put(102, "Bob"); map.put(103, "Charlie"); // Display the map System.out.println("Map: " + map); // Get a value by key System.out.println("Value for key 102: " + map.get(102)); // Check if a key exists if (map.containsKey(101)) { System.out.println("Key 101 is present."); } // Remove a key-value pair map.remove(103); System.out.println("Map after removal: " + map); // Iterate through keys and values for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + " => " + entry.getValue()); } } }

    Output:

    Map: {101=Alice, 102=Bob, 103=Charlie} Value for key 102: Bob Key 101 is present. Map after removal: {101=Alice, 102=Bob} 101 => Alice 102 => Bob

    βœ… Key Points to Remember:

    1. Keys are unique, values can be duplicate.

    2. Use HashMap for fastest access, TreeMap for sorted keys, LinkedHashMap to maintain insertion order.

    3. Map is ideal for storing data in key-value format, like dictionaries.


    πŸ’‘ Interview Tip: Keep answers structured and give real examples.


    • Autoboxing: Automatic conversion of primitive types (like int, double, char) into their corresponding wrapper classes (Integer, Double, Character).

    • Unboxing: Automatic conversion of wrapper class objects into their corresponding primitive types.

    ???? Introduced in Java 5 to make code cleaner and avoid manual conversions.


    Β Example of Autoboxing
    public class AutoboxingExample { public static void main(String[] args) { int num = 10; // primitive int // Autoboxing: int β†’ Integer Integer obj = num; System.out.println("Primitive int: " + num); System.out.println("Autoboxed Integer: " + obj); } }

    Output:

    Primitive int: 10 Autoboxed Integer: 10

    Here, Java automatically converts int β†’ Integer.


    Example of Unboxing
    public class UnboxingExample { public static void main(String[] args) { Integer obj = 25; // Wrapper class object // Unboxing: Integer β†’ int int num = obj; System.out.println("Wrapper Integer: " + obj); System.out.println("Unboxed int: " + num); } }

    Output:

    Wrapper Integer: 25 Unboxed int: 25

    Here, Java automatically converts Integer β†’ int.


    Combined Example (Autoboxing + Unboxing in Collections)
    import java.util.ArrayList; public class AutoUnboxingExample { public static void main(String[] args) { ArrayList list = new ArrayList<>(); // Autoboxing (int β†’ Integer) list.add(100); list.add(200); // Unboxing (Integer β†’ int) int sum = list.get(0) + list.get(1); System.out.println("Sum: " + sum); } }

    Output:

    Sum: 300

    Summary:
    • Autoboxing: primitive β†’ wrapper (int β†’ Integer).

    • Unboxing: wrapper β†’ primitive (Integer β†’ int).

    • Makes working with collections (which only store objects) easier.


    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    Java Program

    class InterestCalculator { // Method to calculate Simple Interest public double simpleInterest(double principal, double rate, double time) { return (principal * rate * time) / 100; } // Method to calculate Compound Interest public double compoundInterest(double principal, double rate, double time) { return principal * Math.pow((1 + rate / 100), time) - principal; } public static void main(String[] args) { InterestCalculator calc = new InterestCalculator(); double p = 10000; // Principal double r = 5; // Rate of interest double t = 2; // Time in years double si = calc.simpleInterest(p, r, t); double ci = calc.compoundInterest(p, r, t); System.out.println("Principal: " + p); System.out.println("Rate: " + r + "%"); System.out.println("Time: " + t + " years"); System.out.println("Simple Interest: " + si); System.out.println("Compound Interest: " + ci); } }

    βœ… Output

    Principal: 10000.0 Rate: 5.0% Time: 2.0 years Simple Interest: 1000.0 Compound Interest: 1025.0



    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    Swing in Java

    • Swing is a GUI (Graphical User Interface) toolkit in Java.

    • It is built on top of AWT (Abstract Window Toolkit) but is lightweight (platform-independent look and feel).

    • All Swing classes are in the package:

      javax.swing.*

    Swing Class Hierarchy (Simplified)

    Swing is huge, but the main hierarchy looks like this ????

    java.lang.Object └── java.awt.Component └── java.awt.Container └── javax.swing.JComponent β”œβ”€β”€ JLabel β”œβ”€β”€ JButton β”œβ”€β”€ JCheckBox β”œβ”€β”€ JRadioButton β”œβ”€β”€ JTextField β”œβ”€β”€ JTextArea β”œβ”€β”€ JList β”œβ”€β”€ JTable β”œβ”€β”€ JMenuBar └── JPanel └── java.awt.Window └── java.awt.Frame └── javax.swing.JFrame └── java.awt.Dialog └── javax.swing.JDialog

    Key points:

    • JComponent β†’ Base class for most Swing components.

    • Top-level containers: JFrame, JDialog, JApplet.

    • Intermediate container: JPanel.

    • Leaf components (widgets): buttons, text fields, labels, lists, tables, etc.


    Β Different Swing Components

    Here are the most common Swing components you will use:

    Top-Level Containers

    • JFrame β†’ Main window of the application.

    • JDialog β†’ Popup dialog window.

    • JApplet β†’ Applet window (legacy, rarely used now).

    Control Components (Basic widgets)

    • JLabel β†’ Display text or image.

    • JButton β†’ Push button.

    • JCheckBox β†’ Checkbox.

    • JRadioButton β†’ Radio button (used in groups).

    • JTextField β†’ Single-line text input.

    • JTextArea β†’ Multi-line text input.

    • JPasswordField β†’ Secure text input (masked).

    Container Components

    • JPanel β†’ Simple container to organize components.

    • JScrollPane β†’ Scrollable view.

    • JSplitPane β†’ Divides two components.

    • JTabbedPane β†’ Tabbed navigation.

    Menu Components

    • JMenuBar β†’ Menu bar.

    • JMenu β†’ Menu inside menu bar.

    • JMenuItem β†’ Item inside a menu.

    Advanced Components

    • JTable β†’ Table for data.

    • JTree β†’ Hierarchical tree structure.

    • JList β†’ List of items.

    • JComboBox β†’ Drop-down list.

    • JProgressBar β†’ Shows progress.

    • JSlider β†’ Slider control.


    4. Small Example (JFrame with Components)

    import javax.swing.*; public class SwingExample { public static void main(String[] args) { // Create a frame JFrame frame = new JFrame("Swing Example"); frame.setSize(400, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create components JLabel label = new JLabel("Enter your name:"); JTextField textField = new JTextField(15); JButton button = new JButton("Submit"); // Add to panel JPanel panel = new JPanel(); panel.add(label); panel.add(textField); panel.add(button); // Add panel to frame frame.add(panel); // Make visible frame.setVisible(true); } }

    Summary

    • Swing is in javax.swing package.

    • Hierarchy: Object β†’ Component β†’ Container β†’ JComponent β†’ Swing components.

    • Top-level containers: JFrame, JDialog, JApplet.

    • Common components: JLabel, JButton, JTextField, JCheckBox, JList, JTable, etc

    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    What is FXML?

    • FXML is an XML-based language used to define the structure of a JavaFX user interface.

    • Instead of writing all UI code in Java, you can design the GUI in an XML file and then connect it with Java code (controller).

    • It separates UI design from application logic β†’ much cleaner and easier to maintain.

    Example FXML file (sample.fxml):

    "1.0" encoding="UTF-8"?> <VBox xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml" fx:controller="com.example.Controller"> <Label text="Enter your name:" /> <TextField fx:id="nameField" /> <Button text="Submit" onAction="#handleSubmit" /> VBox>

    Β Here:

    • fx:id links the UI element to the Java controller.

    • onAction specifies the method in the controller.

    Controller (Controller.java):

    package com.example; import javafx.fxml.FXML; import javafx.scene.control.TextField; public class Controller { @FXML private TextField nameField; @FXML private void handleSubmit() { System.out.println("Hello, " + nameField.getText()); } }

    Β Features of JavaFX

    JavaFX is the modern GUI toolkit for Java, replacing Swing.

    Β Key Features:

    1. FXML support β†’ UI in XML + logic in Java (separation of concerns).

    2. Scene Graph β†’ Everything in JavaFX is a node in a scene graph (tree structure).

    3. CSS Styling β†’ JavaFX supports CSS to style components like in web apps.

    4. Rich Controls β†’ Provides controls like TableView, TreeView, DatePicker, WebView.

    5. 2D/3D Graphics & Media β†’ Supports animation, charts, audio, video, 3D rendering.

    6. Properties and Binding β†’ Components can auto-update when values change.

    7. Cross-platform β†’ Works across Windows, Linux, Mac.

    8. FXML + Scene Builder β†’ Drag-and-drop UI design tool.


    Layouts in Java GUI (JavaFX / Swing)

    Layout managers are used to arrange components in a window.

    In JavaFX (Layouts):

    1. Pane β†’ Basic container, absolute positioning.

    2. HBox β†’ Arranges components in a horizontal row.

    3. VBox β†’ Arranges components in a vertical column.

    4. BorderPane β†’ Divides window into Top, Bottom, Left, Right, Center regions.

    5. GridPane β†’ Arranges components in a rows and columns grid (like a table).

    6. StackPane β†’ Places components on top of each other (stacked).

    7. FlowPane β†’ Arranges components left to right, then wraps.

    8. TilePane β†’ Places components in equal-sized tiles.

    9. AnchorPane β†’ Anchors components to edges (e.g., top 10px, left 20px).


    In Swing (Layout Managers):

    1. FlowLayout β†’ Places components left-to-right, wraps to next line.

    2. BorderLayout β†’ Divides container into North, South, East, West, Center.

    3. GridLayout β†’ Uniform grid (equal cell sizes).

    4. BoxLayout β†’ Components arranged either X-axis or Y-axis.

    5. CardLayout β†’ Switch between different panels (like card stack).

    6. GroupLayout β†’ Aligns components hierarchically (used in GUI builders).


    βœ… Summary

    • FXML β†’ XML-based UI definition for JavaFX.

    • JavaFX Features β†’ Scene Graph, FXML, CSS styling, properties binding, 2D/3D graphics, media, rich controls.

    • Layouts:

      • JavaFX β†’ Pane, HBox, VBox, BorderPane, GridPane, StackPane, etc.

      • Swing β†’ FlowLayout, BorderLayout, GridLayout, BoxLayout, CardLayout.

    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    Types of JDBC Drivers

    1. Type-1 (JDBC-ODBC Bridge Driver)

    • Converts JDBC calls into ODBC calls.

    • Requires ODBC driver installed.

    • ❌ Deprecated (removed from Java 8+).

    1. Type-2 (Native-API Driver)

    • Converts JDBC calls into native database API calls.

    • Requires database client libraries.

    • Faster than Type-1 but platform dependent.

    1. Type-3 (Network Protocol Driver)

    • JDBC calls β†’ Middleware server β†’ Database.

    • Independent of database, good for enterprise apps.

    • Needs extra middleware, slower than Type-4.

    1. Type-4 (Thin Driver / Pure Java Driver)

    • JDBC calls directly converted into database protocol.

    • 100% Java, portable, best performance.

    • Most widely used today (e.g., MySQL Connector/J).


    Summary:

    • Type-1 β†’ Bridge (old, slow, removed).

    • Type-2 β†’ Native API (needs client libs).

    • Type-3 β†’ Middleware based (enterprise).

    • Type-4 β†’ Thin driver (pure Java, fastest, common).

    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    1.this keyword

    • Refers to the current object of the class.

    • Uses of this:

      1. To refer to current object’s instance variables.

      2. To call another constructor of the same class (this(...)).

      3. To pass the current object as a parameter to methods/constructors.

    Β Example:

    class Student { String name; int age; Student(String name, int age) { this.name = name; // 'this' differentiates instance variable and parameter this.age = age; } void show() { System.out.println("Name: " + this.name + ", Age: " + this.age); } }

    2. final keyword

    • Means can’t be changed (depends on context).

    • Uses of final:

      1. final variable β†’ Constant (value can’t be modified).

      2. final method β†’ Cannot be overridden in subclasses.

      3. final class β†’ Cannot be inherited.

    Example:

    final class Animal { // cannot be extended final int legs = 4; // constant value final void sound() { // cannot be overridden System.out.println("Animals make sound"); } }

    3. static keyword

    • Belongs to the class, not objects.

    • Uses of static:

      1. static variable β†’ Shared among all objects.

      2. static method β†’ Can be called without creating object.

      3. static block β†’ Runs once when class is loaded.

      4. static class (nested) β†’ Inner class declared static.

    Example:

    class Counter { static int count = 0; // shared variable Counter() { count++; } static void showCount() { // static method System.out.println("Total objects: " + count); } } public class Test { public static void main(String[] args) { new Counter(); new Counter(); Counter.showCount(); // call without object } }

    Summary Table

    Keyword Meaning Used With Effect
    this Refers to current object Inside methods/constructors Access instance variables, call constructors
    final Cannot be changed Variable, Method, Class Constant value, prevent override, prevent inheritance
    static Belongs to class Variable, Method, Block, Inner class Shared value, class-level method, runs once

    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    In Java, data types are divided into two broad categories: primitive data types and non-primitive (reference) data types.

    1. Primitive Data Types

    These are the most basic data types in Java and are not objects. Java has 8 primitive types:

    Data Type

    Description

    Size

    Example

    byte

    8-bit signed integer

    1 byte

    byte b = 100;

    short

    16-bit signed integer

    2 bytes

    short s = 1000;

    int

    32-bit signed integer

    4 bytes

    int i = 12345;

    long

    64-bit signed integer

    8 bytes

    long l = 123456789L;

    float

    32-bit floating-point number

    4 bytes

    float f = 12.34f;

    double

    64-bit floating-point number

    8 bytes

    double d = 123.456;

    char

    16-bit Unicode character

    2 bytes

    char c = 'A';

    boolean

    Represents true or false

    1 bit

    boolean b = true;


    2. Non-Primitive (Reference) Data Types

    These refer to objects and include types that are not predefined by Java. They are created by the programmer or provided by Java libraries.

    Examples:

    • Strings: String name = "Java";
    • Arrays: int[] arr = {1, 2, 3};
    • Classes: class Student { ... }
    • Interfaces
    • Enums

    Key Points

    • Primitive types store actual values.
    • Non-primitive types store references to memory locations.

    Java is statically typed, so you must declare the data type of a variable before using it

    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    The Java Virtual Machine (JVM) is a key part of the Java Runtime Environment (JRE). It enables Java's write once, run anywhere feature.

    Key Responsibilities of JVM:

    1. Loading Code
      • It loads the .class file (compiled bytecode) into memory.
    2. Verifying Code
      • Checks the bytecode for security and correctness.
    3. Executing Code
      • Interprets or JIT-compiles the bytecode into native machine code for execution.
    4. Memory Management
      • Handles memory allocation and Garbage Collection (automatic removal of unused objects).
    5. Exception Handling
      • Manages runtime exceptions and errors to prevent crashes.
    6. Platform Independence
      • Allows Java programs to run on any OS that has a compatible JVM.
    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    The Character class in Java is a wrapper class for the primitive char data type. It provides methods for manipulating characters, including character classification, conversion, and comparisons. The compareTo() method compares two Character objects, while the toString() method returns a string representation of the character.Β 

    Character class?

    • It wraps a char value into an object.
    • It's part of the wrapper classes in Java (Integer, Double, Boolean, etc.).
    • It provides utility methods to manipulate or inspect character data (like checking if a character is a digit, letter, uppercase, etc.)

    Example : Character ch = new Character('A'); // or simplyΒ  Character ch = 'A'; // auto-boxing

    Β 

    compareTo() method

    • Signature: public int compareTo(Character anotherCharacter)
    • It compares two Character objects lexicographically.
    • Returns:
      • 0 if both characters are equal
      • A positive number if the first character is greater
      • A negative number if the first character is lesser

    Example: Character c1 = 'A'; Character c2 = 'B';

    toString() method

    • Signature: public String toString()
    • Converts the Character object to a String representation.

    Example:

    Character c = 'Z';

    String s = c.toString();Β  // s = "Z"

    System.out.println(s);Β Β Β  // Output: Z

    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    File Class in Java

    • The File class in Java (in package java.io) is used to represent the pathname of a file or directory.

    • It does not read/write file content β€” instead, it is used to create, delete, check, and get information about files/directories.

    • For actual reading/writing, classes like FileReader, FileWriter, FileInputStream, FileOutputStream are used.

    Declaration:

    import java.io.File;

    Two Common Methods of File Class

    1. exists()

    • Checks whether the file/directory actually exists in the given path.

    • Returns true if it exists, otherwise false.

    βœ… Example:

    import java.io.File; public class FileExistsExample { public static void main(String[] args) { File f = new File("test.txt"); if (f.exists()) { System.out.println("File exists!"); } else { System.out.println("File does not exist."); } } }

    2. createNewFile()

    • Creates a new, empty file if it does not already exist.

    • Returns true if the file is created, otherwise false.

    • Throws IOException if an error occurs.

    Β Example:

    import java.io.File; import java.io.IOException; public class CreateFileExample { public static void main(String[] args) { try { File f = new File("newfile.txt"); if (f.createNewFile()) { System.out.println("File created: " + f.getName()); } else { System.out.println("File already exists."); } } catch (IOException e) { e.printStackTrace(); } } }

    Summary

    • File class β†’ represents file/directory path, used for management (not for reading/writing).

    • Common methods:

      • exists() β†’ checks if file/directory exists.

      • createNewFile() β†’ creates a new empty file.

    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    Steps for Connecting Java Application with Database using JDBC

    1. Import JDBC Package

      • Import required classes from java.sql package.

      import java.sql.*;
    2. Load/Register the Driver

      • Load the database driver class (Type-4 driver is common today).

      Class.forName("com.mysql.cj.jdbc.Driver"); // For MySQL
    3. Establish Connection

      • Use DriverManager.getConnection() to connect with DB.

      Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/testdb", "root", "password");
    4. Create Statement/PreparedStatement

      • Use to send SQL queries to the database.

      Statement stmt = con.createStatement(); // or PreparedStatement pstmt = con.prepareStatement("SELECT * FROM students WHERE id=?");
    5. Execute Query/Update

      • For SELECT β†’ executeQuery() returns ResultSet.

      • For INSERT/UPDATE/DELETE β†’ executeUpdate() returns number of affected rows.

      ResultSet rs = stmt.executeQuery("SELECT * FROM students"); while (rs.next()) { System.out.println(rs.getInt(1) + " " + rs.getString(2)); }
    6. Process the Results

      • Extract data from ResultSet.

      • Methods: getInt(), getString(), getDouble(), etc.

    7. Close the Connection

      • Always close ResultSet, Statement, and Connection to free resources.

      rs.close(); stmt.close(); con.close();

    Summary of JDBC Steps

    1. Import package (java.sql.*).

    2. Load/register driver (Class.forName).

    3. Establish connection (DriverManager.getConnection).

    4. Create statement (Statement/PreparedStatement).

    5. Execute query (executeQuery / executeUpdate).

    6. Process results (ResultSet).

    7. Close resources.

    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    Commit

    • Definition: Saves all the changes made by the current transaction permanently in the database.

    • Once committed β†’ cannot be undone.

    • Used when all operations in a transaction are successful.

    Example:

    con.setAutoCommit(false); // start transaction stmt.executeUpdate("INSERT INTO accounts VALUES (1,'John',5000)"); con.commit(); // permanently save

    Rollback

    • Definition: Cancels all the changes made by the current transaction and restores the database to the previous state (before transaction started).

    • Used when something goes wrong (like error, failure).

    Β Example:

    con.setAutoCommit(false); // start transaction try { stmt.executeUpdate("INSERT INTO accounts VALUES (2,'Mike',6000)"); stmt.executeUpdate("UPDATE accounts SET balance=balance-2000 WHERE id=99"); // invalid id con.commit(); // won't execute if exception occurs } catch (Exception e) { con.rollback(); // undo all changes }
    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    What are Constructors?

    • A constructor in Java is a special method used to initialize objects.

    • It has the same name as the class and no return type (not even void).

    • Called automatically when an object is created using new.

    Example:

    class Student { String name; int age; // Constructor Student(String n, int a) { name = n; age = a; } void display() { System.out.println(name + " " + age); } } public class Test { public static void main(String[] args) { Student s1 = new Student("John", 20); // constructor called automatically s1.display(); } }

    Difference Between Constructors and Methods

    FeatureConstructorMethod
    NameMust be same as class nameCan have any name
    Return TypeNo return type (not even void)Must have a return type (int, String, void, etc.)
    InvocationCalled automatically when object is createdCalled explicitly using object
    PurposeUsed to initialize objectUsed to define behavior (operations) of object
    OverloadingCan be overloadedCan also be overloaded
    InheritanceNot inheritedMethods are inherited by subclasses

    Summary

    • Constructor β†’ Special method for object initialization, same name as class, no return type, auto-called when object is created.

    • Method β†’ Defines behavior, has return type, called explicitly by object.

    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    FeatureStatic MethodDefault Method
    Keywordstaticdefault
    Called byInterface nameObject of implementing class
    Overridable?NoYes
    PurposeUtility methods in interfaceProvide default implementation

    Summary:

    • Static β†’ Interface-level, cannot be overridden.

    • Default β†’ Object-level, can be overridden.

    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    throw

    • Used inside a method to explicitly throw an exception.

    • Can throw only one exception at a time.

    • Followed by exception object.

    Example:

    public class ThrowExample { static void checkAge(int age) { if (age < 18) { throw new ArithmeticException("Not eligible to vote"); // throw used here } else { System.out.println("Eligible to vote"); } } public static void main(String[] args) { checkAge(16); // This will throw exception } }

    Output:

    Exception in thread "main" java.lang.ArithmeticException: Not eligible to vote

    Β throws

    • Used in method declaration to declare exceptions that a method might throw.

    • Can declare multiple exceptions separated by commas.

    • Does not throw the exception itself; only informs the caller that exception may occur.

    Β Example:

    import java.io.*; public class ThrowsExample { static void readFile() throws IOException { // declares exception FileReader file = new FileReader("test.txt"); file.read(); file.close(); } public static void main(String[] args) { try { readFile(); // must handle IOException } catch (IOException e) { System.out.println("File not found or error reading file"); } } }

    Β Key Differences

    Featurethrowthrows
    UsageInside method bodyIn method declaration
    PurposeTo actually throw an exceptionTo declare potential exceptions
    NumberOne exception at a timeMultiple exceptions allowed
    Followed byException objectException class(es)
    Examplethrow new IOException();void read() throws IOException

    Β Summary:

    • throw β†’ actively throws a single exception.

    • throws β†’ declares that a method may throw exception(s).

    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    Garbage Collection in Java (Brief)

    • Garbage Collection (GC) is the automatic process of removing objects from memory that are no longer referenced.

    • It helps free heap memory and prevents memory leaks.

    • JVM automatically performs GC; programmers don’t need to manually delete objects.


    Advantages of Garbage Collection

    1. Automatic memory management β†’ No need for manual memory deallocation.

    2. Prevents memory leaks β†’ Frees unused objects.

    3. Improves program reliability β†’ Reduces chances of crashes due to memory errors.


    Disadvantages of Garbage Collection

    1. Performance overhead β†’ GC consumes CPU cycles.

    2. Non-deterministic β†’ You cannot predict exactly when GC will run.

    3. Cannot free all resources β†’ GC only manages memory, not external resources (like file handles).


    Role of finalize() Method

    • finalize() is a method called by the garbage collector before destroying an object.

    • It can be used to release resources (like closing files or network connections) before object removal.

    • Example:

    class Test { protected void finalize() { System.out.println("Object is about to be garbage collected"); } } public class GCExample { public static void main(String[] args) { Test t = new Test(); t = null; // make object eligible for GC System.gc(); // suggest JVM to run GC } }

    Output (may vary):

    Object is about to be garbage collected

    Note: finalize() is deprecated in Java 9+, and its use is discouraged in modern Java.


    Summary:

    • GC = automatic memory management.

    • Advantages: Automatic, prevents memory leaks, improves reliability.

    • Disadvantages: Performance overhead, non-deterministic, doesn’t free external resources.

    • finalize() β†’ method called before object destruction to perform cleanup.

    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    GUI Programming in Java

    • GUI (Graphical User Interface) programming allows developers to create graphical interfaces for Java applications, such as windows, buttons, text fields, menus, etc.

    • In Java, GUI can be developed using AWT and Swing.

    • GUI programming makes programs user-friendly and interactive compared to console-based applications.


    1. AWT (Abstract Window Toolkit)

    • AWT is the original Java GUI toolkit.

    • It provides platform-dependent, heavyweight components.

    Features of AWT:

    1. Part of java.awt package.

    2. Provides components like Button, Label, TextField, Checkbox.

    3. Components are heavyweight β†’ rely on native OS resources.

    4. Supports event handling through listeners.

    5. Basic layout managers: FlowLayout, BorderLayout, GridLayout.

    βœ… Example of AWT Button:

    import java.awt.*; import java.awt.event.*; public class AWTExample { public static void main(String[] args) { Frame f = new Frame("AWT Example"); Button b = new Button("Click Me"); f.add(b); f.setSize(300,200); f.setVisible(true); } }

    2. Swing

    • Swing is part of javax.swing package.

    • Provides lightweight, platform-independent components.

    Features of Swing:

    1. Built on top of AWT but lighter and more flexible.

    2. Components include JFrame, JButton, JLabel, JTextField, JTable.

    3. Supports pluggable look and feel (custom UI themes).

    4. Supports MVC architecture for components.

    5. Better event handling and layout management.

    Example of Swing Button:

    import javax.swing.*; public class SwingExample { public static void main(String[] args) { JFrame frame = new JFrame("Swing Example"); JButton button = new JButton("Click Me"); frame.add(button); frame.setSize(300,200); frame.setVisible(true); } }

    Summary Table: AWT vs Swing

    FeatureAWTSwing
    Packagejava.awtjavax.swing
    ComponentsHeavyweightLightweight
    Platform DependencyDependent on OSPlatform independent
    Look & FeelDepends on OSPluggable look & feel
    ExamplesButton, Label, TextFieldJButton, JLabel, JTextField
    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    import java.util.Scanner;


    public class ReverseString {

    Β  Β  public static void main(String[] args) {

    Β  Β  Β  Β  Scanner sc = new Scanner(System.in);


    Β  Β  Β  Β  // Take input from user

    Β  Β  Β  Β  System.out.print("Enter a string: ");

    Β  Β  Β  Β  String input = sc.nextLine();


    Β  Β  Β  Β  // Reverse the string

    Β  Β  Β  Β  String reversed = "";

    Β  Β  Β  Β  for (int i = input.length() - 1; i >= 0; i--) {

    Β  Β  Β  Β  Β  Β  reversed += input.charAt(i);

    Β  Β  Β  Β  }


    Β  Β  Β  Β  // Display the reversed string

    Β  Β  Β  Β  System.out.println("Reversed string: " + reversed);


    Β  Β  Β  Β  sc.close();

    Β  Β  }

    }

    βœ… Sample Run:

    Enter a string: Hello

    Reversed string: olleH

    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    Featurefinalfinallyfinalize()
    TypeKeywordBlockMethod
    PurposePrevent changes (constant, method override, inheritance)Always executes after try-catchCalled by GC before object destruction
    UsageVariable, Method, ClassException handlingObject cleanup
    Called byProgrammerJVMJVM GC
    Examplefinal int x = 10;finally { ... }protected void finalize() { ... }

    Summary:

    • final β†’ prevents modification.

    • finally β†’ always executes after try-catch.

    • finalize() β†’ cleans up before garbage collection

    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    Vector Class in Java

    • Vector is a part of java.util package.

    • It is a dynamic array that can grow or shrink automatically when elements are added or removed.

    • Vector can store objects of any type and allows duplicate values.

    • It is synchronized, meaning thread-safe (unlike ArrayList).

    βœ… Example of Vector:

    import java.util.Vector; public class VectorExample { public static void main(String[] args) { Vector v = new Vector<>(); v.add("Apple"); v.add("Banana"); v.add("Cherry"); System.out.println("Vector elements: " + v); } }

    Output:

    Vector elements: [Apple, Banana, Cherry]

    Β Difference Between Vector and Stack

    FeatureVectorStack
    TypeDynamic arrayLIFO (Last In First Out) data structure
    InheritanceExtends AbstractListExtends Vector
    AccessCan access any element randomlyAccess restricted to top element (push/pop)
    Operationsadd(), remove(), get(), etc.push(), pop(), peek()
    UsageGeneral-purpose collectionSpecifically for LIFO operations

    Summary:

    • Vector β†’ Dynamic array, thread-safe, random access.

    • Stack β†’ Subclass of Vector, follows LIFO, used for push/pop operations.

    πŸ’‘ Interview Tip: Keep answers structured and give real examples.

    1. Technology & Foundation

    • AWT β†’ Oldest GUI toolkit (1995), built on native OS components.

    • Swing β†’ Extension of AWT (1997), written completely in Java (lightweight).

    • JavaFX β†’ Modern framework (2014+), uses FXML + CSS + GPU acceleration.


    2. Component Type

    • AWT β†’ Heavyweight (depends on OS look & feel).

    • Swing β†’ Lightweight (independent of OS).

    • JavaFX β†’ Lightweight, modern UI with CSS & XML-based layouts.


    3. UI Features

    • AWT β†’ Basic components (buttons, labels, checkboxes).

    • Swing β†’ Rich widgets (tables, trees, tabbed panes, sliders).

    • JavaFX β†’ Advanced controls, charts, animations, audio/video, web integration.


    4. Graphics Support

    • AWT β†’ Very limited graphics, 2D only.

    • Swing β†’ Supports 2D, some customization possible.

    • JavaFX β†’ Hardware-accelerated 2D & 3D graphics, animations, multimedia.


    5. Look & Feel

    • AWT β†’ Native look (varies by OS).

    • Swing β†’ Pluggable Look & Feel (same UI across OS).

    • JavaFX β†’ Modern styling with CSS, highly customizable.


    6. Ease of Development

    • AWT β†’ Old, minimal support.

    • Swing β†’ Better than AWT, but verbose.

    • JavaFX β†’ Simplified via FXML + Scene Builder (drag-and-drop UI design).


    7. Current Usage

    • AWT β†’ Legacy only.

    • Swing β†’ Still used in older enterprise apps.

    • JavaFX β†’ Recommended for new modern apps.


    Β Comparison Table

    FeatureAWTSwingJavaFX
    Introduced199519972014 (Java 8)
    TypeHeavyweightLightweightLightweight + Modern
    UI ComponentsBasic onlyRich widgetsAdvanced + Media + Charts
    Look & FeelNative (OS-based)Pluggable (Java-based)CSS-based, modern styling
    GraphicsLimited 2D2D supportGPU-accelerated 2D & 3D
    Ease of UseHard (low-level)Easier but verboseEasier (FXML + Scene Builder)
    Use TodayLegacyLegacy enterprise appsModern apps (recommended)



    πŸ’‘ Interview Tip: Keep answers structured and give real examples.
    Share this Post
    πŸ“ Practice These Questions

    Test yourself in quiz mode before the interview.

    Start Practice Quiz
    πŸ†

    Monthly Challenge

    Compete with top learners & win exciting prizes

    LIVE NOW
    🎁 Rewards + Certificate Participate β†’

    Popular Competitive Exam Quizzes