Unit 1 (10 Marks)
Q1,2,3-Explain Java and its features
Java and its uses
Java is an Object oriented popular programming language and a platform. It is a high level,
robust, object-oriented and secure programming language.
It is a robust technology widely used to develop mobile apps, web apps, desktop apps,
games and much more.
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
It is one of the most popular programming languages in the world
It has a large demand in the current job market
It is easy to learn and simple to use
It is open-source and free
It is secure, fast and powerful
It has huge community support (tens of millions of developers)
Java is an object oriented language which gives a clear structure to programs and allows
code to be reused, lowering development costs.
As Java is close to C++ and C#, it makes it easy for programmers to switch to Java or vice
versa.
Some applications of java are
1.Desktop Applications such as acrobat reader, media player, antivirus, etc
2.Web Applications such as irctc.co.in
3. Enterprise Applications such as banking applications
4.Mobile
5.Embedded System
6.Smart Card
7.Robotics
8.Games, etc.
Features of java
1. Simple:Java is a small and simple language. Java does not use pointers, preprocessor
header files, goto statement and many others. It also eliminates operator overloading and
multiple inheritance. Java is modeled on C and C++ languages. So it is familiar to
programmers.
2. Object-Oriented:Java is an object-oriented programming language. Everything in Java is
an object. Object-oriented means we organize our software as a combination of different
types of objects that include both data and behavior
3. Portable :Portability is a major aspect of the Internet because there are many different
types of computers and operating systems connected to it. If a Java program needs to be
run on virtually any computer connected to the Internet, there needed to be some way to
enable program to execute on different systems. Java ensures portability through 2 types:
a. Bytecode generation (runs on any machine)
b. Machine-independent data type sizes.
4. Platform independent:Java code can be executed on multiple platforms, for example,
Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and
converted into bytecode. This bytecode is a platform-independent code because it can be
run on multiple platforms, i.e., Write Once and Run Anywhere (WORA).
5. Secured:Java provides a secure means of creating internet applications. Java systems
not only verify all memory access but also ensure that no viruses are communicated with an
applet.
6. Robust :It has strict compile time and run time checking for data types. It is designed as a
garbagecollection language relieving programmers of virtually all memory management
problems. Java also includes the concept of exception handling which captures series errors
and eliminates any risk of crashing the system.
7. Architecture neutral: Java is not tied to a specific machine or operating system
architecture. Changes and upgrades in operating systems, processors and system
resources will not force any changes in Java programs
8.Complied and Interpreted: Java supports crossplatform code through the use of Java
bytecode. Byte codes are not machine instructions and therefore, in the second stage, Java
interpreter generates machine code that can be directly executed by the machine that is
running the Java program.
9. High Performance:Java performance is impressive for an interpreted language, mainly
due to the use of intermediate bytecode. Java architecture is also designed to reduce
overheads during runtime. Further, the incorporation of multithreading enhances the over all
execution speed of Java programs.
10. Multithreaded:It means handling multiple task-simultaneously. Java supports
multithreaded programs. This means that we need not wait for the application to finish one
task before beginning another.. This feature greatly improves the interactive performance of
graphical applications.
11. Distributed: Java is designed as a distributed language for creating applications on
networks. It has the ability to share both data and programs. Java applications can open and
access remote objects on Internet as easily as they can do in a local system. This enables
multiple programmers at multiple remote locations to collaborate and work together on a
single project.
12. Dynamic:Java is a dynamic language. Java is capable of dynamically linking in new
class libraries, methods, and objects.Java Programs carry with them large amount of
run-time type information that is used to verify and resolve access to objects at run time.
Q4.What is meant by JDK, JRE and JVM? Differentiate between them?
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it
doesn't physically exist.
It is a specification that provides a runtime environment in which Java bytecode can be
executed.
JVMs are available for many hardware and software platforms (i.e. JVM is platform
dependent).
JRE(Java Runtime Environment). It is also written as Java RTE.
The Java Runtime Environment is a set of software tools which are used for developing Java
applications.
It is used to provide the runtime environment.
It is the implementation of JVM. It physically exists. It contains a set of libraries + other files
that JVM uses at runtime.
JDK(Java Development Kit).
The Java Development Kit (JDK) is a software development environment which is used to
develop Java applications and applets.
It physically exists. It contains JRE + development tools.
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as
an interpreter/loader (java), a compiler (javacetc. to complete the development of a Java
Application.
5. What are Java tokens? List and explain the different types of Java Tokens.
Java Tokens
Java tokens are the smallest units in a Java program that are meaningful to the compiler. When a
Java program is compiled, the source code is broken into these tokens.
There are five primary types of tokens:
1. Keywords
Keywords are reserved words that have predefined meanings in Java. They cannot be used as
variable names, class names, or identifiers.
Examples:
● class, public, static, void
2. Identifiers
Identifiers are the names given to variables, classes, methods, etc. They are created by the
programmer and must follow specific naming rules.
Rules:
● Must start with a letter, $, or _
● Cannot start with a digit
● Cannot use Java keywords
Examples:
● myVariable, EmployeeName, _count
3. Literals
Literals are fixed values assigned to variables. They represent constant values used in the code.
Types of literals:
● Integer literal: 10, -5
● Floating-point literal: 3.14, -0.01
● Character literal: 'A', '9'
● String literal: "Hello", "Java"
● Boolean literal: true, false
4. Operators
Operators are symbols that perform operations on variables and values.
Types of operators:
● Arithmetic (+, -, *, /, %)
● Relational (>, <, ==, !=)
● Logical (&&, ||, !)
● Assignment (=, +=, -=)
● Unary (++, --)
5. Separators
Separators (also called punctuators) are used to define structure and organize code.
Common separators:
● () → parentheses (method calls, grouping)
● {} → braces (blocks)
● [] → brackets (arrays)
● ; → semicolon (end of statement)
● , → comma (separating variables)
● . → dot (accessing members)
6. What is the purpose of data types? Explain the different categories of
data types available in Java programming. (1+2+7) and
12. Explain Java Data Types.
In Java, data types specify the kind of data that a variable can store. They define the size,
nature, and behavior of data used in a Java program. Java is a strongly typed language,
meaning every variable must have a declared data type..
Purpose of Data Types:
● Defining data storage: Data types specify the type of value a variable can hold (e.g.,
integers, floating-point numbers, text, boolean values).
● Memory allocation: They determine how much memory space is allocated to store a
particular value, ensuring efficient memory usage.
● Operation enforcement: Data types dictate which operations can be performed on
the data, preventing type mismatches and ensuring correct calculations.
● Code reliability and efficiency: Using appropriate data types helps write robust and
performant code by ensuring the data is handled correctly.
Categories of Data Types:
Primitive Data Types:]
○ Integers: byte, short, int, long (used to store whole numbers).]
○ Floating-point numbers: float, double (used to store numbers with decimal
points).
○ Characters: char (used to store individual characters, such as letters or
symbols).
○ Booleans: boolean (used to represent true/false values).
Non-Primitive (Reference) Data Types:
○ Arrays: Collections of elements of the same data type.
○ Classes: User-defined blueprints for creating objects, which contain data and
methods.
○ Interfaces: Define a contract for classes to implement, specifying methods
without their implementations.]
○ Strings: Sequences of characters (Java provides a special String class).
7. Define Constants. Explain different types of Constants in Java
A constant in Java is a variable whose value cannot be changed after it has been assigned.
Constants are useful for representing fixed values, such as mathematical constants or
configuration settings. In Java, constants are declared using the final keyword. By
convention, constant names are written in uppercase with underscores separating words.
Types of Constants in Java
● Integer Constants: Represent whole numbers without decimal points.
○ Examples: 10, -5, 0, 123456789
● Floating-Point Constants: Represent numbers with decimal points or in scientific
notation.
○ Examples: 3.14, -0.5, 2.0, 1.23e5
● Character Constants: Represent single characters enclosed in single quotes.
○ Examples: 'A', 'b', '1', '$'
● String Constants: Represent sequences of characters enclosed in double quotes.
○ Examples: "Hello", "Java", "123"
● Boolean Constants: Represent truth values, either true or false.
8.Explain any two/three types of Operators in Java with examples.And
13. What are operators in Java? Explain any 5 with example
In Java, operators are symbols that tell the compiler to perform specific operations on
one, two, or more operands (variables, values, or expressions). Operators are used to
perform tasks such as mathematical calculations, logical evaluations, value
assignments, and comparisons.
1. Arithmetic Operators
These operators are used to perform basic mathematical operations such as addition,
subtraction, multiplication, division, and modulus.
Operator Description Example Result
+ Addition a + b Sum of a and
b
- Subtraction a - b Difference
* Multiplication a * b Product
/ Division a / b Quotient
% Modulus a % b Remainder
Eg-
int a = 20, b = 8;
System.out.println("Addition: " + (a + b)); // 28
System.out.println("Subtraction: " + (a - b)); // 12
System.out.println("Multiplication: " + (a * b)); // 160
System.out.println("Division: " + (a / b)); // 2
System.out.println("Modulus: " + (a % b)); // 4
2. Relational (Comparison) Operators
These operators are used to compare two values. They return a boolean value (true or
false).
Operator Description Example
== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater or a >= b
equal
<= Less or equal a <= b
eg-int x = 10, y = 20;
System.out.println(x == y); // false
System.out.println(x < y); // true
3. Logical Operators
These operators are used to combine multiple conditions (expressions) and return a boolean
result.
Operator Description Example
&& Logical AND a > 5 && a <
15
` `
! Logical NOT (negation) !(a == b)
Eg-
int age = 25;
System.out.println(age > 18 && age < 30); // true
System.out.println(age < 18 || age > 60); // false
System.out.println(!(age == 25)); // false
4. Assignment Operators
Used to assign values to variables.
Operator Description Example
= Assign value a = 10
+= Add and assign a += 5
-= Subtract and a -= 2
assign
*= Multiply and assign a *= 3
/= Divide and assign a /= 2
Eg-
int a = 10;
a += 5; // a becomes 15
System.out.println(a); // Output: 15
5. Unary Operators
Operate on a single operand.
Operator Description Example Result
+ Unary plus +a +a
- Unary minus -a -a
++ Increment a++ or a+1
++a
-- Decrement a-- or a-1
--a
! Logical NOT !true false
Eg-
int a = 5;
System.out.println(++a); // Output: 6
9. Explain if statement, if…else statement and nested if statement with syntax
and example.
1. if Statement in Java
The if statement is used to execute a block of code only when a given condition is true.
Syntax:
if (condition) {
// statements to execute if condition is true
}
Eg-
int age = 20;
if (age >= 18) {
System.out.println("You are eligible to vote.");
}
2. if-else Statement in Java
The if-else statement is used to choose between two blocks of code, depending on
whether a condition is true or false
Syntax:
if (condition) {
// statements if condition is true
} else {
// statements if condition is false
}
Eg-
int number = 5;
if (number % 2 == 0) {
System.out.println("Even number");
} else {
System.out.println("Odd number");
}
Nested if Statement in Java
A nested if is an if statement inside another if or else block. It is used to check multiple
conditions.
Syntax:
if (condition1) {
if (condition2) {
// statements if both condition1 and condition2 are true
} else {
// statements if condition1 is true but condition2 is false
}
} else {
// statements if condition1 is false
}
Eg-
int a = 10, b = 20, c = 15;
if (a > b) {
if (a > c) {
System.out.println("a is the largest");
} else {
System.out.println("c is the largest");
}
} else {
if (b > c) {
System.out.println("b is the largest");
} else {
System.out.println("c is the largest");
}
}
if (condition1) {
if (condition2) {
// statements if both condition1 and condition2 are true
} else {
// statements if condition1 is true but condition2 is false
}
} else {
// statements if condition1 is false
}
10.With syntax and example explain 3 types of iterative statements.
Iterative Statements in Java
Iterative statements allow you to execute a block of code repeatedly as long
as a specified condition is true. Java supports three primary types of loops:
1. for Loop
The for loop is used when the number of iterations is known in advance.
Syntax:
for (initialization; condition; update) {
// statements to be executed
}
Eg:
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
2. while Loop
The while loop is used when the condition is checked before the loop
executes. It is ideal for situations where the number of iterations is not
known beforehand.
Syntax:
while (condition) {
// statements to be executed
}
Eg:
int i = 1;
while (i <= 5) {
System.out.println("Value: " + i);
i++;
}
3. do-while Loop
The do-while loop is used when the loop body should execute at least
once, regardless of the condition.
syntax:
do {
// statements to be executed
} while (condition);
Eg:
int i = 1;
do {
System.out.println("Number: " + i);
i++;
} while (i <= 5);
11. With a neat labelled diagram, explain the working of JVM.
JVM (Java Virtual Machine) Working
The Java Virtual Machine (JVM) is a crucial component of the Java Runtime
Environment (JRE). It provides a platform-independent environment for
running Java bytecode. Here's a simplified overview of how the JVM works:
Loading and Execution
1. Class Loading: The JVM loads the .class file into memory.
2. Verification: The JVM checks the loaded class for security and integrity.
3. Initialization: The JVM initializes static variables and executes static blocks.
4. Method Execution: The JVM executes the main method, which calls other
methods.
Memory Management
1. Method Area: Stores class metadata, such as method code and static
variables.
2. Heap: Stores objects created by the application.
3. Stack: Stores method call stack frames, including local variables and
method parameters.
4. Native Method Stack: Stores native method calls.
Garbage Collection
The JVM periodically performs garbage collection to:
1. Identify unreachable objects: Determine which objects are no longer
referenced.
2. Reclaim memory: Free the memory occupied by unreachable objects.
Key Benefits
1. Platform independence: Java code can run on any platform with a JVM.
2. Memory management: The JVM manages memory allocation and
deallocation.
3. Security: The JVM provides a sandboxed environment for running Java
code.
The JVM's working ensures that Java code is executed efficiently, securely,
and independently of the underlying platform.
14. What are arrays? Explain different types of arrays in Java with
example?
Arrays in Java are used to store multiple values of the same data type in a
single variable. Java supports both one-dimensional (1D) and
two-dimensional (2D) arrays.
🔷 Characteristics of Arrays in Java:
● Fixed size (declared at creation)
● Can store primitive data types or objects
● Elements are accessed using indices (starting from 0)
● Stored in contiguous memory locations
1. One-Dimensional Array (1D)
A single row of elements. Ideal for simple lists or sequences.
Syntax:
int[] arr = new int[5]; // Declaration
arr[0] = 10; // Assignment
Example:
int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers[2]); // Output: 30
2. Two-Dimensional Array (2D)
Used to store data in rows and columns (like a matrix or table).
Syntax:
int[][] matrix = new int[2][3]; // 2 rows, 3 columns
Example:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(matrix[1][2]); // Output: 6
15. What are control statements in Java? Explain
Control statements in Java are used to control the flow of execution of a
program. They help decide which part of the code to execute, how many
times to execute, or when to stop execution based on certain conditions.
They are essential for implementing decision-making, looping, and
branching logic.
1. Decision-Making Statements
Used to execute a block of code only if a condition is true, or choose
between multiple conditions.
Examples:
● if
● if-else
● if-else-if
● switch
2. Looping (Iterative) Statements
Used to repeat a block of code multiple times.
Types:
● for loop
● while loop
● do-while loop
3. Branching Statements
Used to alter the normal flow of control (exit a loop early, skip to the next
iteration, or return from a method).
Types:
● break – exits the loop/switch
● continue – skips to the next loop iteration
● return – exits from a method
Unit 1(15 Mark)
1.With a neat diagram explain the structure of Java programming with
example
The structure of a Java program consists of several key components,
organized in a specific order. These components, when combined, form a
complete and executable Java program.
● Documentation Section: This section includes comments that describe the purpose
of the program, author information, or any other relevant details. Comments are
ignored by the compiler and are used for documentation purposes.
● Package Statement: This statement declares the package to which the class
belongs. Packages are used to organize classes into namespaces, preventing naming
conflicts and improving code maintainability.
● Import Statements: These statements import classes or interfaces from other
packages, allowing the current class to use them.
● Interface Section: This section defines interfaces, which specify a contract for
classes to implement. Interfaces declare methods without providing their
implementation.
● Class Definition: This is the core of the program, where the class is defined. It
includes the class name, variables (data members), and methods (functions).
● Main Method Definition: The main method definition includes the method signature
(public static void main(String[] args)) and the code block that contains the program's
logic.
2. What is the purpose of data types? Explain the different categories of
data types available in Java programming. (1+2+12)
In Java, data types specify the kind of data that a variable can store. They define the size,
nature, and behavior of data used in a Java program. Java is a strongly typed language,
meaning every variable must have a declared data type..
Purpose of Data Types:
● Defining data storage: Data types specify the type of value a variable can hold (e.g.,
integers, floating-point numbers, text, boolean values).
● Memory allocation: They determine how much memory space is allocated to store a
particular value, ensuring efficient memory usage.
● Operation enforcement: Data types dictate which operations can be performed on
the data, preventing type mismatches and ensuring correct calculations.
● Code reliability and efficiency: Using appropriate data types helps write robust and
performant code by ensuring the data is handled correctly.
Categories of Data Types:
Primitive Data Types:]
○ Integers: byte, short, int, long (used to store whole numbers).]
○ Floating-point numbers: float, double (used to store numbers with decimal
points).
○ Characters: char (used to store individual characters, such as letters or
symbols).
○ Booleans: boolean (used to represent true/false values).
Non-Primitive (Reference) Data Types:
○ Arrays: Collections of elements of the same data type.
○ Classes: User-defined blueprints for creating objects, which contain data and
methods.
○ Interfaces: Define a contract for classes to implement, specifying methods
without their implementations.]
○ Strings: Sequences of characters (Java provides a special String class).
3. Explain any 4 types of Operators in Java with examples. (4+4+4+3)
In Java, operators are symbols that tell the compiler to perform specific operations on
one, two, or more operands (variables, values, or expressions). Operators are used to
perform tasks such as mathematical calculations, logical evaluations, value
assignments, and comparisons.
1. Arithmetic Operators
These operators are used to perform basic mathematical operations such as addition,
subtraction, multiplication, division, and modulus.
Operator Description Example Result
+ Addition a + b Sum of a and
b
- Subtraction a - b Difference
* Multiplication a * b Product
/ Division a / b Quotient
% Modulus a % b Remainder
Eg-
int a = 20, b = 8;
System.out.println("Addition: " + (a + b)); // 28
System.out.println("Subtraction: " + (a - b)); // 12
System.out.println("Multiplication: " + (a * b)); // 160
System.out.println("Division: " + (a / b)); // 2
System.out.println("Modulus: " + (a % b)); // 4
2. Relational (Comparison) Operators
These operators are used to compare two values. They return a boolean value (true or
false).
Operator Description Example
== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater or a >= b
equal
<= Less or equal a <= b
eg-int x = 10, y = 20;
System.out.println(x == y); // false
System.out.println(x < y); // true
3. Logical Operators
These operators are used to combine multiple conditions (expressions) and return a boolean
result.
Operator Description Example
&& Logical AND a > 5 && a <
15
` `
! Logical NOT (negation) !(a == b)
Eg-
int age = 25;
System.out.println(age > 18 && age < 30); // true
System.out.println(age < 18 || age > 60); // false
System.out.println(!(age == 25)); // false
4. Assignment Operators
Used to assign values to variables.
Operator Description Example
= Assign value a = 10
+= Add and assign a += 5
-= Subtract and a -= 2
assign
*= Multiply and assign a *= 3
/= Divide and assign a /= 2
Eg-
int a = 10;
a += 5; // a becomes 15
System.out.println(a); // Output: 15
4. With syntax and example explain different types of decision making
and branching statements [ if, if…else, nested if…else and switch
statement] (2+3+5+5)
decision making statementsUsed to execute a block of code only if a
condition is true, or choose between multiple conditions.There re mainly 4
types of decision statements
1. if Statement in Java
The if statement is used to execute a block of code only when a given condition is true.
Syntax:
if (condition) {
// statements to execute if condition is true
}
Eg-
int age = 20;
if (age >= 18) {
System.out.println("You are eligible to vote.");
}
2. if-else Statement in Java
The if-else statement is used to choose between two blocks of code, depending on
whether a condition is true or false
Syntax:
if (condition) {
// statements if condition is true
} else {
// statements if condition is false
}
Eg-
int number = 5;
if (number % 2 == 0) {
System.out.println("Even number");
} else {
System.out.println("Odd number");
}
Nested if Statement in Java
A nested if is an if statement inside another if or else block. It is used to check multiple
conditions.
Syntax:
if (condition1) {
if (condition2) {
// statements if both condition1 and condition2 are true
} else {
// statements if condition1 is true but condition2 is false
}
} else {
// statements if condition1 is false
}
Eg-
int a = 10, b = 20, c = 15;
if (a > b) {
if (a > c) {
System.out.println("a is the largest");
} else {
System.out.println("c is the largest");
}
} else {
if (b > c) {
System.out.println("b is the largest");
} else {
System.out.println("c is the largest");
}
}
if (condition1) {
if (condition2) {
// statements if both condition1 and condition2 are true
} else {
// statements if condition1 is true but condition2 is false
}
} else {
// statements if condition1 is false
}
Switch Statement
Used to select one of many possible blocks of code to be executed, depending on the
value of a variable.
Syntax:
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
...
default:
// default block
}
Eg:
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
5. Define 1 dimensional and 2 dimensional arrays. With syntax
and example explain how 1D and 2D arrays are declared
initialized and accessed.
Arrays in Java are used to store multiple values of the same data type in a
single variable. Java supports both one-dimensional (1D) and
two-dimensional (2D) arrays.
🔷 Characteristics of Arrays in Java:
● Fixed size (declared at creation)
● Can store primitive data types or objects
● Elements are accessed using indices (starting from 0)
● Stored in contiguous memory locations
1. One-Dimensional Array (1D)
A single row of elements. Ideal for simple lists or sequences.
Syntax:
// Declaration
int[] arr;
// Memory Allocation
arr = new int[5];
// Declaration + Initialization
int[] arr = {10, 20, 30, 40, 50};
Example:
int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers[2]); // Output: 30
2. Two-Dimensional Array (2D)
Used to store data in rows and columns (like a matrix or table).
Syntax:
// Declaration
int[][] matrix;
// Memory Allocation
matrix = new int[2][3]; // 2 rows, 3 columns
// Declaration + Initialization
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
Example:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(matrix[1][2]); // Output: 6
6. Explain Java Data Types with example for each?
In Java, data types specify the kind of data that a variable can store. They define the size,
nature, and behavior of data used in a Java program. Java is a strongly typed language,
meaning every variable must have a declared data type..
Primitive Data Types
These are basic built-in types and are not objects. There are 8 primitive data types in
Java:
🔹 a) Integer Types
Data Type Size Range Example
short 2 -32,768 to 32,767 short b = 30000;
bytes
int 4 -2^31 to 2^31 - 1 int c = 123456;
bytes
long 8 -2^63 to 2^63 - 1 long d =
bytes 1234567890L;
🔹 b) Floating-Point Types
Data Type Size Description Example
float 4 Single precision float pi =
bytes 3.14f;
double 8 Double precision double e =
bytes 2.71828;
🔹 c) Character Type
Data Type Size Description Example
char 2 Stores a single char ch =
bytes character 'A';
🔹 d) Boolean Type
Data Type Size Description Example
boolean 1 bit Stores true or boolean flag =
false true;
7. Explain various control statements in Java with examples.
Control statements in Java are used to control the flow of execution of a
program. They help decide which part of the code to execute, how many
times to execute, or when to stop execution based on certain conditions.
They are essential for implementing decision-making, looping, and
branching logic.
1. Decision-Making Statements
Used to execute a block of code only if a condition is true, or choose
between multiple conditions.
Examples:
● if
● if-else
● if-else-if
● switch
2. Looping (Iterative) Statements
Used to repeat a block of code multiple times.
Types:
● for loop
● while loop
● do-while loop
3. Branching Statements
Used to alter the normal flow of control (exit a loop early, skip to the next
iteration, or return from a method).
Types:
● break – exits the loop/switch
● continue – skips to the next loop iteration
● return – exits from a method
Unit 2
16.Explain the class and object in Java with example.&
17. With programming example explain class and object in
Java(10marks)
8. With an example program, explain the concept of classes and objects
in Java. How are they created and accessed?(15marks)
An object is an instance of a class . A class is a template or blueprint from
which objects are created .It can be physical
An object has three characteristics:
• State: Represents the data (value) of an object.
• Behavior: Represents the behavior (functionality) of an object such as
deposit, withdraw, etc.
• Identity: An object identity is typically implemented via a unique ID.
For Example, Pen is an object . Its name is Reynolds ; color is white, known
as its state . It is used to write, so writing is its behavior .
A class is a group of objects which have common properties. It is a template
or blueprint from which objects are created. It is a logical entity. It can't be
physical.
A class in Java can contain:
• Fields
• Methods
• Constructors
• Blocks
• Nested class and interface
Example program:
class Student {
int id = 21510;
String name = "Advaith";
public static void main(String[] args) {
Student s1 = new Student(); // Creating an object of Student
System.out.println("The Registration id of the student: " + s1.id);
System.out.println("The Name of the student is :" + s1.name);
18. What are classes? How do you declare a class in Java? Explain each
term in it.(2+3+5)
A class is a group of objects which have common properties. It is a template
or blueprint from which objects are created. It is a logical entity. It can't be
physical.
Field Declaration
Data is encapsulated in a class by placing data fields inside the body of the
class definition.
datatype fieldname ;
For example :
class Rectangle
{
int length ;
int width ;
}
Method Declaration
Methods are declared inside the body of the class but immediately after the
declaration of instance variables
class Rectangle
int length ; //Declaration of field
int width ; 12 //Declaration of field
int rectArea() //Declaration of method
{
int area = length * width ;
return (area) ;
}
}
19. What are constructors? Explain its types with example(10marks)
9. Discuss the concept of constructors. Explain how they are used to
initialize objects. Provide examples to illustrate the use of constructors
in Java.
10. What are constructors? Explain types of constructors with
examples.(15 marks)
• Constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling the constructor, memory
for the object is allocated in the memory. It is a special type of method that is
used to initialize the object. Every time an object is created using the new
keyword, at least one constructor is called.
Types of Java constructors
1.Default constructor (no-arg constructor)
A constructor is called "Default Constructor" when it doesn't have any
parameter
Eg:
class Bike1 {
Bike1() {
System.out.println("Bike is created");
}
public static void main(String args[]) {
Bike1 b = new Bike1();
}
}
2.Parameterized constructor
A constructor which has a specific number of parameters is called a
parameterized constructor.
Eg:
class Student {
int id;
String name;
Student(int i, String n) {
id = i;
name = n;
}
void display() {
System.out.println(id + " " + name);
}
public static void main(String args[]) {
Student s1 = new Student(111, "Karan");
Student s2 = new Student(222, "Aryan");
s1.display();
s2.display();
}
}=
20. What is inheritance? Explain its types.
21. What is inheritance? What are its advantages and disadvantages?
22. What is inheritance? Explain the different forms of inheritance.
23. Explain the concept of inheritance in Java
24. Explain single and multi level inheritance with example.
25. Explain single and hierarchical inheritance with example.
26. With example, explain multilevel and hierarchical inheritance.(10
mark)
11. What is inheritance? Explain the different forms of inheritance. (15
mark)
Inheritance
• Reusability is the another aspect of OOP paradigm. Java supports this
concept.
• This is basically done by creating new classes, reusing the properties of
existing ones.
• The mechanism of deriving a new class from an old one is called inheritance.
• The old class is known as base class, super class or parent class.
• The new one is called the subclass, derived class or child class.
• The inheritance allows subclasses to inherit all the variables and methods of
their parent classes.
• The keyword extends signifies that the properties of the super class name
are extended to the subclass name.
• The subclass will now contain its own variables and methods as well as
those of the super class.
• This kind of situation occurs when we want to add some more properties to
an existing class without actually modifying it.
Advantages Of Inheritance in Java:
Code Reusability
Abstraction
Class Hierarchy
Polymorphism
Disadvantages Of Inheritance in Java:
Complexity
Tight Coupling
Types of inheritance
1. Single inheritance (only one super class)
2. Multilevel inheritance (derived from a derived class)
3. Hierarchical inheritance (one super class, many subclasses)
4. Multiple inheritance (several super class)
5. Hybrid inheritance (combination of different types of inheritance)
Single Inheritance:
• When a class inherits another class, it is known as a single inheritance.
• For example Dog class inherits the Animal class, so there is the single
inheritance.
class Animal
{
void eat()
{
System.out.println("Animal is eating");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("Dog is barking");
}
}
public class Example
{ public static void main(String[] args)
{ Dog dog = new Dog(); dog.eat(); // inherited method dog.bark(); // method of
child class }
}
Multilevel Inheritance:
• In Multilevel Inheritance, a derived class will be inheriting a base class, and
as well as the derived class also acts as the base class for other classes.
class Animal
{
void eat()
{
System.out.println("Animal is eating");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("Dog is barking");
}
}
class Labrador extends Dog
{
void color()
{
System.out.println("Labrador is brown");
}
}
public class Example
{
public static void main(String[] args)
{
Labrador labrador = new Labrador();
labrador.eat(); // inherited from Animal
labrador.bark(); // inherited from Dog
labrador.color(); // method of Labrador
}
}
Hierarchical Inheritance:
• In Hierarchical Inheritance, one class serves as a superclass (base class) for
more than one subclass.
class Shape
{
void draw()
{
System.out.println("Drawing a shape");
}
}
class Circle extends Shape
{
void draw()
{
System.out.println("Drawing a circle");
}
}
class Rectangle extends Shape
{
void draw()
{
System.out.println("Drawing a rectangle");
}
} class Triangle extends Shape
{
void draw()
{
System.out.println("Drawing a triangle");
}
}
public class Example
{
public static void main(String[] args)
{
Shape circle = new Circle();
Shape rectangle = new Rectangle();
Shape triangle = new Triangle();
circle.draw();
rectangle.draw();
triangle.draw();
}
}
Multiple Inheritance (Through Interfaces)
• In Multiple inheritances, one class can have more than one superclass and
inherit features from all parent classes.
• Please note that Java does not support multiple inheritances with classes.
• In Java, we can achieve multiple inheritances only through Interfaces
interface Vehicle {
void start();
void stop();
}
interface ElectronicDevice {
void turnOn();
void turnOff(); }
class Car implements Vehicle, ElectronicDevice {
public void start() {
System.out.println("Car starting"); }
public void stop() {
System.out.println("Car stopping"); }
public void turnOn() {
System.out.println("Car turning on"); }
public void turnOff() {
System.out.println("Car turning off");
}}
// example of Multiple inheritance
public class Example {
public static void main(String[] args) {
Car car = new Car();
car.start();
car.stop();
car.turnOn();
car.turnOff();
}
}
Hybrid Inheritance(Through Interfaces):
• It is a mix of two or more of the other types of inheritance.
• Since Java support classes, multiple hybrid doesn’t with is also not possible
with inheritances inheritance classes.
• In Java, we can achieve hybrid inheritance only through Interfaces.
27. What is the difference between method overloading and method
overriding?
28. What is method overloading? Explain with example.
29. What is method overriding? Explain with example.(10 mark)
12. Explain method overloading and method overriding in java, providing
programming examples for each.(15 mark)
Method Overriding
• If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in Java.
• In method overriding, the derived class provides the specific implementation
of the method that is already provided by the base class or parent class.
• In method overriding, the return type must be the same or covariant (return
type may vary in the same direction as the derived class).
Eg:
class Shape
{
void draw()
{
System.out.println("Drawing a shape");
}
}
class Circle extends Shape
{
void draw()
{
System.out.println("Drawing a circle");
}
}
public class Main { public static void main(String[] args)
{
Shape shape = new Shape();
shape.draw();
Circle circle = new Circle();
circle.draw();
}
}
Output:
Drawing a shape
Drawing a circle
Method Overloading
• If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
• In method overloading, more than one method shares the same method
name with a different signature in the class.
• In method overloading, the return type can or can not be the same, but we
have to change the parameter because, in java, we can not achieve the
method overloading by changing only the return type of the method.
import java.io.*;
class MethodOverloadingEx {
static int add(int a, int b)
{
return a + b;
} static int add(int a, int b, int c)
{
return a + b + c;
}
public static void main(String args[])
{
System.out.print(" a+b = ");
System.out.println(add(4, 6));
System.out.print(" a+b+c = ");
System.out.println(add(4, 6, 7));
}
}
OUTPUT
a+b = 10
a+b+c = 17
30. What is exception handling? Why do exceptions occur?
31. What is exception? Explain the methods to handle it.
32. Explain the different types of exception handling methods in java.(10
mark)
13. Explain the types of exceptions in detail with example code for each.
14. Explain the methods of handling exceptions in Java with appropriate
programming example for each.(15 mark)
Java exceptions
● When executing Java code, different errors can occur:
○ coding errors made by the programmer
○ errors due to wrong input
○ or other unforeseeable things
● When an error occurs, Java will normally stop and generate an error
message.
● The technical term for this is: Java will throw an exception (throw an error). ●
When an exception occurs within a method, it creates an object.
● This object is called the exception object.
● It contains information about the exception, such as the name and
description of the exception and the state of the program when the exception
occurred.
Major reasons why an exception Occurs
● Code errors
● Invalid user input
● Device failure
● Loss of network connection
● Physical limitations (out of disk memory)
● Opening an unavailable file
● Exception Handling in Java is one of the effective means to handle the
runtime errors so that the regular flow of the application can be preserved.
● In java there are three methods to handle the exceptions
● They are
* try-catch
* finally
* throw
try and catch
● The try statement allows you to define a block of code to be tested for errors
while it is being executed.
● The catch statement allows you to define a block of code to be executed, if
an error occurs in the try block.
● The try and catch keywords come in pairs
● Syntax
try {
// Block of code to try
}
catch(Exception e)
{
// Block of code to handle errors
};
Finally
•The finally statement lets you execute code, after try...catch, regardless of the
result
•The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
The throw keyword
● The "throw" keyword is used to throw an exception.
● The throw statement allows you to create a custom error.
● The throw statement is used together with an exception type.
● There are many exception types available in Java:
○ ArithmeticException
○ FileNotFoundException
○ ArrayIndexOutOfBoundsException
○ SecurityException, etc
33. What is an Applet? Explain the life cycle of an Applet.
34. What is an Applet? Explain its programming example. Explain types
of Applet.(10 mark)
15. With a programming example, explain Applet and its features.
Explain its life cycle.(15 mark)
● Applet is a special type of program that is embedded in the webpage to
generate the dynamic content. It runs inside the browser and works at client
side.
● An applet is a Java class that extends the java.applet.Applet (or
java.applet.*) class.
● A main() method is not invoked on an applet, and an applet class will not
define main().
● Applets are designed to be embedded within an HTML page.
● It is used to make the website more dynamic and entertaining
When an applet begins, the following methods are called, in this sequence:
● init( )
● start( )
● paint( )
When an applet is terminated, the following sequence of method calls takes
place:
● stop( )
● destroy( )
1. init( ) : The init( ) method is the first method to be called. This is where you
should initialize variables. This method is called only once during the run time
of your applet.
2. start( ) : The start( ) method is called after init( ). It is also called to restart
an applet after it has been stopped. Note that init( ) is called once i.e. when
the first time an applet is loaded whereas start( ) is called each time an
applet’s HTML document is displayed onscreen. So, if a user leaves a web
page and comes back, the applet resumes execution at start( ).
3. paint( ) : Invoked immediately after the start() method, and also any time the
applet needs to repaint itself in the browser. The paint() method is actually
inherited from the java.awt. The paint() has one parameter of type graphics.
This is used whenever output to the applet is required.
4. stop( ) : The stop( ) method is called when a web browser leaves the HTML
document containing the applet—when it goes to another page, for example.
When stop( ) is called, the applet is probably running. You should use stop( )
to suspend threads that don’t need to run when the applet is not visible. You
can restart them when start( ) is called if the user returns to the page.
5. destroy( ) : The destroy( ) method is called when the environment
determines that your applet needs to be removed completely from memory. At
this point, you should free up any resources the applet may be using. The
stop( ) method is always called before destroy( ).
// Overriding paint() method
public void paint(Graphics g)
g.drawString("Hello World", 20, 20);
HTML code:
<html>
<body>
<applet code="HelloWorldApplet.class" width="200"
height="200">
</applet>
</body>
</html>
There are 2 Types of applet
1. Local Applet
● Local Applet is developed locally and stored in the local system.
● A web page doesn't need the get the information from the internet when it
finds the local Applet in the system.
● It is specified or defined by the file name or pathname.
● There are two attributes used in defining an applet, i.e., the codebase that
specifies the path name and code that defined the name of the file that
contains Applet's code.
2. Remote Applet
● A remote applet is designed and developed by another developer.
● It is located or available on a remote computer that is connected to the
internet.
● In order to run the applet stored in the remote computer, our system is
connected to the internet then we can download run it.
● In order to locate and load a remote applet, we must know the applet's
address on the web that is referred to as Uniform Resource Locator(URL).
Unit 3
35. Explain thread with its example. Also explain the benefits of thread.
(6+4)
36. Explain threads. Explain its life cycle
38. Describe the life cycle of a thread in Java. Explain each phase in
detail(10 mark)
19. Discuss the different states in the life cycle of a thread in Java.
Explain each state in detail with suitable examples.(15 mark)
Threads in Java
• A Thread is a very light-weighted process.
• It is the smallest part of the process that allows a program to operate more
efficiently by running multiple tasks simultaneously.
• In order to perform complicated tasks in the background, we used the
Thread concept in Java.
• All the tasks are executed without affecting the main program. • In a program
or process, all the threads have their own separate path for execution, so
each thread of a process is independent.
Benefits of threads
1.Java Threads are lightweight compared to processes, it takes less time and
resource to create a thread.
2.Threads in Java provide a powerful mechanism for building responsive,
scalable, and efficient concurrent applications.
3.Threads share their parent process data and code Context switching
between threads is usually less expensive than between processes.
4.Thread intercommunication is relatively easy than process communication.
By using threads, applications can remain responsive to user input even while
performing lengthy operations in the background.
5.Threads allow multiple tasks to be executed concurrently, improving the
performance of applications by utilizing available resources more efficiently
New
• By default, a Thread will be in a new state, in this state, code has not
yet been run and the execution process is not yet initiated.
• It remains in this state until we start it using the start() method.
Runnable State
• A thread in the runnable state is prepared to execute the code. When a
new thread's start() function is called, it enters a runnable state.
• In the runnable environment, the thread is ready for execution and is
awaiting the processor's availability (CPU time). That is, the thread has
entered the queue (line) of threads waiting for execution.
• Threads in this state are either running or ready to run, but they’re
waiting for resource allocation from the system.
Running State
• Running implies that the processor (CPU) has assigned a time slot to
the thread for execution. When a thread from the runnable state is
chosen for execution by the thread scheduler, it joins the running state.
• When the thread gets the CPU, it moves from the runnable to the
running state. Generally, the most common change in the state of a
thread is from runnable to running and again back to runnable.
• In the running state, the processor allots time to the thread for
execution and runs its run procedure. This is the state in which the
thread directly executes its operations. Only from the runnable state
will a thread enter the running state.
Runnable state and running state is together called as Active
state.
Waiting/Blocked State
• Whenever a thread is inactive for a span of time (not permanently)
then, either the thread is in the blocked state or is in the waiting state.
• When the thread is alive, i.e., the thread class object persists, but it
cannot be selected for execution by the scheduler. It is now inactive.
• The thread will be in blocked state when it is trying to acquire a lock
but currently the lock is acquired by the other thread. The thread will
move from the blocked state to runnable state when it acquires the
lock.
• The thread will be in waiting state when it calls wait() method or
join() method. It will move to the runnable state when other thread
will notify or that thread will be terminated.
• A thread lies in a timed waiting state when it calls a method with a timeout
parameter. A thread lies in this state until the timeout is completed or
until a notification is received. For example, when a thread calls sleep or
a conditional wait, it is moved to a timed waiting state.
Dead/Terminated State
• When a thread's run() function ends the execution of sentences, it
automatically dies or enters the dead state. That is, when a thread exits
the run() process, it is terminated or killed.
• When the stop() function is invoked, a thread will also go dead.
• It’s in the terminated state when it has either finished execution or was
terminated abnormally.
37. Describe the concept of multithreading in Java. Give its
advantages and provide an example.(10 mark)
16. Explain thread and multithreading. Write and explain a Java
program to implement multiple thread.
18. What is multithreading? What are its advantages? Write a Java
program to implement multithreading.(15 mark)
Multithreading in Java is a programming concept that allows multiple threads
(smaller units of a process) to run concurrently within a program. Java
supports multithreading through its built-in Thread class and the Runnable
interface.
Advantages of Multithreading in Java:
1. Better CPU Utilization: Idle CPU time can be used efficiently.
2. Faster Execution: Tasks can be completed more quickly by parallel
execution.
3. Improved Responsiveness: Useful in GUI applications where the UI
remains responsive while performing tasks in the background.
4. Resource Sharing: Threads share the same memory space, reducing
overhead.
5. Simplified Program Structure: Helps structure programs that perform
multiple concurrent activities.
Example:// Define a class that implements Runnable
class MyTask implements Runnable {
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println(Thread.currentThread().getName() + " - Count: " +
i);
public class Main {
public static void main(String[] args) {
// Create Runnable objects
MyTask task1 = new MyTask();
MyTask task2 = new MyTask();
// Wrap Runnable objects in Thread
Thread thread1 = new Thread(task1);
Thread thread2 = new Thread(task2);
// Start both threads
thread1.start();
thread2.start();
}
39. Describe the various constructors available in the Thread class.
Provide examples.
Constructors of Thread class
• Thread()
• Thread(Runnable target)
• Thread (Runnable target, String name)
• Thread(String name)
• Thread(ThreadGroup group, Runnable target)
• Thread(ThreadGroup group, Runnable target, String name)
• Thread(ThreadGroup group, Runnable target, String name, long stackSize)
• Thread(ThreadGroup group, String name)
1. Using Thread()
class MyThread extends Thread {
public void run() {
System.out.println("Thread running with default
constructor.");
public class Example1 {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
2. Using Thread(Runnable target)
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread running with Runnable
target.");
public class Example2 {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
3. Using Thread(Runnable target, String name)
public class Example3 {
public static void main(String[] args) {
Runnable r = () -> System.out.println("Named
thread is running.");
Thread t = new Thread(r, "MyThread");
t.start();
System.out.println("Thread Name: " + t.getName());
4. Using Thread(String name)
public class Example4 {
public static void main(String[] args) {
Thread t = new Thread("CustomNameThread");
t.start();
System.out.println("Thread Name: " +
t.getName());
}
40. Explain the methods of making classes threadable
41. Explain how you can create and start a thread in Java. Provide and
explain an example to demonstrate this process.
There are two approaches to making your classes behave as threads:
• Extending the Thread class
• Implementing the Runnable interface
Extending the Thread class
• One way to create a thread is to create a new class that extends Thread and
then to create an instance of that class.
• The extending class must override the run() method, which is the entry point
for the new thread.
• It must also call start() to begin execution of the new thread.
• We use the following constructors for creating the Thread:
• Thread
• Thread(Runnable r)
• Thread(String name)
• Thread(Runnable r, String name)
Implementing the Runnable interface
• Another method to create a thread is to create a class that implements the
Runnable interface.
• Runnable abstracts a unit of executable code.
• We can construct a thread on any object that implements Runnable.
• To implement Runnable, a class need only implement a single method called
run()
• The Runnable interface should be implemented by any class whose
instances are intended to be executed by a thread. Runnable interface have
only one method named run().
• public void run() is used to perform action for a thread.
42. What is multithreading? Write and explain a Java program to
implement multithreading
When multiple threads are executed in parallel at the same time, this process
is known as Multithreading .
The Multithreading concept is popularly applied in games, animation…etc.
class MyThread extends Thread {
Eg: public void run() {
System.out.println("Thread is running...");
public static void main(String[] args) {
MyThread t1 = new MyThread(); // create thread object
t1.start(); // start the thread
}
}
43. Explain Synchronization in java with programming example(10mark)
20. Describe the concept of synchronization in Java threads. Describe
why synchronization is necessary and provide examples to demonstrate
its usage.
21. Illustrating java programs, explain how synchronization is important
in programming. What happens if it is skipped during
multithreading(15mark)
• Synchronization in Java is the process that allows only one thread at a
particular time to complete a given task entirely.
• The synchronization is mainly used
1.to prevent thread interference.
2.to prevent consistency problem.
• General form of synchronized statement
Synchronized(objRef) {
//statements to be synchronized
}
eg:
class Counter {
private int count = 0;
public synchronized void increment() {
Count++;
}
public int getCount() {
return count;
}
}
There are two synchronizations in Java as mentioned below:
1.Process Synchronization
2.Thread Synchronization
• Process Synchronization is a technique used to coordinate the execution of
multiple processes. It ensures that the shared resources are safe and in order.
• Thread Synchronization is used to coordinate and ordering of the execution
of the threads in a multi-threaded program. There are two types of thread
synchronization as mentioned below: Mutual Exclusive Cooperation
(Inter-thread communication)
✅
Importance of Synchronization in Programming
Synchronization is crucial in multithreaded programming because it ensures
that only one thread accesses a shared resource (like a variable or method)
at a time. It helps avoid conflicts and ensures data consistency.
🔷 Why Synchronization is Important:
1. ✅ Prevents Thread Interference
○ When two or more threads try to modify shared data at the same
time, they can interfere with each other’s operations.
2. ✅ Ensures Data Consistency
○ Synchronization ensures that one thread completes its operation
on shared data before another begins, preserving correct values.
3. ✅ Avoids Race Conditions
○ It helps prevent race conditions, where the outcome of a program
depends on the unpredictable timing of threads.
What Happens if Synchronization is Skipped?
1. ❌ Inconsistent Output
○ The final result may vary every time you run the program, due to
threads overwriting each other’s work.
2. ❌ Data Corruption
○ Shared data may get corrupted if multiple threads modify it
simultaneously.
3. ❌ Hard-to-Debug Bugs
○ These issues are often timing-dependent and difficult to
reproduce and fix.
44. Explain the delegation event model. Explain the steps of registering
source with listener.
• Event Handling is the mechanism that controls the event and decides what
should happen if an event occurs. This mechanism has the code which is
known as event handler that is executed when an event occurs.
• Java uses the Delegation Event Model to handle the events.
Registering the source with a listener is a crucial step in the Java
Delegation Event Model. It establishes a connection between an
event source and a listener, allowing the listener to receive and
handle events generated by the source.
The following are the steps for registering the source with a
listener:-
1.Create the Event Listener: Define a class that implements the
appropriate listener interface for the type of event you want to
handle. For example, if you're dealing with GUI events, you might
implement the ActionListener interface.
2.Implement Listener Methods: Implement the methods specified
by the listener interface within the listener class. These methods
will be called when the associated event occurs.
3. Create the Event Source: Instantiate the event source object.
This could be a GUI component like a button, text field, or menu
item, depending on the type of event you're handling.
4. Instantiate the Listener: Create an instance of the listener
class you implemented in step 1.
5. Register the Listener with the Event Source: Use a method
provided by the event source to register the listener. This method
varies depending on the event source and the type of event you're
handling.
45. What is an event and event handling in Java? Provide Example.
Explain the two types of events in java?
• The change in the state of an object or behavior by performing actions is
referred to as an Event in Java.
• Actions include button click, keypress, page scrolling, or cursor movement.
Types of Events
1. The Foreground Events:
• Foreground events typically refer to events that require immediate attention
and are directly related to the user interaction or user interface.
2. The Background Events :
• Background events occur in the background or behind the scenes, usually
without requiring direct user interaction.
• These events may include tasks like network communication, data
processing, or automated system operations.
46. Write a note on event listener interface. Explain any ten.
Listeners are created by implementing one or more of the interfaces defined
by the java.awt.event package.
✅
1. ActionListener
● Used for: Button clicks or menu selections.
● Method: actionPerformed(ActionEvent e)
✅ 2. AdjustmentListener
● Used for: Scrollbar adjustments.
● Method: adjustmentValueChanged(AdjustmentEvent e)
✅ 3. ComponentListener
● Used for: Component visibility or size changes.
● Methods:
○ componentResized()
○ componentMoved()
○ componentShown()
○ componentHidden()
✅ 4. ItemListener
● Used for: Checkbox or list item selection changes.
● Method: itemStateChanged(ItemEvent e)
✅ 5. ContainerListener
● Used for: Adding or removing components in a container.
● Methods:
○ componentAdded()
○ componentRemoved()
✅ 6. FocusListener
● Used for: When a component gains or loses keyboard focus.
● Methods:
○ focusGained()
○ focusLost()
✅ 7. KeyListener
● Used for: Keyboard input.
● Methods:
○ keyPressed()
○ keyReleased()
○ keyTyped()
✅ 8. MouseListener
● Used for: Mouse clicks and button events.
● Methods:
○ mouseClicked()
○ mousePressed()
○ mouseReleased()
○ mouseEntered()
○ mouseExited()
✅ 9. MouseMotionListener
● Used for: Mouse movement and dragging.
● Methods:
○ mouseDragged()
○ mouseMoved()
✅ 10. WindowListener
● Used for: Window events like open, close, minimize.
● Methods:
○ windowOpened()
○ windowClosing()
○ windowClosed()
○ windowIconified()
○ windowDeiconified()
○ windowActivated()
○ windowDeactivated()
47. Explain Adapter class and Inner class with example.
Adapter classes are abstract classes provided by the Java AWT (Abstract
Window Toolkit) package for receiving various events. These classes contain
empty implementations of the methods in an event listener interface, providing
a convenience for creating listener objects.
import java.awt.*;
import java.awt.event.*;
class AdapterExample extends Frame {
AdapterExample() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.out.println("Window Closing");
dispose(); // Closes the window
}
});
setSize(300, 200);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new AdapterExample();
Inner class or nested class is a class that is declared inside the class or
interface.
class Outer {
int outerData = 10;
class Inner {
int innerData = 5;
void display() {
System.out.println("Sum: " + (outerData + innerData));
public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.display(); // Output: Sum: 15
48. What is Swings in Java. Explain its features.
49. Write a note on Java swings with example. Also specify its features.
50. Explain Java Swing with an example. Write the difference between
AWT and Swing.
Java Swings
• Java Swing is a popular and powerful Graphical User Interface (GUI) toolkit
that is used for developing desktop applications.
• It is a part of the Java Foundation Classes (JFC) and provides a rich set of
components and layout managers for creating a variety of GUIs.
• Java Swing is platform-independent and can be used on any operating
system that supports Java.
Features of Java Swing
1. Platform Independence: Platform independence is one of Java Swing’s
most remarkable features. It can run on any platform that supports Java.
Thus, Swing-based applications can run on Windows, Mac, Linux, or any
other Java-compatible operating system.
2. Lightweight Components: Java Swing provides a set of lightweight
components that are easy to use and customizable. These components are
designed to consume less memory and use less processing power, making
Swing-based applications run efficiently. Features of Java Swing
3. Pluggable Look and Feel: Java Swing provides a pluggable look and feels
that allows developers to customize the appearance of the GUI according to
the user’s preferences. Developers can choose from several pre-built looks
and feel themes or create their own custom themes.
4. Layout Managers: Java Swing provides a set of layout managers that can
be used to organize the graphical components in a GUI. These layout
managers enable developers to create flexible and responsive GUIs that
adapt to different screen sizes and resolutions.
5. Robust Event Handling Mechanism: Java Swing provides a robust event
handling mechanism that allows developers to handle events generated by
the graphical components. Developers can register event listeners to detect
and respond to user interactions with the GUI
51. What is meant by the components and containers in Java? Explain
any 5(10 mark)
23. Write and explain the programming examples for using Jbutton,
JTextField, JTextBox.
24. Explain Swings in Java. What are components and containers? Give
exemplar code to implement any component or container(15 mark)
Components and Containers of Java Swing
A component is an independent visual control and Java Swing Framework
contains a large set of these components which provide rich functionalities
and allow high level of customization.
A container holds a group of components. It provides a space where a
component can be managed and displayed.
JFrame: JFrame is a top-level container that represents the main window of a
GUI application. It provides a title bar, and minimizes, maximizes, and closes
buttons.
JPanel: JPanel is a container that can hold other components. It is commonly
used to group related components together.
JButton: JButton is a component that represents a clickable button. It is
commonly used to trigger actions in a GUI application.
JLabel: JLabel is a component that displays text or an image. It is commonly
used to provide information or to label other components.
JTextField: JTextField is a component that allows the user to input text. It is
commonly used to get input from the user, such as a name or an address.
Eg:
import javax.swing.*;
public class Example {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
22. Explain the two methods of making classes threadable in Java with
example(15 mark)
1. Extending the Thread Class
● You create a class that extends the java.lang.Thread class.
● Override the run() method to define the task to be executed in the
thread.
● Call the start() method to begin execution, which internally calls run().
Example:
class Multi extends Thread {
public void run() {
System.out.println("thread is running...");
public static void main(String args[]) {
Multi t1 = new Multi(); // Create thread object
t1.start(); // Start the thread
2. Implementing the Runnable Interface
● Create a class that implements the Runnable interface.
● Implement the run() method.
● Pass an instance of your class to a Thread object and start it using the
start() method.
Example:
class example implements Runnable {
public void run() {
System.out.println("thread is running...");
public static void main(String args[]) {
example m1 = new example(); // Create Runnable
object
Thread t1 = new Thread(m1); // Pass it to a
Thread
t1.start(); // Start the thread