Define a Class.
A class is a blueprint or template for creating objects.
It defines the data (fields) and methods (functions) that describe the behavior and properties of objects.
Example:
class Student {
int age;
void display() {
[Link](age);
}
}
Differentiate between Numeric Literal and Non-Numeric Literal.
Numeric Literal Non-Numeric Literal
Represents numbers (integers or real values). Represents characters, strings, or boolean values.
Example: 10, 23.5 Example: 'A', "Hello", true, false
Explain Newborn State of a Thread.
When a thread object is created but not yet started, it is said to be in the newborn (new) state.
It enters the runnable state only after calling the start() method.
What is the use of Packages in Java?
A package is a collection of related classes and interfaces.
It is used to group classes, avoid name conflicts, and provide access control and reusability.
Example:
[Link], [Link], [Link]
Define Null Layout.
A Null Layout means no layout manager is used in a container.
Components are manually positioned using setBounds().
Example:
setLayout(null);
6. Differentiate between Swing and JPanel.
Swing JPanel
Swing is a GUI toolkit that provides lightweight JPanel is a container component used to group other
components like JButton, JLabel, etc. components inside a Swing GUI.
Example: [Link].* Example: JPanel panel = new JPanel();
7. What is JDBC Driver / JDBC-ODBC Bridge driver?
A JDBC Driver is a software component that enables Java applications to interact with databases.
The JDBC-ODBC Bridge Driver connects Java programs to databases using the ODBC driver, acting as a
bridge between JDBC and ODBC.
8. Define ComponentEvent Class.
ComponentEvent is a subclass of AWTEvent that represents events related to GUI components, such as
resizing, moving, showing, or hiding a component.
Example:
ComponentEvent is triggered when a component is resized.
9. Define Layout Manager / List Layout Managers.
A Layout Manager controls how components are arranged within a container.
Common Layout Managers are:
FlowLayout
GridLayout
BorderLayout
CardLayout
BoxLayout
Null Layout
10. Distinguish between init() and destroy()/start() methods of an applet.
init() destroy()/start()
Called once when the applet is first loaded. start() is called each time the applet is started; destroy() is
Used for initialization. called once before applet is unloaded.
Example: load resources Example: stop animation, release resources
11. Define Delegation Event Model.
The Delegation Event Model is Java’s event-handling mechanism where an event source generates an event
and sends it to one or more event listeners that handle it.
It separates event generation and event handling.
12. What are final variables?
A final variable is a constant — its value cannot be changed once assigned.
Syntax:
final int MAX = 100;
13. What is Array?
An array is a collection of elements of the same data type stored in contiguous memory locations.
It allows multiple values to be stored in a single variable.
Example:
int num[] = {10, 20, 30};
1. Define classes and objects
A class is a blueprint or template that defines the structure (data and methods) of objects.
An object is an instance of a class that represents a real-world entity having state (data) and behavior
(methods).
2. Write a note on constructors
A constructor is a special method in a class used to initialize objects when they are created.
Its name is the same as the class name, and it does not have a return type.
Types: Default constructor and Parameterized constructor.
3. Define the term polymorphism
Polymorphism means “one name, many forms.”
It allows a single function or method to behave differently based on the input.
In Java, it is achieved by method overloading (compile-time) and method overriding (runtime).
4. What is two-dimensional array?
A two-dimensional array is an array of arrays used to store data in a table or matrix form.
It is declared as:
int[][] arr = new int[3][3];
5. What is exception handling?
Exception handling is a mechanism to handle runtime errors and maintain normal program flow.
Java uses try, catch, throw, throws, and finally keywords for handling exceptions.
6. Define JTextField
JTextField is a Swing component used to create a single-line text box that allows the user to enter or edit text.
7. Define Delegation (Event) Model
The Delegation Event Model in Java defines how an event is handled.
The source generates an event, and it is handled by an event listener object that implements the appropriate
interface.
8. Java is a platform-independent language – justify
Java programs are compiled into bytecode, which can run on any system having a Java Virtual Machine
(JVM).
This makes Java platform-independent and portable.
9. Define token / list different types of tokens
Tokens are the smallest individual units in a Java program.
Types of tokens:
Keywords
Identifiers
Literals
Operators
Separators
10. Why multiple inheritance is not supported in Java?
Multiple inheritance is not supported in Java to avoid ambiguity caused by the diamond problem.
Instead, Java uses interfaces to achieve multiple inheritance of type.
11. Differentiate between & and && operators
& (Bitwise AND): Performs bit-by-bit AND operation on two values.
&& (Logical AND): Evaluates two boolean expressions; the second condition is checked only if the first one is
true (short-circuit operator).
12. Differentiate between = and == operators
= (Assignment Operator): Used to assign a value to a variable.
int a = 10;
== (Relational Operator): Used to compare two values for equality.
if(a == 10)
13. What is an abstract method/class?
An abstract class is a class declared with the abstract keyword and cannot be instantiated.
An abstract method is a method declared without implementation; it must be overridden in a subclass.
14. Differentiate between drawRect() and fillRect()
drawRect(): Draws only the outline of a rectangle.
fillRect(): Fills the interior of the rectangle with the current color.
15. Java is platform independent – Justify
Java programs are compiled into bytecode by the compiler.
This bytecode can run on any system with a Java Virtual Machine (JVM), making Java platform independent
and portable.
16. What is this keyword?
The this keyword is a reference variable that refers to the current object of the class.
It is used to distinguish between instance variables and parameters with the same name.
17. Difference between String and StringBuffer
String StringBuffer
Immutable (cannot be changed once created) Mutable (can be modified)
Slower for repeated modifications Faster for repeated modifications
Stored in string constant pool Stored in heap memory
18. What is final variable/method/class?
final variable: Value cannot be changed once assigned.
final method: Cannot be overridden by subclasses.
final class: Cannot be inherited.
19. What is command line argument?
Command line arguments are values passed to the main() method when a program is executed from the
command prompt.
They are stored in the String array args[].
Example:
java Sum 10 20
1. Explain Primitive Datatypes / Datatypes used in Java.
In Java, data types specify the type and size of values that variables can hold. Java is a strongly typed
language, meaning every variable must be declared with a data type before use. There are two main
categories of data types: primitive and non-primitive.
Primitive data types are the basic built-in types that represent simple values. Java provides eight primitive
data types: byte, short, int, long, float, double, char, and boolean. Integer types (byte, short, int, long) store
whole numbers of different ranges, while float and double are used to store fractional or decimal numbers.
The char type stores a single character (using Unicode encoding), and boolean holds either true or false.
Non-primitive data types include classes, arrays, interfaces, and strings. For example, int num = 25; declares
an integer, while String name = "Java"; creates a string object. These data types help define the structure of
data used in a program, making Java efficient and platform-independent.
2. Explain Looping Statements with Example.
Looping statements in Java allow a block of code to be executed repeatedly as long as a specified condition
remains true. They are essential for performing repetitive tasks like traversing arrays, generating sequences,
or checking conditions multiple times. There are three main types of loops in Java: for, while, and do-while.
The for loop is used when the number of iterations is known. For example:
for(int i=1; i<=5; i++) {
[Link](i);
}
The while loop checks the condition before executing the block, useful when the number of iterations is
unknown:
int i=1;
while(i<=5) {
[Link](i);
i++;
}
The do-while loop executes at least once because it checks the condition after running the loop body:
int i=1;
do {
[Link](i);
i++;
} while(i<=5);
Loops reduce code redundancy, improve efficiency, and make repetitive tasks simpler and structured.
3. Write a Note on Constructors.
A constructor in Java is a special method that initializes an object when it is created. It has the same name as
the class and does not have any return type—not even void. Constructors are automatically called when an
object is instantiated using the new keyword. There are two types of constructors: default constructors and
parameterized constructors.
A default constructor takes no arguments and assigns default values to object variables.
Example:
class Demo {
Demo() { [Link]("Default Constructor Called"); }
}
A parameterized constructor takes arguments to initialize variables:
class Demo {
int a;
Demo(int x) { a = x; }
}
Constructors support overloading, meaning a class can have multiple constructors with different parameter
lists. They help in ensuring that every object starts in a valid state. Constructors are fundamental in
object-oriented programming as they define how objects are built and initialized.
4. How Will You Access Class Members Using Objects? Give Example.
In Java, a class defines variables and methods, while objects are instances of that class. To access the
members (fields and methods) of a class, we use the dot (.) operator along with the object name. First, an
object is created using the new keyword, and then its members can be accessed.
Example:
class Student {
int age = 20;
void display() {
[Link]("Age: " + age);
}
public static void main(String[] args) {
Student s1 = new Student();
[Link]([Link]);
[Link]();
}
}
In this example, the object s1 is used to access both the variable age and the method display(). Objects act as
a bridge between the class definition and its functionality, allowing interaction with the class members. This
mechanism promotes encapsulation, where data and behavior are combined within the same structure,
ensuring modularity and data security.
5. Explain Different Types of Built-in Exceptions.
An exception in Java is an event that interrupts the normal flow of program execution. Java provides a
powerful mechanism to handle such errors through its exception handling framework. Exceptions are objects
that represent errors, and Java classifies them into checked and unchecked exceptions.
Some common built-in exceptions are:
ArithmeticException: Occurs when an arithmetic error happens, like division by zero.
NullPointerException: Happens when a program tries to access a null object reference.
ArrayIndexOutOfBoundsException: Occurs when accessing an invalid array index.
NumberFormatException: Thrown when string conversion to a number fails.
IOException: Occurs during input-output operations.
Example:
try {
int a = 5 / 0;
} catch (ArithmeticException e) {
[Link]("Division by zero not allowed!");
}
Exception handling makes programs more robust and prevents crashes. Java uses keywords like try, catch,
throw, throws, and finally for structured exception management.
6. How Parameters Can Be Passed to Applet Using Tags?
In Java, parameters can be passed to an applet using the <PARAM> tag within the HTML file that embeds the
applet. These parameters are used to customize the applet’s behavior. Inside the Java applet, the method
getParameter(String name) retrieves the value of a parameter.
Example HTML code:
<applet code="[Link]" width="300" height="200">
<param name="username" value="Rahul">
</applet>
Applet code:
import [Link].*;
import [Link].*;
public class Sample extends Applet {
String name;
public void init() {
name = getParameter("username");
}
public void paint(Graphics g) {
[Link]("Hello " + name, 50, 50);
}
}
Here, the <PARAM> tag passes the value “Rahul” to the applet, which displays “Hello Rahul” on screen. This
mechanism allows applets to interact dynamically with web pages, providing flexibility and reusability.
7. Write a Java Program to Demonstrate Thread Priorities.
In Java, threads are lightweight sub-processes that allow a program to perform multiple tasks simultaneously.
Each thread has a priority level (ranging from 1 to 10), which determines the order in which threads are
scheduled for execution. By default, each thread gets a priority of 5. The priorities can be changed using
setPriority() and retrieved using getPriority().
Example:
class PriorityDemo extends Thread {
public void run() {
[Link]([Link]().getName() +
" Priority: " + [Link]().getPriority());
}
public static void main(String[] args) {
PriorityDemo t1 = new PriorityDemo();
PriorityDemo t2 = new PriorityDemo();
[Link](Thread.MIN_PRIORITY); // 1
[Link](Thread.MAX_PRIORITY); // 10
[Link]();
[Link]();
}
}
In this example, t2 has higher priority, so it may execute first. However, thread scheduling depends on the
JVM and operating system. Thread priorities help optimize multitasking and CPU time allocation in concurrent
applications.
8. Explain Delegation Event Model.
The Delegation Event Model is Java’s mechanism for handling events in GUI-based programs. It follows a
source-listener pattern where an event is generated by an event source and handled by one or more event
listeners. The event source (like a button) generates an event object when an action occurs, such as a click.
This event is then passed to the registered listener which contains code to handle it.
Components:
Event Source – The component that generates an event (e.g., button).
Event Object – Encapsulates event details.
Event Listener – Interface that defines methods to respond to the event.
Example:
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Button clicked!");
}
});
This model separates event generation from handling, making programs modular and easier to maintain. It
forms the basis for all GUI interactions in Swing and AWT applications.
9. Explain throw, throws, and finally with Example.
In Java, exceptions are handled using specific keywords such as throw, throws, and finally.
The throw keyword is used to explicitly throw an exception from a block of code.
The throws keyword is used in method declarations to specify the type of exceptions a method might throw to
the calling method.
The finally block is always executed, regardless of whether an exception occurs or not, making it ideal for
cleanup operations like closing files or releasing resources.
Example:
class Example {
static void check(int age) throws ArithmeticException {
if (age < 18)
throw new ArithmeticException("Not Eligible");
else
[Link]("Eligible");
}
public static void main(String args[]) {
try {
check(15);
} catch (Exception e) {
[Link](e);
} finally {
[Link]("Execution Complete");
}
}
}
Here, throw creates an exception, throws declares it, and finally ensures the message executes always.
Together, they provide reliable exception management.
10. Discuss User-Defined Packages.
A package in Java is a collection of related classes, interfaces, and sub-packages. Packages help organize
code, avoid name conflicts, and control access to classes. There are two types of packages: built-in (Java
API) and user-defined.
User-defined packages are created by programmers to group their own classes. They are defined using the
package keyword at the top of a Java file.
Example:
package mypack;
public class Message {
public void show() {
[Link]("Hello from my package!");
}
}
To use it in another program:
import [Link];
class Demo {
public static void main(String[] args) {
Message obj = new Message();
[Link]();
}
}
Packages improve code modularity, make maintenance easier, and enable reuse across different projects.
They also support access protection using public, private, and protected modifiers.
1. What is an array and explain types of arrays with examples
An array in Java is a data structure that stores multiple values of the same data type in contiguous memory
locations. It allows easy access to elements using an index. The main advantage of arrays is that they
simplify data manipulation and reduce code complexity when handling large sets of related data.
In Java, arrays are objects that can store primitive data types as well as objects of classes. The array index
starts from zero (0), and the last index is (n – 1) where n is the array length.
Types of Arrays in Java:
One-Dimensional Array:
It represents a linear list of elements.
Example:
int[] numbers = {10, 20, 30, 40};
for(int i=0; i<[Link]; i++)
[Link](numbers[i]);
Two-Dimensional Array:
It represents data in a rows and columns structure, similar to a matrix.
Example:
int[][] matrix = { {1,2,3}, {4,5,6}, {7,8,9} };
[Link](matrix[1][2]); // prints 6
Arrays in Java are dynamically allocated, meaning memory is assigned during runtime. They can also be
created using the new keyword. Arrays simplify repetitive tasks like storing marks of students, matrix
operations, and data tables.
2. How do you create & initialize a one-dimensional or two-dimensional array in Java
Arrays in Java can be declared, created, and initialized in multiple ways. They are powerful for handling lists
or tabular data efficiently.
1. One-Dimensional Array
A one-dimensional array stores a list of elements of the same type.
Declaration and Creation:
int[] marks = new int[5];
This creates an array capable of holding five integers.
Initialization:
marks[0] = 85;
marks[1] = 90;
marks[2] = 75;
Combined Declaration and Initialization:
int[] marks = {85, 90, 75, 60, 95};
Accessing Elements:
for(int i = 0; i < [Link]; i++)
[Link](marks[i]);
2. Two-Dimensional Array
A two-dimensional array is an array of arrays (used for tabular or matrix data).
Declaration and Creation:
int[][] matrix = new int[3][3];
Initialization:
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
Combined Declaration and Initialization:
int[][] matrix = { {1,2,3}, {4,5,6}, {7,8,9} };
Accessing Elements:
for(int i=0;i<3;i++){
for(int j=0;j<3;j++)
[Link](matrix[i][j]+" ");
[Link]();
}
Arrays can hold primitive or reference types, and the length property is used to find the number of elements.
3. Write a Java program to demonstrate thread priorities
In Java, each thread has a priority which determines the order in which threads are scheduled for execution.
The priority of a thread is represented by an integer value between 1 (MIN_PRIORITY) and 10
(MAX_PRIORITY). By default, every thread has a priority of 5 (NORM_PRIORITY).
Threads with higher priority are given more CPU time compared to lower-priority threads. However, the final
scheduling decision depends on the operating system's thread scheduler.
Program Example:
class MyThread extends Thread {
public void run() {
[Link]("Running thread: " + [Link]().getName());
[Link]("Priority: " + [Link]().getPriority());
}
}
public class ThreadPriorityDemo {
public static void main(String args[]) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
[Link](Thread.MIN_PRIORITY); // 1
[Link](Thread.NORM_PRIORITY); // 5
[Link](Thread.MAX_PRIORITY); // 10
[Link]();
[Link]();
[Link]();
}
}
Output:
Running thread: Thread-0 Priority: 1
Running thread: Thread-1 Priority: 5
Running thread: Thread-2 Priority: 10
This demonstrates how Java handles thread priorities and execution order.
4. Explain how threads are created using Runnable interface
In Java, threads can be created in two ways — by extending the Thread class or by implementing the
Runnable interface. The second method is more flexible because it allows a class to extend another class
while still running as a thread.
The Runnable interface contains a single method public void run(). To create a thread:
Create a class that implements the Runnable interface.
Provide an implementation for the run() method.
Create a Thread object and pass the Runnable instance to it.
Start the thread using start() method.
Example:
class MyRunnable implements Runnable {
public void run() {
for(int i=1; i<=5; i++) {
[Link]([Link]().getName() + " - Count: " + i);
try {
[Link](500);
} catch(InterruptedException e) {
[Link](e);
}
}
}
}
public class RunnableDemo {
public static void main(String args[]) {
Thread t1 = new Thread(new MyRunnable(), "Thread1");
Thread t2 = new Thread(new MyRunnable(), "Thread2");
[Link]();
[Link]();
}
}
Explanation:
Both threads run concurrently, each executing the run() method.
The [Link]() method pauses the thread temporarily.
The Runnable method is preferred when multiple inheritance is required.
5. Explain different types of built-in exceptions
In Java, exceptions are runtime errors that disrupt the normal flow of execution. The exception handling
mechanism allows a programmer to handle such errors gracefully and maintain normal program flow.
Exceptions are represented by objects that derive from the Throwable class, which has two main subclasses:
Exception and Error.
Built-in Exceptions are predefined in Java libraries and are automatically raised by the Java Virtual Machine
(JVM) when an error occurs. They are mainly divided into two categories:
Checked Exceptions:
These are exceptions checked by the compiler during compile time. Examples:
IOException: Occurs during input/output operations.
SQLException: Occurs during database access errors.
FileNotFoundException: When a file is not found.
ClassNotFoundException: When a class is missing.
Unchecked Exceptions:
These occur during program execution and are not checked at compile time. They are subclasses of
RuntimeException. Examples:
ArithmeticException: Division by zero.
NullPointerException: Accessing an object with null reference.
ArrayIndexOutOfBoundsException: Invalid array index.
NumberFormatException: Invalid numeric conversion.
Exception handling is performed using try, catch, throw, throws, and finally blocks.
For example:
try {
int a = 5/0;
} catch(ArithmeticException e) {
[Link]("Cannot divide by zero");
}
6. Write short note on (a) JRadioButton (b) JCheckBox
(a) JRadioButton:
A JRadioButton in Swing is used when the user has to select only one option from a group of options. When
one radio button is selected, others in the same group are automatically deselected. It is part of the
[Link] package.
Example:
JRadioButton male = new JRadioButton("Male");
JRadioButton female = new JRadioButton("Female");
ButtonGroup group = new ButtonGroup();
[Link](male);
[Link](female);
This ensures that only one button can be active at a time.
(b) JCheckBox:
A JCheckBox allows the user to select multiple options independently. Each checkbox can be selected or
deselected without affecting others.
Example:
JCheckBox java = new JCheckBox("Java");
JCheckBox python = new JCheckBox("Python");
Both checkboxes can be selected simultaneously.
Key Difference:
JRadioButton: Single selection within a group.
JCheckBox: Multiple selections allowed.
Both are used to design interactive GUIs in Swing applications.
7. Differentiate (a) JCheckBox vs JRadioButton (b) JList vs JComboBox
(a) JCheckBox vs JRadioButton
Feature JCheckBox JRadioButton
Selection Multiple options can be selected Only one option in a group can be selected
Grouping Independent, no grouping required Must be grouped using ButtonGroup
Example Yes/No/Maybe options Male/Female selection
Behavior Works independently Mutually exclusive options
(b) JList vs JComboBox
Feature JList JComboBox
Visibility Displays a list of items Displays a dropdown list
Selection Can allow multiple selections Allows only one selection at a time
Space Requires more screen space Saves space via dropdown
Example Selecting hobbies Selecting a country from dropdown
These components are part of the Swing package and help design user-friendly graphical interfaces for
desktop applications.
8. Explain components of Swing
Swing is a part of Java’s JFC (Java Foundation Classes) used to create platform-independent GUI
applications. Swing components are lightweight and written entirely in Java, which makes them portable and
flexible compared to AWT components.
Major Swing Components:
JFrame: Top-level container that represents the main window of an application.
JPanel: Used as a generic container to group other components.
JLabel: Displays non-editable text or images.
JButton: Represents a clickable button that triggers an action.
JTextField: Single-line text input field.
JTextArea: Multi-line text input area.
JCheckBox: Allows multiple independent selections.
JRadioButton: Used for mutually exclusive selections.
JList: Displays a list of items; can allow multiple selections.
JComboBox: A drop-down list from which the user can select one item.
JMenuBar, JMenu, JMenuItem: For adding menus and submenus to GUI applications.
Layout Managers: Swing supports various layout managers such as FlowLayout, BorderLayout, GridLayout,
CardLayout, and BoxLayout to control component placement.
Swing provides event-driven programming with listeners that respond to user interactions.
9. Discuss steps in developing and running a local applet
An applet is a small Java program that runs inside a web browser or an applet viewer. It is used for creating
dynamic web content. Applets are part of Java’s AWT and Swing libraries.
Steps to Develop and Run a Local Applet:
Create the Source Code:
Define a class that extends the Applet class or JApplet.
Example:
import [Link].*;
import [Link].*;
public class HelloApplet extends Applet {
public void paint(Graphics g) {
[Link]("Hello, Applet!", 50, 50);
}
}
Compile the Program:
Use the Java compiler.
javac [Link]
Create an HTML File:
Use the <applet> tag to embed the applet.
<applet code="[Link]" width="200" height="200"></applet>
Run the Applet:
Execute using Applet Viewer.
appletviewer [Link]
Applet Life Cycle Methods:
init(): Initialization.
start(): Executed after initialization.
paint(): For displaying graphics.
stop() and destroy(): For cleanup.
12. Explain Delegation Event Model
The Delegation Event Model in Java defines how events are generated and handled in GUI programming. It
separates the event source from the event listener, allowing better modularity and flexibility.
Working of Delegation Model:
An event source (like a button or checkbox) generates an event.
The event is delegated to an event listener that implements specific listener interfaces (like ActionListener,
ItemListener, etc.).
The listener handles the event by executing the appropriate method (e.g., actionPerformed()).
Steps:
Implement the listener interface:
Example: ActionListener for button clicks.
Register the listener with the source:
[Link](this);
Define the event-handling method:
public void actionPerformed(ActionEvent e) {
[Link]("Button Clicked!");
}
Example:
import [Link].*;
import [Link].*;
import [Link].*;
public class EventDemo extends JFrame implements ActionListener {
JButton b;
EventDemo() {
b = new JButton("Click");
[Link](this);
add(b);
setSize(200,200);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
[Link]("Button was clicked!");
}
public static void main(String[] args) {
new EventDemo();
}
}
This model is used throughout Java’s AWT and Swing frameworks for handling events like clicks, key
presses, and mouse movements.
1. Explain the Use of Different Operators in Java
Operators in Java are special symbols that perform specific operations on one, two, or three operands and
return a result. They form the foundation of expressions and are widely used in decision-making,
mathematical calculations, and logic building. Java supports a wide range of operators, classified into several
categories according to their functionality.
Arithmetic Operators:
Used to perform basic mathematical operations such as addition, subtraction, multiplication, division, and
modulus.
Example:
int a = 10, b = 5;
[Link](a + b); // 15
[Link](a % b); // 0
Relational Operators:
Used to compare two values and return a boolean (true or false).
Operators: <, >, <=, >=, ==, !=
Example:
if(a > b) [Link]("a is greater");
Logical Operators:
Used to combine multiple conditions.
&& (AND), || (OR), and ! (NOT).
if(a > 0 && b > 0) [Link]("Both positive");
Assignment Operators:
Used to assign values to variables.
=, +=, -=, *=, /=
a += 5; // same as a = a + 5
Increment and Decrement Operators:
Used to increase or decrease value by one.
++ and --
a++; // increments by 1
Bitwise Operators:
Used for operations on bits.
&, |, ^, ~, <<, >>, >>>.
They are especially useful in low-level programming or system development.
Conditional (Ternary) Operator:
A shorthand for if-else.
Syntax: condition ? expression1 : expression2
int max = (a > b) ? a : b;
Special Operators:
Includes instanceof (checks if an object belongs to a specific class) and the dot (.) operator to access class
members.
In conclusion, Java’s operators are essential in all types of programming — from basic mathematical
operations to complex decision-making. Understanding their precedence and associativity is crucial for
writing accurate and efficient Java code.
2. Explain Interfaces with Example
An interface in Java is a collection of abstract methods and constants used to achieve abstraction and
multiple inheritance. It defines a contract or blueprint that a class must follow, but it does not contain method
implementations. Interfaces are declared using the interface keyword.
Interfaces contain only method declarations and constant definitions. All interface methods are implicitly
public and abstract, and all variables are public, static, and final. A class that implements an interface must
provide concrete definitions for all its abstract methods.
Syntax:
interface Animal {
void sound(); // abstract method
}
class Dog implements Animal {
public void sound() {
[Link]("Barks");
}
}
class Test {
public static void main(String args[]) {
Animal a = new Dog();
[Link]();
}
}
In this example, the interface Animal defines an abstract method sound(). The class Dog implements Animal
and provides its own version of the method. This enables polymorphism — the ability to call the same method
on different classes and get different behavior.
Advantages of Interfaces:
Provides 100% abstraction.
Supports multiple inheritance.
Helps in loose coupling between classes.
Improves reusability and modularity.
Real-world Example:
Consider a RemoteControl interface that defines turnOn() and turnOff() methods. Classes like TV and Fan
implementing this interface will define their specific behavior for turning on or off.
In Java 8 and later, interfaces can also have default and static methods with bodies, making them more
powerful. Overall, interfaces are an essential OOP concept that help in designing scalable and flexible
applications.
3. What is Constructor Overloading? Write a Java Program to Implement It
A constructor in Java is a special method that initializes objects when they are created. Constructor
Overloading refers to having more than one constructor in the same class with different parameter lists
(number, type, or order). It allows creating objects in different ways, depending on available data.
Rules:
Constructors must have the same name as the class.
They cannot have a return type.
They must differ in parameter count or type.
Example:
class Student {
int id;
String name;
// Default Constructor
Student() {
id = 0;
name = "Unknown";
}
// Parameterized Constructor
Student(int i, String n) {
id = i;
name = n;
}
void display() {
[Link](id + " " + name);
}
public static void main(String args[]) {
Student s1 = new Student();
Student s2 = new Student(101, "Rahul");
[Link]();
[Link]();
}
}
Explanation:
Here, there are two constructors — one with no parameters and one with parameters. Java decides which one
to call based on the arguments passed during object creation. This allows flexible initialization of objects.
Advantages:
Increases code flexibility.
Provides multiple ways to initialize objects.
Improves readability and reduces duplication.
Real-world Example:
In a BankAccount class, you can have one constructor to create an empty account and another to create one
with an initial balance.
Constructor overloading is a classic example of compile-time polymorphism in Java. It enhances the clarity
and usability of class structures.
4. Explain JLabel and JButton with Real World Example
In Java Swing, JLabel and JButton are components used to build Graphical User Interfaces (GUIs). Swing is
part of Java’s Abstract Window Toolkit (AWT) and provides platform-independent, lightweight components.
JLabel:
JLabel is a component that displays static text, an image, or both. It cannot be edited by the user. It is often
used to label input fields or display messages.
JLabel label = new JLabel("Enter Name:");
JButton:
JButton is a component that creates a button which can trigger an event when clicked.
JButton button = new JButton("Submit");
Program Example:
import [Link].*;
class LoginExample {
public static void main(String[] args) {
JFrame f = new JFrame("Login Form");
JLabel l = new JLabel("Username:");
JTextField t = new JTextField();
JButton b = new JButton("Login");
[Link](50,50,100,30);
[Link](150,50,150,30);
[Link](100,120,100,30);
[Link](l); [Link](t); [Link](b);
[Link](null);
[Link](400,300);
[Link](true);
}
}
Explanation:
Here, a JLabel is used to display “Username” and a JButton acts as a clickable login button. These elements
are visually interactive and enhance user experience.
Real-world Use:
In real applications, JLabels display prompts or information, while JButtons handle user actions like “Login”,
“Submit”, or “Exit”.
In conclusion, JLabel provides non-interactive text or images, whereas JButton allows users to perform
actions. They are integral to Swing-based GUI development.
5. Differentiate Between One-Dimensional and Two-Dimensional Arrays and Write a Java Program to Sort
An array is a collection of elements of the same data type stored in contiguous memory locations. Java
supports both one-dimensional and two-dimensional arrays.
One-Dimensional Array:
It is a linear structure containing a list of elements.
int marks[] = {90, 70, 80, 60};
Each element can be accessed by its index, e.g., marks[0].
Two-Dimensional Array:
It is an array of arrays — used to represent data in rows and columns.
int matrix[][] = {{1,2,3},{4,5,6},{7,8,9}};
Here, matrix[0][1] = 2.
Difference Table:
Feature 1D Array 2D Array
Structure Linear Matrix (rows × columns)
Declaration int a[] = new int[5]; int a[][] = new int[3][3];
Access Single index Two indexes
Example Use Marks of students Table of marks in subjects
Sorting Example (1D Array):
import [Link].*;
class SortArray {
public static void main(String args[]) {
int a[] = {10, 5, 30, 20, 15};
[Link](a);
[Link]("Sorted Array:");
for(int i : a)
[Link](i + " ");
}
}
Explanation:
The program sorts the array elements in ascending order using [Link](). Sorting helps in searching and
organizing data efficiently.
Arrays are the foundation for data structures and are essential for algorithms like sorting, searching, and
matrix operations.
6. Explain Exception Handling Mechanism
Exception Handling is a technique used in Java to handle runtime errors gracefully without crashing the
program. It ensures the smooth flow of execution even when unexpected events occur.
Common Causes:
Division by zero
Invalid array index
Null object access
File not found
Keywords Used:
try: Contains code that might throw an exception.
catch: Used to handle the exception.
throw: Used to explicitly throw an exception.
throws: Declares exceptions in method signature.
finally: Executes code whether exception occurs or not.
Example:
class Example {
public static void main(String args[]) {
try {
int a = 5 / 0;
} catch (ArithmeticException e) {
[Link]("Division by zero not allowed!");
} finally {
[Link]("Program executed successfully.");
}
}
}
Explanation:
The above code catches an ArithmeticException and continues program flow. Without handling, the program
would terminate abruptly.
Types of Exceptions:
Checked Exceptions: Handled at compile time (e.g., IOException).
Unchecked Exceptions: Handled at runtime (e.g., ArithmeticException).
Errors: Represent serious issues (e.g., OutOfMemoryError).
Advantages:
Prevents abnormal termination.
Increases program reliability.
Helps debugging.
Conclusion:
Exception handling adds robustness to Java programs. It isolates error-handling logic and keeps code clean
and manageable.
4. Explain the features of Java
Java is one of the most popular and widely used programming languages in the world. It was developed by
James Gosling at Sun Microsystems in 1995. Java was designed to be simple, secure, platform-independent,
and object-oriented, making it ideal for developing distributed and network-based applications.
Java’s power lies in its features — each designed to make software development efficient, portable, and
reliable.
Main Features of Java:
Simple:
Java’s syntax is clean and easy to understand. It removes complex features from C++ such as pointers,
operator overloading, and multiple inheritance (replaced by interfaces). Java’s memory management is
automatic, using garbage collection.
Object-Oriented:
Everything in Java is treated as an object, making it easy to model real-world systems. The four main OOP
principles—Encapsulation, Inheritance, Abstraction, and Polymorphism—form the core of Java.
Platform-Independent and Portable:
Java programs are compiled into bytecode using the javac compiler. This bytecode can run on any system
that has the Java Virtual Machine (JVM). Thus, “Write Once, Run Anywhere (WORA)” is the hallmark of Java.
Compiled and Interpreted:
Java combines both compilation (to bytecode) and interpretation (by JVM), which ensures both efficiency and
flexibility.
Robust:
Java provides strong memory management, type checking, and exception handling. Errors like memory leaks
and pointer corruption are minimized.
Secure:
Java runs inside a sandbox environment in the JVM, which protects the system from viruses and
unauthorized access. It restricts file access and memory manipulation.
Multithreaded:
Java supports multithreading, allowing multiple threads (parts of a program) to run concurrently. This is
crucial for animations, games, and network applications.
Distributed:
Java is designed for distributed computing with built-in networking libraries and RMI (Remote Method
Invocation).
High Performance:
Java’s Just-In-Time (JIT) compiler converts bytecode to machine code at runtime, making it faster than
traditional interpreted languages.
Dynamic and Extensible:
Java supports dynamic linking and class loading at runtime, which allows applications to grow as needed.
Conclusion:
Java’s combination of simplicity, robustness, and platform independence makes it a preferred choice for web,
mobile, and enterprise application development.
5. Differentiate between Object-Oriented and Procedure-Oriented Programming. Explain OOP Concepts
Difference Between POP and OOP:
Feature Procedure-Oriented Programming (POP) Object-Oriented Programming (OOP)
Approach Based on functions and procedures Based on classes and objects
Data Security Data is global and can be accessed freely Data is hidden inside objects (Encapsulation)
Reusability Functions can be reused Entire classes can be reused through inheritance
Examples C, Pascal Java, C++, Python
Data Handling Separate from functions Data and methods are bundled together
Modularity Less modular Highly modular and scalable
OOP Concepts in Java
Class:
A class is a blueprint or template that defines variables (fields) and methods (functions) common to all
objects of that type.
class Student {
int rollNo;
String name;
void display() {
[Link](rollNo + " " + name);
}
}
Object:
An object is an instance of a class that represents a real-world entity.
Student s1 = new Student();
Encapsulation:
The process of wrapping data and code together into a single unit. It hides internal implementation details
and only exposes necessary features through getters and setters.
class Account {
private int balance = 5000;
public int getBalance() { return balance; }
}
Abstraction:
The process of hiding complex details and showing only essential features to the user. Achieved using
abstract classes and interfaces.
Inheritance:
Mechanism where one class acquires properties and behaviors of another class using the extends keyword.
class A { void display() { [Link]("Base"); } }
class B extends A { void message() { [Link]("Derived"); } }
Polymorphism:
Means “many forms.” It allows a method or object to behave differently in different contexts.
Compile-time: Method Overloading
Runtime: Method Overriding
Dynamic Binding:
Method call is resolved at runtime rather than compile time, ensuring flexibility in code execution.
Conclusion:
OOP provides modularity, reusability, and maintainability, which makes Java programs easier to design, test,
and extend.
6. What is Method Overloading? Write a Java Program to Implement It
Definition:
Method Overloading is an important feature of polymorphism in Java. It allows a class to have more than one
method with the same name but different parameter lists (different number, order, or data types of
arguments). The compiler determines which method to execute at compile time—hence it is known as
compile-time polymorphism.
Rules of Method Overloading:
Methods must have the same name.
They must differ in the number or type of parameters.
The return type alone cannot distinguish overloaded methods.
Advantages:
Increases code readability and reusability.
Simplifies code — same function name can perform related tasks.
Reduces method name confusion.
Example Program:
class Calculator {
// Method 1: Adds two integers
int add(int a, int b) {
return a + b;
}
// Method 2: Adds three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Method 3: Adds two double values
double add(double a, double b) {
return a + b;
}
}
public class MethodOverloadingDemo {
public static void main(String[] args) {
Calculator calc = new Calculator();
[Link]("Sum of 2 integers: " + [Link](10, 20));
[Link]("Sum of 3 integers: " + [Link](5, 10, 15));
[Link]("Sum of 2 doubles: " + [Link](2.5, 3.5));
}
}
Output:
Sum of 2 integers: 30
Sum of 3 integers: 30
Sum of 2 doubles: 6.0
Explanation:
The add() method is declared three times, but with different parameter lists.
When you call add(10,20), the compiler invokes the version that matches two integers.
Java resolves these calls at compile-time, not runtime.
Conclusion:
Method overloading enhances program flexibility and allows the same operation to handle multiple data
types. It is one of the most fundamental examples of polymorphism in Java.
1. Discuss various Layout Managers
In Java Swing and AWT, Layout Managers are used to control the positioning and sizing of GUI components
within a container such as JFrame or JPanel. They automatically adjust component alignment when the
window is resized or new components are added. Java provides several built-in layout managers in the
[Link] package.
Types of Layout Managers:
FlowLayout:
Places components in a single row from left to right, wrapping to the next line if needed.
Default layout for JPanel.
setLayout(new FlowLayout());
BorderLayout:
Divides the container into five regions: NORTH, SOUTH, EAST, WEST, CENTER.
Default layout for JFrame.
add(button1, [Link]);
GridLayout:
Arranges components in a grid of rows and columns.
setLayout(new GridLayout(2, 3));
CardLayout:
Allows switching between multiple panels like flipping through cards.
Useful for wizard-based interfaces.
BoxLayout:
Arranges components either vertically or horizontally.
Null Layout:
Components are placed manually using setBounds().
setLayout(null);
Each layout manager is designed for specific GUI needs, ensuring platform-independent, flexible, and
resizable user interfaces.
2. Explain the life cycle of a thread. Write a Java program to implement thread priorities
A thread in Java is a lightweight subprocess that allows concurrent execution of two or more parts of a
program. The life cycle of a thread represents the various states a thread goes through during its execution.
Thread Life Cycle States:
New: Thread is created but not yet started.
Runnable: Thread is ready to run and waiting for CPU time.
Running: Thread scheduler selects it for execution.
Blocked/Waiting: Thread is temporarily inactive (e.g., waiting for I/O).
Terminated: Thread completes its execution or is stopped.
Program Demonstrating Thread Priorities:
class MyThread extends Thread {
public void run() {
[Link]("Running: " + [Link]().getName());
[Link]("Priority: " + [Link]().getPriority());
}
}
public class ThreadLifeCycle {
public static void main(String args[]) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
[Link](Thread.MIN_PRIORITY);
[Link](Thread.NORM_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();
[Link]();
}
}
Explanation:
Each thread displays its priority. The thread scheduler gives preference to higher-priority threads, though
execution order may vary by OS.
3. What is multithreading? Describe two ways to create a thread in Java
Multithreading is the ability of a program to perform multiple tasks simultaneously within a single process.
Each task is called a thread, and multiple threads share the same memory space but execute independently. It
enhances CPU utilization and responsiveness in real-time applications.
Advantages of Multithreading:
Better resource utilization.
Faster execution.
Simplifies complex programs.
Enables concurrent I/O operations.
Two Ways to Create Threads in Java:
By Extending the Thread Class:
class MyThread extends Thread {
public void run() {
[Link]("Thread running...");
}
}
public class ThreadExample {
public static void main(String args[]) {
MyThread t = new MyThread();
[Link]();
}
}
The run() method defines thread logic.
The start() method begins execution.
By Implementing Runnable Interface:
class MyRunnable implements Runnable {
public void run() {
[Link]("Runnable thread running...");
}
}
public class RunnableExample {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
[Link]();
}
}
Runnable is preferred when a class needs to extend another class, promoting multiple inheritance through
interfaces.
🔹
1. Difference between final keyword and finalize() method in Java
Final Keyword
The final keyword is a modifier that can be applied to variables, methods, and classes.
Once a final variable is initialized, its value cannot be changed.
A final method cannot be overridden by subclasses.
A final class cannot be inherited (no subclass can be created).
Examples:
final int MAX = 100; // final variable
final class Vehicle { } // final class
final void display() { } // final method
🔹 Finalize() Method
finalize() is a method defined in the Object class.
It is called just before an object is garbage collected.
It’s used to perform cleanup operations such as closing files or releasing memory.
Example:
class Test {
protected void finalize() {
[Link]("Finalize method called before object destruction.");
}
public static void main(String[] args) {
Test obj = new Test();
obj = null; // eligible for garbage collection
[Link](); // manually call garbage collector
}
}
Comparison Table:
Feature final Keyword finalize() Method
Type Keyword (modifier) Method
Restricts Cleans resources before object
Purpose
access/modification destruction
Variables, Methods,
Used with Objects
Classes
Time of
Compile time Runtime
use
Defined in Language syntax [Link] class
Example final int x = 10; protected void finalize()
🔹
2. Java API Packages
Definition:
Java API (Application Programming Interface) is a library of predefined classes, interfaces, and methods
provided by Java to simplify development.
🔹
They are grouped into packages.
Common Packages:
Package Description Example Classes
[Link] Core classes – automatically imported. Math, String, Object, System
Utility classes for data structures, date, and
[Link] Scanner, ArrayList, HashMap, Date
collections.
[Link] Input/Output classes for file handling. File, BufferedReader, PrintWriter
[Link] Abstract Window Toolkit for GUI. Button, Label, Frame
[Link] GUI components (advanced AWT). JButton, JLabel, JFrame, JPanel
[Link] Used for creating applets. Applet
🔹
[Link] Networking support. Socket, URL, ServerSocket
User-defined Packages:
You can create your own packages using the package keyword.
package mypack;
public class Hello {
public void msg() { [Link]("Hello from mypack!"); }
}
To use it:
import [Link];
🔹
3. Applet and Applet Life Cycle
Definition:
An applet is a small Java program that runs inside a web browser or applet viewer.
🔹
It is mainly used for interactive web applications.
Applet Class Hierarchy:
🔹
Object → Component → Container → Panel → Applet
Applet Life Cycle Methods:
Method Description
init() Initializes applet, called once when loaded.
start() Called after init(); used to start tasks like animations.
paint(Graphics g) Displays content on the screen.
Called when user leaves the page. Suspends the
stop()
applet.
Method Description
Called when applet is terminated, used to free
destroy()
resources.
Example:
import [Link].*;
import [Link].*;
public class HelloApplet extends Applet {
public void paint(Graphics g) {
[Link]("Welcome to Java Applet!", 50, 50);
}
}
HTML File:
<applet code="[Link]" width="300" height="150"></applet>
Diagram:
init() → start() → paint()
↑ ↓
stop() ← destroy()
🔹
4. Platform Independence
Meaning:
Java is platform-independent because the same program can run on any operating system without
modification.
🔹
This is achieved through Bytecode and Java Virtual Machine (JVM).
How it Works:
Java Compiler (javac) converts .java → .class (Bytecode).
Bytecode is universal, not specific to any OS.
JVM on each platform interprets the bytecode into machine code.
Diagram:
Source Code (.java)
↓
Compiler (javac)
↓
Bytecode (.class)
↓
🔹
JVM (Windows/Linux/Mac)
Advantages:
Write Once, Run Anywhere.
No recompilation needed for different platforms.
High portability.
5. Difference between Overloading and Overriding
Feature Method Overloading Method Overriding
Same method name with different Same method name and parameters but defined in
Definition
parameter list. subclass.
Type Compile-time polymorphism. Runtime polymorphism.
Inheritance Not required. Requires inheritance.
Parameters Must differ (type, number, or order). Must be identical.
Return type Can differ (if covariant). Must be same or covariant.
Access
Can be changed (widened). Cannot reduce visibility.
modifier
Example:
// Overloading
class MathOp {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}
// Overriding
class Animal {
void sound() { [Link]("Animal sound"); }
}
class Dog extends Animal {
void sound() { [Link]("Bark"); } // override
}
6. Explain different types of inheritance in Java with examples
Java supports several types of inheritance:
Type Description Example
Single Inheritance One class inherits from another. class B extends A {}
Multilevel
A class is derived from another derived class. A → B → C
Inheritance
Hierarchical
Multiple classes inherit from one base class. A → B and A → C
Inheritance
Combination of two or more types (achieved
Hybrid Inheritance interface A, B; class C implements A, B {}
using interfaces).
Multiple Inheritance Achieved through interfaces, not classes. class C implements A, B {}
7. Difference between Abstract Class and Interface
Feature Abstract Class Interface
A class that can have both abstract and
Definition A collection of abstract methods and constants.
concrete methods.
Keyword Abstract interface
Can have abstract and non-abstract All methods are abstract (Java 7) or can have
Methods
methods. default/static methods (Java 8+).
Variables Can have instance and static variables. Only public static final constants.
Inheritance A class can extend only one abstract class. A class can implement multiple interfaces.
When classes share a common base with When classes share only method signatures (no
Use
some implementation. implementation).
Example:
abstract class Animal {
abstract void sound();
}
interface Pet {
void play();
}
class Dog extends Animal implements Pet {
void sound() { [Link]("Bark"); }
public void play() { [Link]("Play fetch"); }
}