Top Java Interview Questions & Answers (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
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:
-
Reusability β Code can be reused using inheritance.
-
Modularity β Programs are divided into objects, making them easier to manage.
-
Flexibility & Maintainability β Easy to update or modify without affecting the whole system.
-
Security β Data hiding using encapsulation.
-
Real-world modeling β Programs are designed closer to real-life entities.
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)β.
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:
Difference between Class and Object
| Class | Object |
|---|---|
| Blueprint or template | Instance of a class |
| Defines properties & methods | Represents 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
Need of private Access Specifier in Java
-
privateis 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
Explanation of Example
-
balanceis 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.
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
abstractand must be overridden by a subclass.
Syntax:
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:
Four Useful Methods of String Class
| Method | Description | Example |
|---|---|---|
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 |
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:
Advantages of Inheritance
-
Code Reusability β Reuse existing code without rewriting.
-
Method Overriding β Allows child class to provide specific implementation for parentβs methods.
-
Extensibility β Easier to add new features without modifying existing code.
-
Maintenance β Code is easier to maintain and organize.
-
Hierarchical Modeling β Represents real-world relationships in a clear manner.
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:
-
It allows properties and methods to be passed down multiple levels.
Example Program
Output:
Explanation
-
Animalis the grandparent class. -
MammalextendsAnimalβ inheritseat()method. -
DogextendsMammalβ inherits bothwalk()andeat()methods. -
Dogcan also have its own methods likebark().
Β In short:
-
Multilevel inheritance = chain of inheritance (grandparent β parent β child).
-
It allows reusability and hierarchical modeling in programs.
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:
-
Cannot create objects of an interface.
-
A class implements an interface using
implementskeyword. -
Must provide implementation for all abstract methods of the interface.
Example Program
Output:
Uses of Interface
-
Achieves 100?straction.
-
Supports multiple inheritance (a class can implement multiple interfaces).
-
Provides loose coupling between classes.
-
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.
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:
Output:
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:
Output:
Summary Table
| Type | Achieved by | When resolved | Example |
|---|---|---|---|
| Compile-Time Polymorphism | Method Overloading | Compile Time | add(int,int) & add(double,double) |
| Runtime Polymorphism | Method Overriding | Runtime | Parent ref β Child object calling overridden method |
Advantages of Polymorphism
-
Code Reusability β Same method name can perform different tasks.
-
Flexibility β Objects can be treated in multiple ways.
-
Maintainability β Easier to modify behavior without changing interface.
-
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:
-
Compile-time (method overloading)
-
Runtime (method overriding)
-
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:
-
Division by zero
-
Invalid array access
-
Null reference access
-
Invalid type casting
-
File not found
-
Out of memory
-
When program consumes more memory than available β
OutOfMemoryError.
-
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.
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:
-
tryβ Block of code to monitor for exceptions. -
catchβ Block to handle the exception. -
finallyβ Block that always executes (used for cleanup). -
throwβ Used to explicitly throw an exception. -
throwsβ Declares exceptions that a method may throw.
Example:
Output:
Concept of Exception Hierarchy in Java
-
All exception classes in Java are subclasses of
Throwable. -
Throwablehas two main subclasses:-
Errorβ Serious problems not meant to be handled (e.g., OutOfMemoryError). -
Exceptionβ Conditions that programs can handle.
-
Exception class is further divided into:
-
Checked Exceptions
-
Checked at compile-time.
-
Must be either handled or declared using
throws. -
Example:
IOException,SQLException.
-
-
Unchecked Exceptions (Runtime Exceptions)
-
Checked at runtime.
-
Optional to handle.
-
Example:
ArithmeticException,NullPointerException,ArrayIndexOutOfBoundsException.
-
Hierarchy Diagram (Simplified):
Summary
-
Exception Handling: Use
try,catch,finallyto prevent program crash. -
Exception Hierarchy: All exceptions derive from
Throwable.-
Checked = compile-time, must handle.
-
Unchecked = runtime, optional to handle.
-
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:
-
Faster execution β Multiple tasks run in parallel.
-
Better resource utilization β CPU idle time is reduced.
-
Responsive programs β GUI applications remain responsive while performing background tasks.
-
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
Key Points:
-
You override
run()method. -
Use
start()to begin execution (notrun()directly).
B. By Implementing Runnable Interface
Key Points:
-
Use this method when the class already extends another class (since Java supports only single inheritance).
-
The
Runnableinterface has only one method:run().
Summary Table
| Method | How to Use | Advantage |
|---|---|---|
Extend Thread | Create class β Override run() β start() | Simple to implement |
Implement Runnable | Implement Runnable β Override run() β Thread t = new Thread(r) β start() | Allows extending another class |
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
| Method | Description |
|---|---|
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
Output:
β Key Points to Remember:
-
Keys are unique, values can be duplicate.
-
Use
HashMapfor fastest access,TreeMapfor sorted keys,LinkedHashMapto maintain insertion order. -
Map is ideal for storing data in key-value format, like dictionaries.
-
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
Output:
Here, Java automatically converts int β Integer.
Example of Unboxing
Output:
Here, Java automatically converts Integer β int.
Combined Example (Autoboxing + Unboxing in Collections)
Output:
Summary:
-
Autoboxing: primitive β wrapper (
int β Integer). -
Unboxing: wrapper β primitive (
Integer β int). -
Makes working with collections (which only store objects) easier.
Java Program
β Output
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:
Swing Class Hierarchy (Simplified)
Swing is huge, but the main hierarchy looks like this ????
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)
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
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):
Β Here:
-
fx:idlinks the UI element to the Java controller. -
onActionspecifies the method in the controller.
Controller (Controller.java):
Β Features of JavaFX
JavaFX is the modern GUI toolkit for Java, replacing Swing.
Β Key Features:
-
FXML support β UI in XML + logic in Java (separation of concerns).
-
Scene Graph β Everything in JavaFX is a node in a scene graph (tree structure).
-
CSS Styling β JavaFX supports CSS to style components like in web apps.
-
Rich Controls β Provides controls like
TableView,TreeView,DatePicker,WebView. -
2D/3D Graphics & Media β Supports animation, charts, audio, video, 3D rendering.
-
Properties and Binding β Components can auto-update when values change.
-
Cross-platform β Works across Windows, Linux, Mac.
-
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):
-
Pane β Basic container, absolute positioning.
-
HBox β Arranges components in a horizontal row.
-
VBox β Arranges components in a vertical column.
-
BorderPane β Divides window into Top, Bottom, Left, Right, Center regions.
-
GridPane β Arranges components in a rows and columns grid (like a table).
-
StackPane β Places components on top of each other (stacked).
-
FlowPane β Arranges components left to right, then wraps.
-
TilePane β Places components in equal-sized tiles.
-
AnchorPane β Anchors components to edges (e.g., top 10px, left 20px).
In Swing (Layout Managers):
-
FlowLayout β Places components left-to-right, wraps to next line.
-
BorderLayout β Divides container into North, South, East, West, Center.
-
GridLayout β Uniform grid (equal cell sizes).
-
BoxLayout β Components arranged either X-axis or Y-axis.
-
CardLayout β Switch between different panels (like card stack).
-
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.
-
Types of JDBC Drivers
-
Type-1 (JDBC-ODBC Bridge Driver)
-
Converts JDBC calls into ODBC calls.
-
Requires ODBC driver installed.
-
β Deprecated (removed from Java 8+).
-
Type-2 (Native-API Driver)
-
Converts JDBC calls into native database API calls.
-
Requires database client libraries.
-
Faster than Type-1 but platform dependent.
-
Type-3 (Network Protocol Driver)
-
JDBC calls β Middleware server β Database.
-
Independent of database, good for enterprise apps.
-
Needs extra middleware, slower than Type-4.
-
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).
1.this keyword
-
Refers to the current object of the class.
-
Uses of
this:-
To refer to current objectβs instance variables.
-
To call another constructor of the same class (
this(...)). -
To pass the current object as a parameter to methods/constructors.
-
Β Example:
2. final keyword
-
Means canβt be changed (depends on context).
-
Uses of
final:-
final variable β Constant (value canβt be modified).
-
final method β Cannot be overridden in subclasses.
-
final class β Cannot be inherited.
-
Example:
3. static keyword
-
Belongs to the class, not objects.
-
Uses of
static:-
static variable β Shared among all objects.
-
static method β Can be called without creating object.
-
static block β Runs once when class is loaded.
-
static class (nested) β Inner class declared static.
-
Example:
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 |
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
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:
- Loading Code
- It
loads the
.classfile (compiled bytecode) into memory. - Verifying Code
- Checks
the bytecode for security and correctness.
- Executing Code
- Interprets
or JIT-compiles the bytecode into native machine code for execution.
- Memory Management
- Handles
memory allocation and Garbage
Collection (automatic removal of unused objects).
- Exception Handling
- Manages
runtime exceptions and errors to prevent crashes.
- Platform Independence
- Allows
Java programs to run on any OS that has a compatible JVM.
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
File Class in Java
-
The
Fileclass in Java (in packagejava.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,FileOutputStreamare used.
Declaration:
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:
2. createNewFile()
-
Creates a new, empty file if it does not already exist.
-
Returns true if the file is created, otherwise false.
-
Throws
IOExceptionif an error occurs.
Β Example:
Summary
-
Fileclass β 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.
-
Steps for Connecting Java Application with Database using JDBC
-
Import JDBC Package
-
Import required classes from
java.sqlpackage.
-
-
Load/Register the Driver
-
Load the database driver class (Type-4 driver is common today).
-
-
Establish Connection
-
Use
DriverManager.getConnection()to connect with DB.
-
-
Create Statement/PreparedStatement
-
Use to send SQL queries to the database.
-
-
Execute Query/Update
-
For SELECT β
executeQuery()returnsResultSet. -
For INSERT/UPDATE/DELETE β
executeUpdate()returns number of affected rows.
-
-
Process the Results
-
Extract data from
ResultSet. -
Methods:
getInt(),getString(),getDouble(), etc.
-
-
Close the Connection
-
Always close
ResultSet,Statement, andConnectionto free resources.
-
Summary of JDBC Steps
-
Import package (
java.sql.*). -
Load/register driver (
Class.forName). -
Establish connection (
DriverManager.getConnection). -
Create statement (
Statement/PreparedStatement). -
Execute query (
executeQuery/executeUpdate). -
Process results (
ResultSet). -
Close resources.
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:
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:
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:
Difference Between Constructors and Methods
| Feature | Constructor | Method |
|---|---|---|
| Name | Must be same as class name | Can have any name |
| Return Type | No return type (not even void) | Must have a return type (int, String, void, etc.) |
| Invocation | Called automatically when object is created | Called explicitly using object |
| Purpose | Used to initialize object | Used to define behavior (operations) of object |
| Overloading | Can be overloaded | Can also be overloaded |
| Inheritance | Not inherited | Methods 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.
| Feature | Static Method | Default Method |
|---|---|---|
| Keyword | static | default |
| Called by | Interface name | Object of implementing class |
| Overridable? | No | Yes |
| Purpose | Utility methods in interface | Provide default implementation |
Summary:
-
Static β Interface-level, cannot be overridden.
-
Default β Object-level, can be overridden.
throw
-
Used inside a method to explicitly throw an exception.
-
Can throw only one exception at a time.
-
Followed by exception object.
Example:
Output:
Β 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:
Β Key Differences
| Feature | throw | throws |
|---|---|---|
| Usage | Inside method body | In method declaration |
| Purpose | To actually throw an exception | To declare potential exceptions |
| Number | One exception at a time | Multiple exceptions allowed |
| Followed by | Exception object | Exception class(es) |
| Example | throw new IOException(); | void read() throws IOException |
Β Summary:
-
throwβ actively throws a single exception. -
throwsβ declares that a method may throw exception(s).
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
-
Automatic memory management β No need for manual memory deallocation.
-
Prevents memory leaks β Frees unused objects.
-
Improves program reliability β Reduces chances of crashes due to memory errors.
Disadvantages of Garbage Collection
-
Performance overhead β GC consumes CPU cycles.
-
Non-deterministic β You cannot predict exactly when GC will run.
-
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:
Output (may vary):
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.
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:
-
Part of
java.awtpackage. -
Provides components like
Button,Label,TextField,Checkbox. -
Components are heavyweight β rely on native OS resources.
-
Supports event handling through listeners.
-
Basic layout managers:
FlowLayout,BorderLayout,GridLayout.
β Example of AWT Button:
2. Swing
-
Swing is part of
javax.swingpackage. -
Provides lightweight, platform-independent components.
Features of Swing:
-
Built on top of AWT but lighter and more flexible.
-
Components include
JFrame,JButton,JLabel,JTextField,JTable. -
Supports pluggable look and feel (custom UI themes).
-
Supports MVC architecture for components.
-
Better event handling and layout management.
Example of Swing Button:
Summary Table: AWT vs Swing
| Feature | AWT | Swing |
|---|---|---|
| Package | java.awt | javax.swing |
| Components | Heavyweight | Lightweight |
| Platform Dependency | Dependent on OS | Platform independent |
| Look & Feel | Depends on OS | Pluggable look & feel |
| Examples | Button, Label, TextField | JButton, JLabel, JTextField |
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
| Feature | final | finally | finalize() |
|---|---|---|---|
| Type | Keyword | Block | Method |
| Purpose | Prevent changes (constant, method override, inheritance) | Always executes after try-catch | Called by GC before object destruction |
| Usage | Variable, Method, Class | Exception handling | Object cleanup |
| Called by | Programmer | JVM | JVM GC |
| Example | final int x = 10; | finally { ... } | protected void finalize() { ... } |
Summary:
-
final β prevents modification.
-
finally β always executes after try-catch.
-
finalize() β cleans up before garbage collection
Vector Class in Java
-
Vector is a part of
java.utilpackage. -
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:
Output:
Β Difference Between Vector and Stack
| Feature | Vector | Stack |
|---|---|---|
| Type | Dynamic array | LIFO (Last In First Out) data structure |
| Inheritance | Extends AbstractList | Extends Vector |
| Access | Can access any element randomly | Access restricted to top element (push/pop) |
| Operations | add(), remove(), get(), etc. | push(), pop(), peek() |
| Usage | General-purpose collection | Specifically for LIFO operations |
Summary:
-
Vector β Dynamic array, thread-safe, random access.
-
Stack β Subclass of Vector, follows LIFO, used for push/pop operations.
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
| Feature | AWT | Swing | JavaFX |
|---|---|---|---|
| Introduced | 1995 | 1997 | 2014 (Java 8) |
| Type | Heavyweight | Lightweight | Lightweight + Modern |
| UI Components | Basic only | Rich widgets | Advanced + Media + Charts |
| Look & Feel | Native (OS-based) | Pluggable (Java-based) | CSS-based, modern styling |
| Graphics | Limited 2D | 2D support | GPU-accelerated 2D & 3D |
| Ease of Use | Hard (low-level) | Easier but verbose | Easier (FXML + Scene Builder) |
| Use Today | Legacy | Legacy enterprise apps | Modern apps (recommended) |
Share this Post
Monthly Challenge
Compete with top learners & win exciting prizes
LIVE NOW