Java Material
Java Material
SUBJECT NOTES
Class : II – [Link]., CS
Semester : IV - Semester
Student Name :
Register No :
UNIT I
Introduction: Review of Object-Oriented Concepts
1. Class: A class is a blueprint for creating objects. It defines the structure (attributes) and
behavior (methods) that the objects created from the class will have. For example, a class "Car"
might define attributes like color and model, and methods like drive() and brake().
2. Object: An object is an instance of a class. It holds the actual data and methods defined by the
class. Multiple objects can be created from a single class, each with its own unique set of data.
3. Encapsulation: This concept involves bundling the data (attributes) and methods (functions)
that operate on the data into a single unit or class. Encapsulation also ensures that the data
within a class is protected from unauthorized access by hiding its internal details, often
achieved by using access modifiers like private, protected, and public.
4. Inheritance: Inheritance allows a class to inherit attributes and methods from another class.
This promotes code reuse and hierarchical classification. For instance, a "Truck" class can
inherit from a "Vehicle" class, gaining its attributes and methods, while also having unique
features of its own.
6. Abstraction: Abstraction hides the complex implementation details of an object and exposes
only the necessary parts. This is typically achieved through abstract classes and interfaces,
allowing users to work with high-level entities without knowing the internal complexities.
These fundamental concepts form the foundation of OOP, allowing for modular, reusable, and
maintainable code, which is especially beneficial in large-scale software development.
History of Java
Java is a high-level, object-oriented programming language initially developed by Sun
Microsystems (now owned by Oracle Corporation) in 1995. The language has undergone
significant evolution since its inception and remains one of the most popular programming
languages in the world today. Here's a brief history of Java:
1. 1991: The Origins - The Green Team
Java was originally developed as part of a project called Green Project led by James
Gosling, along with Mike Sheridan and Patrick Naughton.
The team wanted a platform-independent language that could run on any type of device.
Initially, they called the language Oak, after an oak tree outside Gosling's office.
However, the name was later changed to Java due to a trademark conflict.
Java was officially released in 1995. The language was promoted with the tagline
"Write Once, Run Anywhere" (WORA), signifying its ability to run on any device that
had a Java Virtual Machine (JVM). This platform independence was made possible
through the bytecode system, which allowed Java programs to be compiled once and
run anywhere.
Java 1.0 was widely adopted by web developers, as it allowed them to create dynamic
content using Java applets that could run within a web browser.
3. Late Growth
Java gained widespread popularity during the late 1990s due to the rise of the Internet.
It was widely used for creating web applications and applets. Around this time, Sun
Microsystems released various versions of Java, including:
Java 1.1 (1997): Introduced event handling, JDBC (Java Database
Connectivity), and inner classes.
Java 2 (1998): This version marked a major upgrade, bringing in the
concept of multiple configurations for different platforms, such as J2SE
(Java 2 Standard Edition), J2EE (Java 2 Enterprise Edition), and J2ME(Java
2 Micro Edition).
4. 2000s: Enterprise Adoption and J2EE
By the early 2000s, Java had become the standard for enterprise-level applications,
particularly with the introduction of Java 2 Enterprise Edition (J2EE), which
provided a robust platform for developing distributed, scalable, and secure applications.
The adoption of Java for server-side programming allowed for the development of
large-scale web applications and enterprise systems. Java's reliability, security features,
and scalability contributed to its dominance in the industry.
5. 2004: Java 5.0 (J2SE 5.0)
Java 5.0 (also known as J2SE 5.0 or Java 1.5) brought several significant language
improvements, such as:
o Generics
o Enhanced for loop
o Autoboxing/Unboxing
o Enums
o Varargs These additions improved developer productivity and made the language more
expressive.
6. 2006: OpenJDK and the Evolution to Java SE
In 2006, Sun Microsystems announced the OpenJDK project, which made Java's
source code available to the public under the GNU General Public License (GPL).
This step encouraged greater community involvement and innovation.
Java has moved to a more rapid release cycle, with a new version released every six
months. Notable versions include:
Java 11 (2018): The first long-term support (LTS) release under Oracle's new cadence.
It included new features like the var keyword for local variables and the removal of
some deprecated features.
Java 17 (2021): Another LTS release, introducing new features such as sealed classes
and pattern matching for switch expressions.
Java Buzzwords
Java, from its inception, has been associated with a series of key "buzzwords" that define its
philosophy and features. These buzzwords highlight the core strengths of the language and
explain why Java is so widely used. Here's a review of the main Java buzzwords:
1. Simple:
Java was designed to be easy to learn and use. It simplified many complex features of languages
like C and C++ by removing explicit pointers, operator overloading, and multiple
syntax is also clean and closely resembles C++, which makes it familiar tomany developers.
2. Object-Oriented:
Everything in Java is based on objects, which makes the language intuitive and flexible for solving
real-world problems. It supports the four fundamental OOP principles encapsulation,inheritance,
polymorphism, and abstraction.
3. Platform-Independent:
4. Secure:
Java places a strong emphasis on security. It provides a security manager that controls access to
automatic
memory management and strong type-checking, helping prevent common security vulnerabilities like
memory leaks or buffer overflow attacks.
5. Robust:
Java was designed with reliability in mind. It emphasizes strong memory management by
-checking
mechanism ensures fewer errors, and runtime checks help identify bugs early.
6. Multithreaded:
Java natively supports multithreading, allowing multiple threads to run concurrently within a
program. This makes it easier to develop applications that perform multiple tasks simultaneously,
such as handling multiple user requests in a web server or performing background operations.
7. Architecture-Neutral:
depend on any specific processor or operating system. This allows Java programs to run on anyplatform
with a compatible JVM.
8. Interpreted:
Java programs are compiled into bytecode, which is interpreted by the JVM. This intermediatestep
allows Java to be platform-independent and makes the program execution faster than traditional
interpreted languages while ensuring portability.
9. High Performance:
While Java may not be as fast as languages like C or C++ due to the overhead of bytecode
interpretation, techniques like Just-In-Time (JIT) compilation, where bytecode is compiledinto
time.
10. Distributed:
Java provides built-in support for developing distributed applications. It comes with libraries
such as Remote Method Invocation (RMI) and supports networking through its extensive API,
which allows Java programs to communicate over the network.
11. Dynamic:
Java is designed to adapt to an evolving environment. It supports dynamic loading of classes,meaning that new
modules can be loaded at runtime without restarting the application. Java also supports reflection, enabling the
inspection and manipulation of classes and objects at runtime.
12. Portable:
Since Java eliminates many system-dependent features (like pointer arithmetic in C/C++) anddefines platform-
independent data types (e.g., the size of int is always 32 bits), it ensures thatJava applications are highly portable
across different platforms.
1. ClassLoader
Role: The ClassLoader is responsible for loading class files into memory during runtime. Java
programs are compiled into .class files containing bytecode, which the ClassLoader brings into
the JVM.
Functions:
o Loading: It loads classes from different sources like local file systems, remote servers,
or JAR files.
o Linking: This step verifies the bytecode and prepares the class for execution.
o Initialization: This involves assigning default values to static variables and invoking
static blocks.
Types of Class Loaders:
o Bootstrap ClassLoader: Loads core Java libraries (like [Link]).
o Extension ClassLoader: Loads classes from the Java Extensions directory.
o Application ClassLoader: Loads application-level classes.
Method Area:
The Method Area stores class-level information, including the runtime constant pool(constants,
method and field data), code for methods, and constructors.
Heap:
Objects created
using new are stored here. Garbage Collection (GC) is responsible for reclaiming memory from unused objects
in the heap.
Stack:
Each thread in the JVM has its own stack. The stack holds frames, where each frame containslocal variables,
method calls, and partial results. The stack grows and shrinks as methods are invoked and return.
Program Counter (PC) Register:
Each thread has its own PC register, which keeps track of the current instruction being executedby that thread. It
holds the address of the current instruction in the bytecode.
Native Method Stack:
This stack holds native (non-Java) methods written in other languages like C or C++. JNI (JavaNative Interface)
allows the JVM to invoke such methods.
3. Execution Engine
The Execution Engine is responsible for executing the bytecode loaded by the ClassLoader. It
converts bytecode into machine code and handles the actual execution of instructions.
Interpreter:
The interpreter executes the bytecode line-by-line. While it's fast to start, interpreting bytecodecan be slow for
frequently executed code.
Just-In-Time (JIT) Compiler:
The JIT compiler improves performance by compiling frequently executed bytecode (hotspots)into native machine
code at runtime. Once compiled, the native code runs faster than interpreting the bytecode repeatedly.
Garbage Collector (GC):
The GC is responsible for automatic memory management. It reclaims memory used by objectsthat are no longer
referenced by the application, ensuring efficient use of the heap memory.
Java Native Interface (JNI):
JNI provides a way for the JVM to call or be called by native applications and libraries writtenin languages like C
and C++. This is often used when interfacing with system-level resources.
1. Class Loading: When a Java program starts, the ClassLoader loads the necessary class files
into memory.
2. Bytecode Verification: The bytecode verifier ensures that the code adheres to Java's security
constraints and will not harm the JVM or the system it is running on.
3. Execution: The Execution Engine starts interpreting or compiling the bytecode into native
code. During execution, it can switch between interpreting and JIT compilation to optimize
performance.
4. Garbage Collection: The GC periodically frees up memory by reclaiming space from objects
that are no longer in use, ensuring efficient memory management.
Variables
Variable is a named memory location used to store data. Each variable has a specific data type
that determines what kind of values it can hold and what operations can be performed on it.
Variables in Java must be declared before they are used, and they can store different types of
data such as integers, floating-point numbers, characters, and more.
Types of Variables in Java
1. Instance Variables (Non-static Fields):
o Defined within a class but outside of any method, constructor, or block.
o Every instance of the class (object) has its own copy of instance variables.
o These variables are associated with objects, so they are also known as object-level
variables.
o Lifetime: They exist as long as the object exists.
o Default Values: They are assigned default values if not initialized explicitly.
Example:
class Example {
Example:
class Example {
}
3. Local Variables:
4. Parameters:
Variables declared in the method signature are called parameters. They act as inputs to
methods.
Example:
class Example {
void method(int paramVar) { // Parameter variable
[Link](paramVar);
}
}
Declaration and Initialization of Variables
Variables in Java are declared by specifying the data type followed by the variable name.
Optionally, the variable can also be initialized with a value.
Syntax:
dataType variableName = value;
Example:
int age = 25; // Declaration and initializationfloat price; //
Declaration only
price = 99.99f; // Initialization later
Variable names must start with a letter (a-z, A-Z), a dollar sign ($), or an underscore (_).
Subsequent characters can be letters, digits (0-9), underscores, or dollar signs.
Java is case-sensitive, so age and Age are different variables.
Keywords cannot be used as variable names (e.g., int class; is invalid).
Instance Variables: Accessible throughout the class in instance methods and exist as long as
the object exists.
Static Variables: Accessible throughout the class and across objects, existing as long as the
class is loaded into memory.
Local Variables: Their scope is limited to the block, method, or constructor in which they are
declared, and they exist only during the execution of that block.
Key Points
Primitive data types are the most basic data types that Java provides.
These are predefined by the language and named by a keyword.
They are used to store simple values. There are eight primitive data types in Java:
a. Integer Types
byte:
o Size: 1 byte (8 bits)
o Range: -128 to 127
o Use case: Useful for saving memory in large arrays.
short:
o Size: 2 bytes (16 bits)
o Range: -32,768 to 32,767
o Use case: Also used to save memory, like byte, but has a larger range.
int:
o Size: 4 bytes (32 bits)
o Range: -2^31 to 2^31 - 1 (-2,147,483,648 to 2,147,483,647)
o Use case: Most commonly used for representing integers in Java.
long:
o Size: 8 bytes (64 bits)
o Range: -2^63 to 2^63 - 1
o Use case: Used when a wider range of integers is needed (e.g., for large calculations).
b. Floating-Point Types
float:
o Size: 4 bytes (32 bits)
o Range: Approximately ±3.40282347E+38F (7 decimal digits)
o Use case: Useful for saving memory in large arrays of floating-point numbers,
especially when high precision isn't required.
double:
o Size: 8 bytes (64 bits)
o Range: Approximately ±1.79769313486231570E+308 (15 decimal digits)
o Use case: Default type for decimal values; used when precision is important.
c. Character Type
char:
o Size: 2 bytes (16 bits)
o Range: 0 to 65,535 (represents Unicode characters)
o Use case: Used to store a single character. It can store any character, including letters,
digits, or special symbols.
d. Boolean Type
boolean:
o Size: Not precisely defined (typically 1 bit, but implementation-specific)
o Values: true or false
o Use case: Used to represent logical values (i.e., true/false conditions). Often used in
conditional statements and loops.
a. Classes:
A class is a blueprint for creating objects. Objects of a class can store data (attributes) and have
methods (functions).
Example: String class stores sequences of characters. Example: String name = "Java";
b. Interfaces:
An interface is a contract that classes can implement. It specifies what methods a class should
implement but not the implementation itself.
Example: List is an interface that is implemented by classes like ArrayList and LinkedList.
c. Arrays:
Arrays are objects that store multiple values of the same type in a contiguous memory location.
They can be primitive types or reference types.
Example: int[] numbers = {1, 2, 3, 4};
a. Local Variables
Definition: A local variable is declared inside a method, constructor, or block.
Scope: The variable is accessible only within the method, constructor, or block where it is
declared.
Lifetime: Local variables are created when the method or block is invoked and destroyed when
the method or block is exited.
Example:
java
Copy code
public void exampleMethod() {
int localVar = 10; // Local variable
[Link](localVar);
}
In this example, localVar exists only within the exampleMethod and cannot be accessed outsideof it.
b. Instance Variables (Non-Static Fields)
Definition: Instance variables are declared inside a class but outside any method or constructor.
They are also known as fields.
Scope: Instance variables are accessible by all methods, constructors, and blocks of the class in
which they are declared. Each object of the class has its own copy of the instance variables.
Lifetime: The lifetime of instance variables coincides with the lifetime of the object. They are
created when the object is created (instantiated) and destroyed when the object is destroyed
(garbage collected).
Example:
Here, instanceVar is an instance variable, and it will be accessible by all methods within theclass MyClass.
c. Static Variables (Class Variables)
Definition: Static variables are declared with the static keyword inside a class but outside any
method or constructor.
Scope: Static variables are accessible by all methods (both static and non-static) and
constructors of the class. Unlike instance variables, static variables are shared among all
instances of the class.
Lifetime: Static variables are created when the class is first loaded into memory (when it is
used for the first time) and destroyed when the class is unloaded (typically when the JVM shuts
down).
Example:
public class MyClass
{
static int staticVar = 10; // Static variable
public static void main(String[] args)
{
[Link](staticVar); // Accessible throughout the class
}
}
In this example, staticVar is a static variable shared by all objects of the class MyClass.
d. Block Variables
Definition: Block variables are declared inside a block of code, such as a loop or an if
statement.
Scope: They are accessible only within the block where they are declared.
Lifetime: Block variables exist only for the duration of the block execution.
Example:
Local Variables: Exist only during the execution of the method, block, or constructor where
they are declared. Memory is allocated when the block is entered and freed when the block is
exited.
Instance Variables: Exist as long as the object they belong to exists. Memory for instance
variables is allocated when an object is instantiated and freed when the object is destroyed
(garbage collected).
Static Variables: Exist for the lifetime of the class in which they are declared. Memory for
static variables is allocated when the class is loaded into memory and is freed when the class is
unloaded (usually when the program terminates).
In this example:
staticVar is a static variable, accessible throughout the class.
instanceVar is an instance variable, tied to each object of ScopeExample.
localVar is a local variable, confined to methodExample().
blockVar is a block variable, confined to the if block.
Arrays in Java
An array in Java is a collection of elements of the same data type stored in contiguous memory
locations.
Arrays provide a way to store multiple values in a single variable, making it easier to work with
groups of related data.
Key Characteristics of Arrays:
Fixed Size: The size of the array is specified when it's created and cannot be changed.
Homogeneous Elements: All elements in an array must be of the same data type (e.g., int[] can
only hold integers).
Indexing: Elements in the array are accessed by their index, starting from 0.
Types of Arrays
1. Single-Dimensional Arrays
2. Multi-Dimensional Arrays (e.g., 2D Arrays)
1. Single-Dimensional Arrays
A single-dimensional array is the most basic form of an array, where data is stored in a single
row.
// Declaration
int[] arr; // Declares an array variable
// Initialization
arr = new int[5]; // Allocates memory for 5 integers
// Declaration and Initialization together int[] arr = new
int[5]; // Array of 5 integers
// Initializing with values
int[] arr = {1, 2, 3, 4, 5}; // Array with 5 elements
Array elements are accessed using their index. Indexes in Java arrays start at 0 and go up to length - 1.
int[] arr = {10, 20, 30, 40, 50};
You can modify elements in an array by assigning new values using their index.
arr[2] = 100; // Changes the third element (index 2) to 100
Example:
2. Multi-Dimensional Arrays
A multi-dimensional array in Java is essentially an array of arrays.
The most commonly used type is the two-dimensional array, which is like a matrix (rows and
columns).
// Declarationint[][]
matrix;
// Initialization
matrix = new int[3][4]; // 3 rows, 4 columns
// Declaration and Initialization together
int[][] matrix = new int[3][4]; // A 2D array with 3 rows and 4 columns
// Initializing with values
int[][] matrix =
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
Elements in a two-dimensional array are accessed using two indices: one for the row and one
for the column.
Example:
2. Traversing Arrays: Arrays can be traversed using loops, such as for, for-each, or while loops.
For Loop:
for (int i = 0; i < [Link]; i++)
{
[Link](arr[i]);
}
Enhanced For Loop (For-Each Loop):
for (int num : arr)
{
[Link](num);
}
3. Copying Arrays: Arrays can be copied using built-in methods like [Link]().
4. Sorting Arrays: Java provides utility methods in the Arrays class for sorting.
Limitations of Arrays:
Fixed Size: Once an array's size is defined, it cannot be changed. If you need a dynamically
resizable array, consider using collections like ArrayList.
Homogeneous: Arrays can only hold elements of the same type. For heterogeneous collections
of objects, you can use Object[] or collections.
Summary:
Single-Dimensional Arrays: A list of elements of the same type stored in contiguous memory.
Multi-Dimensional Arrays: Arrays of arrays, useful for representing data in a tabular form.
Common Operations: Access, modify, traverse, copy, and sort arrays.
Limitations: Fixed size, homogeneous elements. For more flexibility, Java collections like
ArrayList can be used.
Operators in Java
Operators in Java are symbols that perform operations on variables and values.
Java provides several types of operators for different tasks like arithmetic calculations,
logical decisions, comparisons, and more.
Operators are divided into several categories:
1. Arithmetic Operators
These operators are used to perform basic arithmetic calculations.
Operator Description Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulus (Remainder) a%b
Example:
int a = 10;
int b = 5;
[Link](a + b); // Output: 15
[Link](a % b); // Output: 0
3. Logical Operators
Logical operators are used to combine multiple conditions (boolean expressions).
Operator Description Example
&& Logical AND a && b
` `
! Logical NOT !a
Example:
boolean a = true; boolean
b = false;
[Link](a && b); // Output: false
[Link](a || b); // Output: true
[Link](!a); // Output: false
4. Assignment Operators
Assignment operators are used to assign values to variables.
Operator Description Example
= Assign a=b
+= Add and assign a += b
-= Subtract and assign a -= b
*= Multiply and assign a *= b
/= Divide and assign a /= b
%= Modulus and assign a %= b
Example:
int a = 10;
a += 5; // Equivalent to a = a + 5 [Link](a);
// Output: 15
5. Unary Operators
Unary operators are used with a single operand to perform operations like increment,
decrement, negation, etc.
Operator Description Example
+ Unary plus (positive) +a
- Unary minus (negative) -a
++ Increment (pre/post) ++a, a++
-- Decrement (pre/post) --a, a--
! Logical negation !a
Example:
int a = 10;
[Link](++a); // Output: 11 (Pre-increment)
[Link](a--); // Output: 11 (Post-decrement)
[Link](a); // Output: 10
6. Bitwise Operators
Bitwise operators perform operations on bits (binary digits) of integer types.
Operator Description Example
& Bitwise AND a&b
` ` Bitwise OR
^ Bitwise XOR a^b
~ Bitwise NOT ~a
<< Left shift a << 2
>> Right shift a >> 2
>>> Unsigned right shift a >>> 2
Example:
int a = 5; // 0101 in binaryint b = 3; //
0011 in binary
[Link](a & b); // Output: 1 (0001 in binary)
[Link](a | b); // Output: 7 (0111 in binary)
7. Ternary Operator
The ternary operator is a shorthand for an if-else statement. It takes three operands and
evaluates a condition.
Operator Description Example
?: Ternary (conditional) operator condition ? expr1 : expr2
Example:
int a = 10;int b = 20;
int max = (a > b) ? a : b; [Link](max); //
Output: 20
8. Instanceof Operator
The instanceof operator checks if an object is an instance of a specific class or interface.
Example:
String s = "Hello";
[Link](s instanceof String); // Output: true
Summary of Java Operators:
Arithmetic Operators: Perform basic mathematical operations like addition and
multiplication.
Relational Operators: Compare two values and return a boolean result.
Logical Operators: Combine boolean expressions to form complex conditions.
Assignment Operators: Assign values to variables.
Unary Operators: Operate on a single operand, often used for incrementing or negating
values.
Bitwise Operators: Perform bit-level operations on integer types.
Ternary Operator: A concise way to make decisions (if-else).
Instanceof Operator: Checks if an object is an instance of a class.
1. Decision-Making Statements
a. if Statement
The if statement executes a block of code if the given condition is [Link]
(condition)
{
// Code to execute if condition is true
}
Example:
int number = 10;if
(number > 5)
{
[Link]("Number is greater than 5.");
}
b. if-else Statement
The if-else statement provides an alternative block of code to execute if the condition is [Link]
(condition)
{
// Code if condition is true
} else
{
// Code if condition is false
}
Example:
int number = 10;if
(number > 15)
{
[Link]("Number is greater than 15.");
} else
{
[Link]("Number is not greater than 15.");
}
c. if-else-if Ladder
This statement is used to check multiple conditions one after [Link]
(condition1)
{
// Code if condition1 is true
} else if (condition2)
{
// Code if condition2 is true
} else
{
// Code if none of the conditions are true
}
Example:
int score = 85; if
(score >= 90)
{
[Link]("A");
} else if (score >= 80)
{
[Link]("B");
} else if (score >= 70)
{
[Link]("C");
} else
{
[Link]("Fail");
}
d. switch Statement
The switch statement is used to select one of many code blocks to execute based on the value ofa
variable.
switch (variable)
{
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
// More cases...
default:
// Default code if no case matches
}
Example:
int day = 2;
switch (day)
{
case 1:
[Link]("Sunday");
break;
case 2:
[Link]("Monday");break;
case 3: [Link]("Tuesday");break;
default:
[Link]("Invalid day");
}
2. Looping Statements
a. for Loop
The for loop is used to execute a block of code a specific number of [Link]
(initialization; condition; update)
{
// Code to execute in each iteration
}
Example:
while (condition)
{
// Code to execute while condition is true
}
Example:
int i = 0; while
(i < 5)
{
[Link]("i: " + i);
i++;
}
c. do-while Loop
The do-while loop is similar to the while loop, except that it guarantees that the loop willexecute
at least once, even if the condition is false.
do
{
// Code to execute
} while (condition);
Example:
int i = 0;
do
{
[Link]("i: " + i);
i++;
} while (i < 5);
3. Jump Statements
a. break Statement
The break statement is used to exit a loop or switch statement immediately.
Example (in a loop):
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break; // Exit the loop when i is 5
}
[Link](i);
}
b. continue Statement
The continue statement skips the current iteration of a loop and continues with the next
iteration.
Example:
for (int i = 0; i < 5; i++)
{
if (i == 2)
{
continue; // Skip the rest of the loop body when i is 2
}
[Link](i);
}
c. return Statement
The return statement exits from the current method and can return a value if needed.
Example:
public int add(int a, int b)
{
return a + b; // Return the sum of a and b
}
Decision-Making Statements: Control the flow based on conditions (if, if-else, switch).
Looping Statements: Repeat code based on conditions (for, while, do-while).
Jump Statements: Interrupt normal flow by jumping to another point (break, continue, return).
Example:
int intValue = 100;
long longValue = intValue; // Implicit conversion from int to longfloat floatValue =
intValue; // Implicit conversion from int to float
Example:
double doubleValue = 9.78;
int intValue = (int) doubleValue; // Explicit conversion from double to int
[Link](intValue); // Output: 9 (decimal part is truncated)
Example:
// Boxing
Integer integerValue = [Link](100); // from int to Integer
// Unboxing
int intValue = [Link](); // from Integer to int
Example:
String numberString = "123";
int number = [Link](numberString); // String to int
double doubleNumber = [Link]("123.45"); // String to double
[Link](number); // Output: 123 [Link](doubleNumber); // Output:
123.45
// Converting numeric to string
String strFromInt = [Link](number); // int to String
String strFromDouble = [Link](doubleNumber); // double to String
Example:
int intValue = 10;
double doubleValue = 5.5;
double result = intValue + doubleValue; // int is promoted to double
[Link](result); // Output: 15.5
Summary
Implicit Conversion: Automatic widening conversion from a smaller to a larger data type. No
data loss occurs.
Explicit Conversion (Casting): Narrowing conversion from a larger to a smaller data type,
which requires a cast and may result in data loss.
Wrapper Classes: Boxing and unboxing for converting between primitive types and their
corresponding object types.
String Conversion: Converting between strings and numeric types using wrapper class
methods.
Mixed Expressions: Java applies implicit conversion to the largest data type involved in the
expression.
Explanation:
1. Import Statement:
o import [Link]; imports the Scanner class, which is used for obtaining input
from the user.
2. Class Definition:
o public class SimpleCalculator defines a public class named SimpleCalculator.
3. Method:
o The add method takes two integer parameters and returns their sum.
4. Main Method:
o The main method is the entry point of the program. It creates an instance of the Scanner
class to read user input.
oIt prompts the user to enter two integers, calls the add method to calculate the sum, and
then prints the result.
5. Output:
o The program outputs the sum of the two numbers entered by the user.
Run the Program: After successful compilation, run the program with:java
SimpleCalculator
1. Input: Follow the prompts to enter two numbers, and the program will display their sum.
This simple program showcases basic Java syntax, user input handling, method definition, and output.
Constructors in Java
Constructors are special methods in Java that are called when an object of a class is created.
They initialize the new object and can set initial values for the object's attributes.
Constructors have the same name as the class and do not have a return type.
1. Default Constructor: A constructor that does not take any parameters. It initializes object
attributes to default values.
2. Parameterized Constructor: A constructor that takes parameters to initialize the object with
specific values.
Example of Constructors
class Student
{
// Attributes
String name;
int age;
// Default Constructor
public Student()
{
name = "Unknown";
age = 0;
}
// Parameterized Constructor public
Student(String name, int age)
{
[Link] = name; // 'this' refers to the current [Link] = age;
}
// Method to display student details
public void display()
{
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}
public class Main
{
public static void main(String[] args)
{
// Creating an object using the default constructor
Student student1 = new Student();
[Link]("Student 1 Details:"); [Link](); //
Output: Name: Unknown, Age: 0
// Creating an object using the parameterized constructor
Student student2 = new Student("Alice", 20);
[Link]("\nStudent 2 Details:"); [Link](); //
Output: Name: Alice, Age: 20
}
}
Explanation of the Example:
1. Class Definition:
o The Student class has two attributes: name and age.
2. Default Constructor:
o public Student() initializes the name to "Unknown" and age to 0.
3. Parameterized Constructor:
o public Student(String name, int age) initializes the attributes with values passed as
parameters. The this keyword differentiates between the instance variables and
parameters with the same name.
4. Method to Display Details:
o The display() method prints the values of the name and age attributes.
5. Main Method:
o An object of Student is created using both the default and parameterized constructors,
and their details are displayed.
Key Points:
Constructor Overloading: You can have multiple constructors with different parameters, as
shown in the example with both a default and a parameterized constructor.
The this Keyword: Used in constructors to refer to the current object's attributes when the
parameter names are the same as the attributes.
Object Initialization: Constructors are primarily used to set the initial state of an object during
its creation.
Summary
Constructors are special methods for initializing objects.
They can be default (no parameters) or parameterized (with parameters).
Constructors do not have a return type and are invoked automatically when an object is created.
You can overload constructors to create multiple ways of initializing an object.
Methods in Java
Methods in Java are blocks of code that perform specific tasks.
They allow for code reusability, better organization, and separation of functionality.
A method can take inputs (parameters), perform operations, and may return a result.
Understanding methods is fundamental to Java programming.
Key Features of Methods
1. Method Declaration: A method must be declared before it can be used. It consists of the
method signature, which includes the method name and parameters, followed by the method
body.
2. Return Type: Methods can return a value of a specific type or can be declared as void if they
do not return anything.
3. Parameters: Methods can accept parameters, which are values passed to the method when it is
called.
4. Method Overloading: You can have multiple methods in the same class with the same name
but different parameter lists (different types or number of parameters).
Method Syntax
The general syntax for declaring a method in Java is:
accessModifier returnType methodName(parameterType parameterName1, parameterType
parameterName2, ...)
{
// Method body
}
Example of Methods
overloading:
class Calculator
{
// Method to add two numbers (returns an int)
public int add(int a, int b)
{
return a + b; // Return the sum
}
// Method to add three numbers (overloaded method)
public int add(int a, int b, int c)
{
return a + b + c; // Return the sum of three numbers
}
// Method to multiply two numbers (returns a double)public double
multiply(double a, double b) {
return a * b; // Return the product
}
// Method to display results
public void displayResult(String operation, double result)
{
[Link]("The result of " + operation + " is: " + result);
}
}
public class Main
{
public static void main(String[] args)
{
Calculator calculator = new Calculator(); // Create a Calculator object
// Call the add method with two parametersint sum1 =
[Link](10, 20);
[Link]("addition of 10 and 20", sum1);
// Call the add method with three parametersint
sum2 = [Link](10, 20, 30);
[Link]("addition of 10, 20, and 30", sum2);
// Call the multiply method
double product = [Link](5.5, 4.5);
[Link]("multiplication of 5.5 and 4.5", product);
}
}
1. Class Definition:
o The Calculator class contains methods that perform different arithmetic operations.
2. Method Declarations:
o public int add(int a, int b): This method adds two integers and returns the result.
o public int add(int a, int b, int c): This overloaded method adds three integers.
o public double multiply(double a, double b): This method multiplies two doubles and
returns the result.
o public void displayResult(String operation, double result): This method displays the
result of an operation but does not return a value.
3. Method Calls:
o In the main method, a Calculator object is created.
o The add method is called with two and three parameters, demonstrating method
overloading.
o The multiply method is called to demonstrate another operation.
o The displayResult method is used to print the results.
Key Points
Access Modifiers: Methods can have access modifiers (like public, private, etc.) that define
their visibility.
Return Type: Indicates the type of value the method will return. If it does not return a value, it
should be declared as void.
Method Overloading: Allows multiple methods with the same name but different parameters,
improving code readability and organization.
Method Parameters: Can be of any type (primitive or object) and can be passed by value (for
primitives) or by reference (for objects).
Summary
Methods are essential for code organization and reusability in Java.
They can take parameters and return values, facilitating various operations.
Understanding method overloading and proper declaration is crucial for effective Java
programming.
A static block in Java is a block of code that initializes static variables when the class is
loaded.
Static blocks are executed only once when the class is loaded into memory, making them ideal
for initializing static fields that require complex initialization.
1. Class Definition:
o The Example class has a static variable staticVariable and an instance variable
instanceVariable.
2. Static Block:
o The static block initializes staticVariable to 10 and prints a message indicating that the
static block has been executed.
3. Constructor:
o The constructor initializes instanceVariable with the value passed when creating an
object and prints a message.
4. Main Method:
o In the main method, two objects of the Example class are created. When the class is first
loaded, the static block executes only once, followed by the constructor for each object
created.
Output
When you run the program, the output will be:
Static block executed. Static variable initialized to 10Creating first
object...
Constructor executed. Instance variable initialized to 20Creating
second object...
Constructor executed. Instance variable initialized to 30
Key Points
Execution Order: The static block executes before any objects of the class are created and
before any static methods are invoked. In the example, the static block executes before the
constructors.
Usage: Static blocks are often used for complex initialization of static variables, loading
configuration data, or setting up resources that are needed by static methods.
Multiple Static Blocks: If multiple static blocks are present, they execute in the order they
appear in the class.
Summary
Static blocks are a powerful feature in Java for initializing static variables and performing one-
time setup tasks for a class.
They execute only once when the class is loaded, providing a clear and efficient way to manage
static initialization.
class Counter {
// Static variable to keep track of the number of instancesstatic
int count = 0;
// Constructor
public Counter() {
count++; // Increment count every time a new object is created
}
// Static method to get the current count
public static int getCount() {
return count; // Return the number of instances created
}
}
public class Main {
public static void main(String[] args) {
[Link]("Initial count: " + [Link]()); // Output: 0
// Create instances of Counter
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
In Java, String and StringBuffer are two important classes used for handling strings, but they
have different characteristics and use cases.
Both classes have several static methods that provide functionality for string manipulation.
an overview of the String and StringBuffer classes, focusing on their static methods.
1. String Class
The String class in Java is used to represent immutable sequences of characters. Once a String
object is created, it cannot be changed.
This immutability makes the String class inherently thread-safe.
[Link](): Converts various types of values (like int, float, char, etc.) to their string
representation.
String str = [Link](100); // "100"
[Link](): Creates a formatted string using the specified format string and arguments.
String formatted = [Link]("Hello, %s! You have %d new messages.", "Alice", 5);
// "Hello, Alice! You have 5 new messages."
2. StringBuffer Class
[Link](): Appends the specified string to the end of the current StringBuffer
object.
StringBuffer sb = new StringBuffer("Hello");[Link]("
World"); // "Hello World"
[Link](): Inserts a string into the StringBuffer at a specified index.
String greeting = [Link]("Hello, %s! You are %d years old.", name, age);
[Link](greeting); // Output: Hello, Alice! You are 30 years old.
// [Link] example
String fruits = [Link](", ", "Apple", "Banana", "Cherry");
[Link](fruits); // Output: Apple, Banana, Cherry
// Using StringBuffer
StringBuffer sb = new StringBuffer();
[Link]("Hello");
[Link](" World");
[Link]([Link]()); // Output: Hello World
[Link](5, ",");
[Link]([Link]()); // Output: Hello, World
[Link]();
[Link]([Link]()); // Output: dlroW ,olleH
}
}
17. Which part of the JVM is responsible for the interpretation and execution of bytecode?
33. Which control statement is used to skip the current iteration and move to the next iteration of
a loop?
5 MARK QUESTIONS:
1. Explain the concept of Object-Oriented Programming (OOP) and list its four
fundamentalprinciples.
2. Define any five Java buzzwords and explain their significance.
3. Describe the architecture of the Java Virtual Machine (JVM).
4. Explain different data types in Java with examples.
5. Differentiate between instance variables and static variables in Java.
6. What is the scope and lifetime of variables in Java?
7. Explain arrays in Java and how they are declared and initialized.
8. Describe the differences between break and continue statements in Java with examples.
9. Explain type conversion and casting in Java.
10 MARK QUESTIONS
1. Discuss in detail the four main concepts of Object-Oriented Programming (OOP) with
real-world examples.
2. Trace the history of Java from its development to its current version, highlighting
keymilestones.
3. Describe the Java buzzwords with examples. How do these characteristics make
Java apowerful and versatile programming language?
4. Explain the architecture and working of the Java Virtual Machine (JVM) with a
detaileddiagram.
5. What are data types in Java? Discuss both primitive and reference data types in detail
withexamples.
6. Write a simple Java program demonstrating the use of constructors, methods, and
instancevariables. Explain the output of the program.
7. Explain the differences between static data, static methods, and static blocks in Java
withexamples.
8. Discuss the differences between String and StringBuffer classes in Java.
9. Write a detailed explanation of control flow statements in Java (if, else, switch, for,
while,do-while) with examples.
10. Explain the concept of type conversion and casting in Java with an example program
thatdemonstrates both implicit and explicit casting.
UNIT II
Basic concept:
➢ In Java, inheritance is a core feature of Object-Oriented Programming (OOP) that allows
a new class to acquire properties (fields) and behaviors (methods) from an existing class.
➢ This promotes code reuse and establishes a relationship between classes.
➢ Here's an overview of the basic concepts of inheritance in Java:
1. Superclass (Parent Class)
2. Subclass (Child Class)
3. Inheritance of Methods and Attributes
4. Method Overriding
5. The super() Function
6. Types of Inheritance in Java
7. Multiple Inheritance via Interfaces
8. Constructor Inheritance
Inheritance in Java
➢ Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
➢ The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes.
➢ When you inherit from an existing class, you can reuse methods and fields of the parent class.
➢ Moreover, you can add new methods and fields in your current class also.
➢ On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
➢ In java programming, multiple and hybrid inheritance is supported through interface only.
We will learn about interfaces later.
File: [Link]
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}}
Output:
barking…
eating…
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class BabyDog extends Dog{
void weep(){[Link]("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}}
Output:
weeping…
barking…
eating…
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class Cat extends Animal{
void meow(){[Link]("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}}
Output:
meowing…
eating…
class A{
void msg(){[Link]("Hello");}
}
class B{
void msg(){[Link]("Welcome");}
}
class C extends A,B{//suppose if it were
Output:
Java provides four types of access levels using the following access modifiers:
Same Same Subclass (Different World (Other
Modifier
Class Package Package) Classes)
private Yes No No No
Same Same Subclass (Different World (Other
Modifier
Class Package Package) Classes)
No Modifier (Package-Private
Yes Yes No No
or Default)
protected Yes Yes Yes No
public Yes Yes Yes Yes
Let's break down the rules for each modifier.
class Animal {
String species; // Default access (package-private)
void makeSound() {
[Link]("Animal sound");
}
}
• In this example, species and makeSound() are accessible by any class within the same
package but are not accessible outside of it.
Example:
class Animal {
protected String species;
protected void makeSound() {
[Link]("Animal sound");
}
}
class Dog extends Animal {
void showSpecies() {
[Link](species); // Accessible in subclass
}
}
• Here, species and makeSound() are accessible in the Dog class (a subclass), even if Dog is
in a different package.
Example:
class Animal {
public String name;
public void makeSound() {
[Link]("Animal sound");
}
}
class Dog {
void showName() {
Animal a = new Animal();
[Link]([Link]); // Accessible from any class
[Link](); // Accessible from any class
}
}
• Both name and makeSound() are accessible from any class, regardless of package or class
hierarchy.
// In package animals
package animals;
public class Animal {
protected String species = "Unknown";
}
// In package pets
package pets;
import [Link];
public class Dog extends Animal {
void showSpecies() {
[Link](species); // Accessible due to protected access
}
}
Example
package zoo;
public class Zoo {
public static void main(String[] args) {
Animal a = new Animal();
[Link]([Link]); // Can access only public members
[Link](); // Can access only public members
}
}
Example:
class Animal {
String name;
// Constructor with parameter name
Animal(String name) {
[Link] = name; // '[Link]' refers to the instance variable, 'name' refers to the parameter
}
void display() {
[Link]("Animal name: " + [Link]); // Accessing the instance variable
}
}
In this example, [Link] refers to the instance variable, and name on the right side refers to the
constructor parameter.
b) Calling the Current Class Constructor
➢ You can use this() to invoke another constructor in the same class. This is known as
constructor chaining and can help avoid code duplication.
Example:
class Animal {
String name;
int age;
// Constructor 1
Animal(String name) {
this(name, 0); // Calls the second constructor
}
// Constructor 2
Animal(String name, int age) {
[Link] = name;
[Link] = age;
}
void display() {
[Link]("Animal name: " + [Link] + ", age: " + [Link]);
}
}
In this case, this(name, 0) calls the second constructor from the first one, allowing shared
initialization logic.
Example:
class Dog {
void print(Dog d) {
[Link]("This is a dog.");
}
void callPrint() {
[Link](this); // Passing the current instance
}
}
Here, this refers to the current instance of the Dog class.
Example:
class Animal {
String name;
Animal(String name) {
[Link] = name;
}
}
class Dog extends Animal {
String breed;
Dog(String name, String breed) {
super(name); // Calls the constructor of Animal
[Link] = breed;
}
void display() {
[Link]("Dog name: " + [Link] + ", breed: " + [Link]);
}
}
In this example, super(name) is used to call the constructor of the Animal class, which initializes
the name field.
b) Accessing Superclass Methods
➢ When a method in a subclass overrides a method in its superclass, the subclass can still call
the superclass version of the method using [Link]().
Example:
class Animal {
void sound() {
[Link]("Animal makes a sound.");
}
}
class Dog extends Animal {
@Override
void sound() {
[Link](); // Calls the sound method from Animal
[Link]("Dog barks.");
}
}
Here, [Link]() calls the sound() method from the Animal class, followed by the Dog class's
sound() method.
Example:
class Animal {
String name = "Generic Animal";
}
class Dog extends Animal {
String name = "Dog";
void displayNames() {
[Link]("Animal name: " + [Link]); // Refers to Animal's name
[Link]("Dog name: " + [Link]); // Refers to Dog's name
}
}
In this example, [Link] refers to the name variable of the Animal class, while [Link] refers
to the name variable of the Dog class.
This example demonstrates how this and super are used together to manage instance variables and
methods in a subclass and its superclass.
Method Overloading
❖ Method Overloading allows different methods to have the same name, but different
signatures where the signature can differ by the number of input parameters or type of
input parameters, or a mixture of both.
❖ Method overloading in Java is also known as Compile-time Polymorphism, Static
Polymorphism, or Early binding.
❖ In Method overloading compared to the parent argument, the child argument will get the
highest priority.
Method Overriding
➢ Overriding is a feature that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its super-classes or parent
classes.
➢ When a method in a subclass has the same name, the same parameters or signature, and
the same return type(or sub-type) as a method in its super-class, then the method in the
subclass is said to override the method in the super-class.
➢ Method overriding is one of the ways by which Java achieves Run Time Polymorphism.
➢ The version of a method that is executed will be determined by the object that is used to
invoke it.
➢ If an object of a parent class is used to invoke the method, then the version in the parent
class will be executed, but if an object of the subclass is used to invoke the method, then
the version in the child class will be executed.
➢ In other words, it is the type of the object being referred to (not the type of the reference
variable) that determines which version of an overridden method will be executed.
Example of Method Overriding in Java
Below is the implementation of the Java Method Overriding:
// Java program to demonstrate
// method overriding in java
// Base Class
class Parent {
void show() { [Link]("Parent's show()"); }
}
// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
@Override void show()
{
[Link]("Child's show()");
}
}
// Driver class
class Main {
public static void main(String[] args)
{
// If a Parent type reference refers
// to a Parent object, then Parent's
// show is called
Parent obj1 = new Parent();
[Link]();
// If a Parent type reference refers
// to a Child object Child's show()
// is called. This is called RUN TIME
// POLYMORPHISM.
Parent obj2 = new Child();
[Link]();
}
}
Output
Parent's show()
Child's show()
Abstract Class
❖ An abstract class in Java is a class that cannot be instantiated directly. It is meant to be
inherited by other classes that provide implementations for its abstract methods.
❖ The primary purpose of abstract classes is to provide a template for other classes and
enforce a certain structure or behavior.
Abstract Method
❖ An abstract method is a method that is declared without an implementation (no method
body).
❖ Subclasses of the abstract class must provide an implementation for all abstract methods.
// Concrete method
void sleep() {
[Link]("Animal is sleeping");
}
}
// Subclass that extends the abstract class
class Dog extends Animal {
// Provide implementation for abstract method
@Override
void sound() {
[Link]("Dog barks");
}
}
// Subclass that extends the abstract class
class Cat extends Animal {
// Provide implementation for abstract method
@Override
void sound() {
[Link]("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog(); // Create a Dog object
Animal myCat = new Cat(); // Create a Cat object
[Link](); // Calls Dog's implementation of sound()
[Link](); // Inherited from Animal class
[Link](); // Calls Cat's implementation of sound()
[Link](); // Inherited from Animal class
}
}
Output:
Dog barks
Animal is sleeping
Cat meows
Animal is sleeping
❖ Method overriding is one of the ways in which Java supports Runtime Polymorphism.
❖ Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time.
• When an overridden method is called through a superclass reference, Java determines which
version(superclass/subclasses) of that method is to be executed based upon the type of the
object being referred to at the time the call occurs.
• At run-time, it depends on the type of the object being referred to (not the type of the
reference variable) that determines which version of an overridden method will be executed
• A superclass reference variable can refer to a subclass object. This is also known as
upcasting. Java uses this fact to resolve calls to overridden methods at run time.
Therefore, if a superclass contains a method that is overridden by a subclass, then when different
types of objects are referred to through a superclass reference variable, different versions of the
method are executed.
Output:
Dog barks
Cat meows
Explanation:
• myAnimal is a reference of type Animal (superclass) but refers to different subclass objects
(Dog and Cat).
• Even though myAnimal is of type Animal, the method that gets called depends on the actual
object type (Dog or Cat), not the reference type.
• This is dynamic method dispatch in action, where the method to execute is decided at
runtime.
❖ The final keyword in Java is used to restrict the modification of classes, methods, and
variables. Once something is declared final, its behavior or value cannot be changed.
❖ Java final keyword is a non-access specifier that is used to restrict a class, variable, and
method. If we initialize a variable with the final keyword, then we cannot modify its value.
2. Final Methods
❖ A method declared as final cannot be overridden by any subclass.
class Animal {
final void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
// This will cause a compile-time error
// void sound() {
// [Link]("Dog barks");
// }
}
• The final keyword prevents any subclass from modifying the behavior of the sound()
method.
• This is useful when you want to lock the method's behavior and prevent subclasses from
changing it.
3. Final Classes
❖ A class declared as final cannot be extended (i.e., no class can inherit from it).
• A final class prevents inheritance, making the class behavior constant and unmodifiable.
• Examples in Java include the String class, which is final, meaning no one can extend the
String class to alter its functionality.
Packages in Java
❖ A package in Java is a way to organize and group related classes and interfaces together.
❖ It helps manage large codebases by categorizing similar types of classes into different
namespaces, avoiding naming conflicts, and making code more modular, reusable, and
maintainable.
❖ Java has a vast standard library of classes, interfaces, and exceptions grouped into packages
(like [Link], [Link], etc.), and developers can also create custom packages.
Defining a Package
❖ To declare that a class is part of a package, use the package keyword at the top of the Java
file, followed by the package name.
❖ The file should also be saved in a directory structure that matches the package name.
Syntax:
package package_name;
Example:
package [Link];
public class Dog {
public void bark() {
[Link]("Dog barks");
}
}
In this example:
• The class Dog is in the [Link] package.
• The source file [Link] must be saved in a directory structure like com/example/animals/.
1. Built-in Packages: Java provides several built-in packages like [Link], [Link], [Link],
etc. These packages contain various classes and interfaces to perform basic tasks.
o Example: [Link], [Link].
2. User-defined Packages: These are custom packages created by developers to organize their
own classes and interfaces logically.
o Example: [Link].
Example
protected class Animal {
protected void eat() {
[Link]("Animal eats");
}
}
3. Default (Package-private): When no access modifier is specified, the member is accessible
only within the same package. This is known as package-private access.
• Default access helps keep internal functionality within a package without exposing it to
other packages.
Example
class Cat {
void meow() {
[Link]("Cat meows");
}
}
4. Private: The member is only accessible within the same class. Private members cannot be
accessed from outside the class, not even by classes in the same package or subclasses.
Example
class Lion {
private void roar() {
[Link]("Lion roars");
}
}
Importing Packages
❖ To use classes or interfaces from a different package, you need to import them into your
Java file.
❖ The import statement makes the specified package classes available for use in the current
class.
Syntax of Importing:
1. Single Class Import:
o This imports a specific class from a package.
import package_name.ClassName;
Example:
import [Link];
2. Wildcard Import:
• This imports all the classes and interfaces from a package.
import package_name.*;
Example:
import [Link].*;
Defining an Interface
You define an interface using the interface keyword, followed by the method declarations
without bodies.
Syntax:
interface InterfaceName {
// Method signatures (implicitly public and abstract)
void method1();
void method2();
}
Example of an Interface:
interface Animal {
void eat(); // Abstract method
void sleep(); // Abstract method
}
• It declares two methods: eat() and sleep(), but they don't have any implementations (they
are abstract).
• Any class that implements the Animal interface must provide concrete implementations of
these methods.
Implementing an Interface
❖ A class that implements an interface must provide implementations for all the abstract
methods declared in the interface. To implement an interface, the class uses the implements
keyword.
Syntax:
class ClassName implements InterfaceName {
// Provide implementation of all abstract methods from the interface
public void method1() {
// method body
}
public void method2() {
// method body
}
}
Example of a Class Implementing an Interface:
interface Animal {
void eat(); // Abstract method
void sleep(); // Abstract method
}
class Dog implements Animal {
@Override
public void eat() {
[Link]("Dog eats bones");
}
@Override
public void sleep() {
[Link]("Dog sleeps");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
[Link](); // Output: Dog eats bones
[Link](); // Output: Dog sleeps
}
}
Explanation:
• The Dog class implements the Animal interface by providing concrete implementations for
the eat() and sleep() methods.
• An object of the Dog class can then call these methods.
Multiple Interfaces:
A class can implement multiple interfaces in Java, which helps achieve multiple
inheritance.
Example
interface Animal {
void eat();
}
interface Pet {
void play();
}
class Dog implements Animal, Pet {
@Override
public void eat() {
[Link]("Dog eats");
}
@Override
public void play() {
[Link]("Dog plays");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
[Link](); // Output: Dog eats
[Link](); // Output: Dog plays
}
}
Explanation:
• The class Dog implements both the Animal and Pet interfaces, providing implementations
for methods from both interfaces.
• This allows Dog to have behaviors from both interfaces.
Extending Interfaces
❖ Just like classes, interfaces can extend other interfaces. When an interface extends another
interface, it inherits all the abstract methods of the parent interface. The child interface can
declare its own additional methods as well.
Syntax:
interface ParentInterface {
void method1();
}
interface ChildInterface extends ParentInterface {
void method2();
}
Explanation:
• The Mammal interface extends the Animal interface, meaning it inherits the eat() method.
• The Mammal interface also defines a new method walk().
• The Dog class implements the Mammal interface, which means it must provide
implementations for both eat() and walk().
try-catch Block
The try block contains the code that might throw an exception, and the catch block is used
to handle the exception. If an exception occurs in the try block, it is caught and handled in the catch
block.
Syntax:
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
Example:
public class Main {
public static void main(String[] args) {
try {
int data = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero!");
}
}
}
Output:
Cannot divide by zero!
throw Keyword
The throw keyword is used to explicitly throw an exception in Java. You can throw either
checked or unchecked exceptions. The exception object is created using the new keyword.
Syntax:
throw new ExceptionType("Error Message");
Example:
Output:
Exception in thread "main" [Link]: Not eligible to vote
return_type method_name() throws ExceptionType1, ExceptionType2 {
// Method code
}
Example:
import [Link].*;
public class Main {
public static void readFile() throws IOException {
FileReader file = new FileReader("[Link]");
BufferedReader fileInput = new BufferedReader(file);
[Link]();
}
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
[Link]("File not found");
}
}
}
In this example, the readFile method declares that it throws an IOException. The calling method
main() handles it using a try-catch block.
finally Block
❖ The finally block is used to execute important code such as closing resources, regardless of
whether an exception is thrown or caught.
❖ It always executes, even if an exception occurs or a return statement is used inside the try or
catch block.
Syntax:
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that will always execute
}
Example:
public class Main {
public static void main(String[] args) {
try {
int data = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
} finally {
[Link]("Finally block is executed");
}
}
}
Output:
The finally block runs regardless of whether the exception is caught or not.
Exception Description
Thrown when an arithmetic error occurs (e.g., divide by
ArithmeticException
zero).
Thrown when trying to access an index that is out of bounds
ArrayIndexOutOfBoundsException
in an array.
Thrown when an application attempts to use null where an
NullPointerException
object is required.
IOException Thrown when an I/O operation fails or is interrupted.
Thrown when an attempt to open the file denoted by a
FileNotFoundException
specified pathname has failed.
Exception Description
Thrown when an application tries to load a class but no
ClassNotFoundException
definition for the class is found.
Thrown when an attempt to convert a string to a numeric type
NumberFormatException
fails.
Creating Your Own Exception Classes
Java allows developers to create custom exceptions by extending the Exception class or its
subclasses.
Steps to Create a Custom Exception:
• Business logic exceptions: These are the exceptions related to business logic and workflow. It
is useful for the application users or the developers to understand the exact problem.
MCQ’S
1. What is inheritance in Java?
A) A mechanism that allows one class to acquire properties of another class.
B) A mechanism to hide data from unauthorized access.
C) A method to increase the size of a class.
D) A technique to convert one type into another.
2. Which of the following is not a type of inheritance in Java?
A) Single Inheritance B) Multiple Inheritance (using classes)
C) Multilevel Inheritance D) Hierarchical Inheritance
3. Which keyword is used to inherit a class in Java?
A) implements B) extends C) inherits D) super
4. In Java, which member has the least accessibility?
A) public B) protected C) private D) default (package-private)
5. Which of the following is true regarding member access in inheritance?
A) Private members are inherited and can be accessed directly.
B) Protected members can be accessed in derived classes.
C) Public members cannot be inherited.
D) Default members can be accessed from any class in any package.
6. Which of the following best describes the usage of the this keyword in Java?
A) Refers to the current class constructor B) Refers to the current object instance
C) Refers to the parent class constructor D) Refers to the parent object instance
7. What does the super keyword do in Java?
A) Refers to the current object B) Refers to the parent class constructor and members
C) Refers to the child class methods D) Refers to static methods only
8. Method overloading is an example of which of the following?
A) Compile-time polymorphism B) Runtime polymorphism
C) Data abstraction D) Encapsulation
9. What is method overloading?
A) When two methods have the same name but different return types
B) When two methods have the same name but different argument lists
C) When two methods have the same signature but different return types
D) When a child class method has the same name as a parent class method
10. What is method overriding?
A) When two methods have the same name but different argument lists
B) When a subclass provides a specific implementation of a method that is already
defined by its parent class
C) When a class has multiple constructors with the same name
D) When two methods have the same name but different return types
11. What is the purpose of an abstract class in Java?
A) To define concrete methods only
B) To provide a blueprint for other classes, containing both abstract and concrete
methods
C) To instantiate objects
D) To support multiple inheritance
12. Which of the following is true about abstract classes?
A) You can create an instance of an abstract class.
B) An abstract class must contain at least one abstract method.
C) All methods in an abstract class must be abstract.
D) A class that extends an abstract class must implement all abstract methods of the
parent class.
13. What is dynamic method dispatch?
A) A process where a method is called based on the object type at compile-time.
B) A process where a method is called based on the object type at runtime.
C) A technique for overloading methods.
D) A technique to handle multiple inheritance.
14. What is the primary use of the final keyword when applied to a method?
A) The method cannot be overloaded.
B) The method cannot be overridden by subclasses.
C) The method can only be used by subclasses.
D) The method can be used with abstract classes.
15. What does it mean when a class is declared as final?
A) It cannot have a constructor. B) It cannot be subclassed.
C) It cannot implement an interface. D) It cannot have any variables.
16. Can a final class be extended in Java?
A) Yes, by any class. B) Yes, but only in the same package.
C) No, a final class cannot be extended. D) Yes, but only by one class.
17. Which of the following cannot be overridden in Java?
A) Static methods B) Final methods C) Both A and B D) Private methods
18. What is a package in Java?
A) A group of related classes and interfaces. B) A method to hide data.
C) A group of objects. D) A collection of constants.
19. Which of the following is a valid package declaration?
A) import [Link].*; B) package [Link].*;
C) package [Link]; D) class package [Link];
20. Which keyword is used to import a package in Java?
A) include B) using C) package D) import
21. What access level do members of a class have if no modifier is specified?
A) public B) protected C) private D) package-private (default)
22. Which of the following allows access to members within the same package?
A) public B) private C) protected D) package-private (default)
23. Which of the following is NOT a valid import statement?
A) import [Link].*; B) import [Link];
C) import static [Link].*; D) import package [Link];
24. What is an interface in Java?
A) A class that contains only concrete methods. B) A collection of abstract methods.
C) A class that cannot be extended. D) A class with final methods.
25. Which of the following is true about interfaces in Java?
A) An interface can contain only abstract methods.
B) An interface can contain both abstract methods and default methods.
C) A class can implement multiple interfaces but can extend only one interface.
D) A class cannot implement an interface.
26. What is the keyword used to implement an interface in Java?
A) extends B) implement C) implements D) interface
27. Can an interface extend multiple interfaces?
A) No, an interface can extend only one interface.
B) Yes, an interface can extend multiple interfaces.
C) An interface cannot extend another interface.
D) An interface must extend a class.
28. Which of the following is not allowed in an interface?
A) Abstract methods B) Default methods C) Static methods D) Instance variables
29. What is the default access modifier for methods declared inside an interface?
A) public B) private C) protected D) default (package-private)
30. What is exception handling in Java?
A) A method to hide data. B) A mechanism to handle runtime errors.
C) A mechanism to handle compile-time errors. D) A process of error-free coding.
31. Which block must be used with the try block?
A) finally B) throw C) catch D) throws
32. Which keyword is used to explicitly throw an exception in Java?
A) throws B) throw C) catch D) final
33. Which keyword is used to declare that a method might throw an exception?
A) throw B) catch C) throws D) final
34. What is the purpose of the finally block in Java?
A) It is executed when no exception is thrown.
B) It is executed only if an exception is thrown.
C) It is executed regardless of whether an exception occurs or not.
D) It is optional and executed if the program terminates abnormally.
35. Which of the following is a checked exception in Java?
A) ArithmeticException B) NullPointerException
C) FileNotFoundException D) ArrayIndexOutOfBoundsException
36. Which of the following exceptions is an unchecked exception?
A) IOException B) SQLException
C) ClassNotFoundException D) ArithmeticException
37. What is the base class for all exceptions in Java?
A) [Link] B) [Link]
C) [Link] D) [Link]
38. What is the correct order of exception handling blocks in Java?
A) try → catch → throw B) try → finally → catch
C) try → catch → finally D) throw → try → catch
39. What will happen if an exception is thrown in a try block and is not caught?
A) The program continues running. B) The program terminates abnormally.
C) The program will compile but won't execute.D) The program executes the catch block.
40. Which block is executed even if an exception is not caught in the catch block?
A) catch B) finally C) throw D) throws
41. When does Exceptions in Java arises in code sequence?
a) Run Time b) Compilation Time
c) Can Occur Any Time d) none of the mentioned
42. Which of these keywords is not a part of exception handling?
a) try b) finally c) thrown d) catch
43. What will be the output of the following Java program?
1. class exception_handling
2. {
3. public static void main(String args[])
4. {
5. try
6. {
7. [Link]("Hello" + " " + 1 / 0);
8. }
9. catch(ArithmeticException e)
10. {
11. [Link]("World");
12. }
13. }
14. }
a) Hello b) World c) HelloWorld d) Hello World
44. Which of the following handles the exception when a catch is not used?
a) finally b) throw handler c) default handler d) java run time system
45. Which part of code gets executed whether exception is caught or not?
a) finally b) try c) catch d) throw
46. Which of the following should be true of the object thrown by a thrown statement?
a) Should be assignable to String type b) Should be assignable to Exception type
c) Should be assignable to Throwable type d) Should be assignable to Error type
47. At runtime, error is recoverable.
a) True b) False
48. Which of these is a super class of all exceptional type classes?
a) String b) RuntimeExceptionsc) Throwable d) Cacheable
49. Which of these class is related to all the exceptions that cannot be caught?
a) Error b) Exception c) RuntimeExecption d) All of the mentioned
50. Which of these handles the exception when no catch is used?
a) Default handler b) finally c) throw handler d) Java run time system
5 MARKS QUESTIONS
1. Explain the basic concept of inheritance in Java.
2. What are the different types of inheritance supported in Java?
3. Explain the difference between method overloading and method overriding.
4. Describe the use of the this and super keywords in Java.
5. What is an interface in Java and how is it implemented?
10 MARK QUESTIONS
1. Explain the concept of dynamic method dispatch in Java with an example.
2. Discuss the access protection mechanism in Java packages.
3. Explain exception handling in Java using try, catch, finally, throw, and throws.
4. What are abstract classes in Java, and how do they differ from interfaces?
5. How can you create custom exceptions in Java, and what are the built-in exception classes
UNIT - III
Java Threads
Threads allows a program to operate more efficiently by doing multiple things at the same time.
Threads can be used to perform complicated tasks in the background without interrupting the main
program.
Creating a Thread
There are two ways to create a thread.
It can be created by extending the Thread class and overriding its run() method:
Extend Syntax
public class Main extends Thread {
public void run() {
[Link]("This code is running in a thread");
}
}
Another way to create a thread is to implement the Runnable interface:
Implement Syntax
public class Main implements Runnable
{ public void run() {
[Link]("This code is running in a thread");
}
}
Running Threads
If the class extends the Thread class, the thread can be run by creating an instance of the class and call
its start() method:
Extend Example
public class Main extends Thread {
public static void main(String[] args) {
Main thread = new Main();
[Link]();
[Link]("This code is outside of the thread");
}
public void run() {
[Link]("This code is running in a thread");
}
}
If the class implements the Runnable interface, the thread can be run by passing an instance of the class
to a Thread object's constructor and then calling the thread's start() method:
Implement Example
public class Main implements Runnable { public static void
main(String[] args) {
Main obj = new Main();
Thread thread = new Thread(obj); [Link]();
[Link]("This code is outside of the thread");
}
public void run() {
[Link]("This code is running in a thread");
}
}
Differences between "extending" and "implementing" Threads
The major difference is that when a class extends the Thread class, you cannot extend any other
class, but by implementing the Runnable interface, it is possible to extend from another class as
well, like: class MyClass extends OtherClass implements Runnable.
2) notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor. If any threads
are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at
the discretion of the implementation.
Syntax:
1. public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
1. public final void notifyAll()
Understanding the process of inter-thread communication
The point to point explanation of the above diagram is as follows:
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases
the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the object.
Why wait(), notify() and notifyAll() methods are defined in Object class not
Thread class?
It is because they are related to lock and object has a lock.
Difference between wait and sleep?
wait() sleep()
The wait() method releases the lock. The sleep() method doesn't release
the lock.
[Link]
1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. [Link]("going to withdraw..."); 6.
7. if([Link]<amount){
8. [Link]("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
10. }
11. [Link]-=amount;
12. [Link]("withdraw completed...");
13. }
14.
15. synchronized void deposit(int amount){
16. [Link]("going to deposit...");
17. [Link]+=amount;
18. [Link]("deposit completed... ");
19. notify();
20. }
21. }
22.
23. class Test{
24. public static void main(String args[]){
25. final Customer c=new Customer();
26. new Thread(){
27. public void run(){[Link](15000);}
28. }.start();
29. new Thread(){
30. public void run(){[Link](10000);}
31. }.start();
32.
33. }}
34.
Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
createNewFile()
Boolean Creates an empty file
exists()
Boolean Tests whether the file exists
getAbsolutePath()
String Returns the absolute pathname of the file
length() Long Returns the size of the file in bytes
list()
String[] Returns an array of the files in the directory
Create a File
To create a file in Java, you can use the createNewFile() method. This method returns a boolean value:
true if the file was successfully created, and false if the file already exists. Note that the method is
enclosed in a try...catch block. This is necessary because it throws an IOException if an error occurs (if
the file cannot be created for some reason):
Example
import [Link]; // Import the File class
import [Link]; // Import the IOException class to handle
errors
Write To a File
In the following example, we use the FileWriter class together with
its write() method to write some text to the file we created in the example above. Note that when you
are done writing to the file, you should close it with the close() method:
Example
import [Link]; // Import the FileWriter class
import [Link]; // Import the IOException class to handle
errors
public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("[Link]");
[Link]("Files in Java might be tricky, but it is fun
enough!");
[Link]();
[Link]("Successfully wrote to the file.");
} catch (IOException e) {
[Link]("An error occurred.");
[Link]();
}
}
}
The output will be:
Successfully wrote to the file.
Read a File
In the following example, we use the Scanner class to read the contents of the text file
Example
import [Link]; // Import the File class
import [Link]; // Import this class to handle
errors
import [Link]; // Import the Scanner class to read text
files public class ReadFile {
public static void main(String[] args) {
try {
File myObj = new
File("[Link]"); Scanner
myReader = new Scanner(myObj); while
([Link]()) {
String data =
[Link]();
[Link](data);
}
[Link]();
} catch (FileNotFoundException e) {
[Link]("An error occurred.");
[Link]();
}
}
}
The output will be:
Files in Java might be tricky, but it is fun enough!
Readable: true
File size in bytes: 0
Delete a File
To delete a file in Java, use the delete() method:
Example
import [Link]; // Import the File class
public class DeleteFile {
public static void main(String[] args)
{ File myObj = new
File("[Link]"); if
([Link]()) {
[Link]("Deleted the file: " + [Link]());
} else {
[Link]("Failed to delete the file.");
}
}
}
The output will be:
Deleted the file: [Link]
Deadlock in Java
Deadlock in Java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting
for an object lock, that is acquired by another thread and second thread is waiting for an object lock
that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the
condition is called deadlock.
37.
38. [Link]();
}
39.
40. }
Output:
43.
44. // resource1
45. private class resource1 {
46. private int i = 10;
47.
48. public int getI() {
49. return i;
50. }
51.
52. public void setI(int i) {
53. this.i = i;
54. }
55. }
56.
57. // resource2
58. private class resource2 {
59. private int i = 20;
60.
61. public int getI() {
62. return i;
63. }
64.
65. public void setI(int i) {
66. this.i = i;
67. }
68. }
69. }
Output:
In block 1
In block 2
In the above code, class DeadlockSolved solves the deadlock kind of situation. It will help in
avoiding deadlocks, and if encountered, in resolving them.
How to Avoid Deadlock in Java?
Deadlocks cannot be completely resolved. But we can avoid them by following basic rules
mentioned below:
1. Avoid Nested Locks: We must avoid giving locks to multiple threads, this is the main reason
for a deadlock condition. It normally happens when you give locks to multiple threads.
2. Avoid Unnecessary Locks: The locks should be given to the important threads. Giving locks to
the unnecessary threads that cause the deadlock condition.
3. Using Thread Join: A deadlock usually happens when one thread is waiting for the other to finish. In
this case, we can use join with a maximum time that a thread will take.
Parallel Stream in Java
One of the prominent features of Java 8 (or higher) is Java Parallel Stream. It is meant for utilizing the
various cores of the processor. Usually, any Java code that has only one processing stream, where it is
sequentially executed. However, by using parallel streams, one can separate the Java code into more
than one stream, which is executed in parallel on their separate cores, and the end result is the
combination of the individual results. The order in which they are executed is not in our control. Hence,
it is suggested to use a parallel stream when the order of execution of individual items does not affect
the final result.
Analysis of Parallel Stream
For increasing the performance of a program, parallel streams are introduced. However, it is not a
guarantee that applying a parallel stream will enhance the result. For example, there can be a scenario
where code must be executed in a certain order. There are certain instances in which we need the code
to be executed in a certain order, and in such a case, it is required to use sequential streams instead of
parallel streams.
Different Ways to Create Stream
There are two ways we can create, which are listed below and described later as follows:
1. Using the parallel() method on a stream
2. Using parallelStream() on a Collection
Vestibulum urna lacus, eleifend venenatis ipsum at, venenatis fringilla mauris.
Fusce nulla augue, convallis at velit ac, pulvinar convallis eros.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac
turpis egestas. Sed ut ipsum molestie dolor dictum luctus.
Maecenas interdum erat feugiat rhoncus mattis. Phasellus facilisis ex non magna
faucibus mollis.
Vestibulum eu tellus nec lectus rutrum ornare ac tincidunt sem.
Explanation: In the above program, we have made a file object that points to a
[Link] file that is already present in the system. After that, a stream is created that does
reading from the text file (only one line at a time). Then we invoke the parallel() method to display the
content of the [Link] on the console. Note that the order of the execution is different each
time we execute the above code. The code is executed again; the following output is displayed on the
console.
Output 2:
FileName: [Link]
1. // Importing the required classes
2. import [Link].*;
3. import [Link];
4. import [Link];
5. import [Link];
6.
7.
8. // Main class
9. public class ParallelStream
10. {
11.
12. // Main method
13. public static void main(String[] argvs) throws IOException
14. {
15.
16. // Creating a File object
17. File f = new File("C:\\Users\\Nikhil\\Downloads\\ParallelStreams\\[Link]"); 18.
19. // Reading the lines of the file [Link] by
20. // making a List by invoking the method readAllLines()
21. List<String> text = [Link]([Link]());
22.
23. // Creating different parallel streams by making a List
24. // by invoking the method readAllLines()
25. [Link]().forEach([Link]::println);
26. }
27. }
28.
Output 1:
Explanation: In the above-mentioned code, we are using a parallel stream. However, we are using the
List to read from the [Link] file. Hence, the parallelstream() method is required.
Other Examples of Parallel Execution of Stream
Let's see a few more examples of parallel execution of streams.
FileName: [Link]
1. // important import statement
2. import [Link];
3.
4. public class ParallelStream1
5. {
6.
7. // main method
8. public static void main(String[] argvs)
9. {
10.
11. [Link]("In Normal");
12.
13. // prints values from 1 to 5 (1 and 5 included)
14. IntStream r = [Link](1, 5);
15. [Link]([Link]::println);
16.
17. [Link]("In Parallel");
18.
19. // prints values from 1 to 5 (1 and 5 included)
20. IntStream r1 = [Link](1, 5);
21. [Link]().forEach([Link]::println);
22.
23. }
24.
25. }
Output:
In Normal
1
2
3
4
5
In Parallel
3
5
4
2
1
Input Stream
Java application uses an input stream to read data from a source; it may be a file, an array, peripheral
device or socket.
Let's understand the working of Java OutputStream and InputStream class by the figure given below.
OutputStream Class
OutputStream class is an abstract class. It is the superclass of all classes representing an output stream
of bytes. An output stream accepts output bytes and sends them to some sink.
Useful Methods of OutputStream Class
Method Description
public void write(int) throws It is used to write a byte to the current output
IOException stream.
public void
It is used to write an array of byte to the
write(byte[])throws
current output stream.
IOException
public void flush() throws
It flushes the current output stream.
IOException
public void close() throws It is used to close the current output stream.
IOException
Method Description
public abstract int read() throws It reads the next byte of data from
IOException the input stream. It
returns -1 at the end of the file.
Non-textual data,
Textual data, strings,
Suitable for binary files,
human-readable info
multimedia
Not specifically
Convenient methods for
String Operations designed for string
string operations
operations
Byte-oriented, no
Reading Line by Line Convenient methods for
built-in line-reading
reading lines
methods
10 MARKS:
2. What is thread synchronization in Java? Discuss the role of synchronized blocks, and
compare synchronized methods versus synchronized blocks with examples.
4. Illustrate the producer-consumer problem using threads in Java, employing wait() and notify().
Explain how these methods facilitate inter-thread communication.
5. Explain the difference between byte streams and character streams in Java. Give
examples of commonly used classes in each category, and describe when each type
should be used.
UNIT IV
➢ Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface
(GUI) or windows-based applications in Java.
➢ Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system. AWT is heavy weight i.e. its components
are using the resources of underlying operating system (OS).
➢ The [Link] package provides classes for AWT API such
as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.
➢ The AWT tutorial will help the user to understand Java GUI programming in simple
and easy steps.
➢ Java AWT Hierarchy
➢ The hierarchy of Java AWT classes are given below.
Components
➢ All the elements like the button, text fields, scroll bars, etc. are called components. In
Java AWT, there are classes for each component as shown in above diagram. In order
to place every component in a particular position on a screen, we need to add them to a
container.
Container
➢ The Container is a component in AWT that can contain another components
like buttons, textfields, labels etc. The classes that extends Container class are known
as container such as Frame, Dialog and Panel.
Types of containers:
1. Window
2. Panel
3. Frame
4. Dialog
Window
The window is the container that have no borders and menu bars. You must use frame, dialog
or another window for creating a window. We need to create an instance of Window class to
create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc.
An instance of Panel class creates a container, in which we can add components.
Frame
The Frame is the container that contain title bar and border and can have menu bars. It can have
other components like button, text field, scrollbar etc. Frame is most widely used container
while developing an AWT application.
Method Description
public void setSize(int width,int height) Sets the size (width and height) of the
component.
1. Input Components
• Text Fields: Allow users to input text information (e.g., search bars, login fields).
• Checkboxes: Enable users to make binary choices; they can be checked or
unchecked.
• Radio Buttons: Allow users to select one option from a group.
• Dropdown Menus: Provide a list of options to select from, saving space.
• Sliders: Enable users to select a value or range by sliding a control.
2. Action Components
• Buttons: Trigger actions when clicked, like submitting a form or opening a link.
• Icon Buttons: Smaller buttons with an icon, often used for actions like editing,
deleting, or sharing.
• Floating Action Buttons (FABs): Circular buttons that promote primary actions,
commonly used in mobile apps.
3. Navigation Components
4. Display Components
• Cards: Containers that present information or actions, often used for showcasing
individual items in a list.
• Tables: Present data in a grid format, useful for organizing structured information.
• Lists: Display items in a sequential format, often with a consistent layout.
• Modals/Dialogs: Pop-up windows that overlay the main interface to capture the
user’s attention for critical actions.
5. Feedback Components
• Labels: Text that describes input fields, making forms more accessible and easier to
understand.
• Error Messages: Appear when users input invalid data, guiding them on what needs
to be corrected.
• Submit and Reset Buttons: Essential for forms, allowing users to complete or reset
the input fields.
7. Utility Components
• Accordions: Expandable sections that reveal or hide content, useful for FAQs and
minimizing clutter.
• Breadcrumbs: Help users understand the site hierarchy and easily navigate back to
previous levels.
• Carousel/Slider: Allow users to scroll through images or items horizontally or
vertically.
These components, when combined effectively, create an intuitive and smooth user
experience that aligns with the goals of the application or website.
Basic UI Components:
1. Labels:
o Labels are non-interactive text components used to display information or
descriptions near other components (like input fields).
o In Java’s Swing, a label can be created using JLabel.
2. Button Text Components:
o Buttons are interactive components that perform an action when clicked. They
can have text, icons, or both.
o In Java, JButton represents a button component.
3. Checkbox:
o A checkbox is a small square that can either be checked or unchecked,
representing a binary choice.
o In Swing, checkboxes are created using JCheckBox.
4. Checkbox Group:
o A checkbox group contains multiple checkboxes, allowing users to select
multiple options.
o In Swing, while checkboxes are independent, a set of checkboxes can be
logically grouped for a cleaner UI.
5. Choice:
o Also known as a dropdown or combo box, a choice component allows users to
select one item from a list.
o In Swing, JComboBox or JList can represent a choice component.
6. List Box:
o A list box displays a list of items, often allowing multiple selections.
o In Swing, JList is used to create a list box.
Container Components:
7. Panels:
o Panels are container components used to group other UI components together.
o In Swing, JPanel is used as a basic container.
8. Scroll Pane:
o A scroll pane allows content to be scrollable, useful for large data sets or
images.
o In Swing, JScrollPane wraps around components that need scrolling, like
tables, lists, or images.
9. Menu:
o A menu component provides a list of commands or options, typically
organized within a menu bar at the top of a window.
o In Swing, menus are created using JMenuBar, JMenu, and JMenuItem.
10. Scroll Bar:
• A scroll bar allows the user to navigate vertically or horizontally through content that
doesn’t fit within the visible area.
• Swing provides JScrollBar to create standalone scroll bars.
Color:
Fonts:
Layout Managers:
EventHandling
➢ An event can be defined as changing the state of an object or behavior by
performing actions.
➢ Actions can be a button click, cursor movement, keypress through keyboard or
page scrolling, etc.
➢ The [Link] package can be used to provide various event classes.
Classification of Events
• Foreground Events
• Background Events
1. Foreground Events
➢ Foreground events are the events that require user interaction to generate, i.e.,
foreground events are generated due to interaction by the user on components in
Graphic User Interface (GUI).
➢ Interactions are nothing but clicking on a button, scrolling the scroll bar, cursor
moments, etc.
2. Background Events
➢ Events that don’t require interactions of users to generate are known as background
events. Examples of these events are operating system failures/interrupts, operation
completion, etc.
Event Handling
➢ It is a mechanism to control the events and to decide what should happen after an
event occur. To handle the events, Java follows the Delegation Event model.
• Source: Events are generated from the source. There are various sources like buttons,
checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc., to
generate events.
• Listeners: Listeners are used for handling the events generated from the source. Each
of these listeners represents interfaces that are responsible for handling events.
➢ To perform Event Handling, we need to register the source with the listener.
➢ Registering the Source With Listener
➢ Different Classes provide different registration methods.
Syntax:
addTypeListener()
visibility.
ActionListener • actionPerformed()
AdjustmentListener • adjustmentValueChanged()
Listener Interface Methods
• componentResized()
• componentShown()
ComponentListener
• componentMoved()
• componentHidden()
• componentAdded()
ContainerListener
• componentRemoved()
• focusGained()
FocusListener
• focusLost()
ItemListener • itemStateChanged()
• keyTyped()
KeyListener • keyPressed()
• keyReleased()
• mousePressed()
• mouseClicked()
MouseListener • mouseEntered()
• mouseExited()
• mouseReleased()
• mouseMoved()
MouseMotionListener
• mouseDragged()
MouseWheelListener • mouseWheelMoved()
TextListener • textChanged()
• windowActivated()
• windowDeactivated()
• windowOpened()
WindowListener • windowClosed()
• windowClosing()
• windowIconified()
• windowDeiconified()
Flow of Event Handling
Code-Approaches
The three approaches for performing event handling are by placing the event handling
code in one of the below-specified places.
1. Within Class
2. Other Class
3. Anonymous Class
Events
Each event has specific methods to provide information about the event, such as its type, the
component that triggered it, and details like the mouse coordinates or which key was pressed.
Event Sources
➢ An Event Source is an object that generates events. When an event occurs (e.g., a
user clicks a button), the event source notifies any event listeners that are registered to
handle that event. Some common event sources include:
1. Button: A button is an event source for ActionEvent, triggered when the button is
clicked.
2. Text Field: A text field generates ActionEvent (when "Enter" is pressed) and
FocusEvent (when it gains or loses focus).
3. Window: Windows, such as frames or dialogs, generate WindowEvent (e.g., on
opening or closing).
4. Mouse: Components that are sensitive to mouse actions, like panels, generate
MouseEvent and MouseMotionEvent.
5. Keyboard: Components that accept keyboard input generate KeyEvent.
The event source holds a list of listeners that are registered to receive notifications about
specific events. When an event occurs, the event source invokes the appropriate method on
each registered listener.
import [Link].*;
import [Link];
import [Link];
public class EventSourceExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Event Source Example");
JButton button = new JButton("Click Me");
// Register the button (event source) with an ActionListener (event listener)
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
[Link]("Button was clicked!");
}
});
[Link](button);
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
1. Event Creation: When an action occurs, the event source (e.g., button) generates an
event object (ActionEvent).
2. Event Dispatching: The event is dispatched to the registered listeners. The
actionPerformed method in ActionListener is called automatically.
3. Event Handling: The listener executes the code within the event handler method,
creating the response (in this case, printing to the console).
Examples of Event Sources in Different UI Components
Event-driven programming often follows the Observer Pattern, where the event source acts
as a subject, notifying registered observers (listeners) of changes (events). The listeners can
then react independently, making the UI more interactive and modular.
Event Listeners
➢ Event Listeners are interfaces in Java (and other languages with similar patterns) that
handle various types of events, such as user actions (clicks, key presses, etc.).
➢ In Java, event listeners belong to the [Link] and [Link] packages.
They "listen" for specific events on UI components and execute code in response.
Here’s an overview of how event listeners work, some common event listener types, and an
example of implementing them.
1. Define and Register the Listener: An event listener is an interface with one or more
methods related to a specific type of event. You register a listener to a component
using methods like addActionListener, addMouseListener, etc.
2. Event Triggering: When an event occurs (e.g., a button is clicked), the registered
listener(s) is notified.
3. Handle the Event: The listener’s event handling method(s) are automatically called,
executing any code inside.
Here are some frequently used event listener interfaces, along with their related events and
methods:
1. ActionListener
o Purpose: Handles ActionEvent, typically used for buttons, menu items, and
other actions.
o Method: void actionPerformed(ActionEvent e)
o Example Usage: Clicking a button or pressing "Enter" in a text field.
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Button was clicked!");
}
});
2. MouseListener
java
Copy code
[Link](new MouseListener() {
public void mouseClicked(MouseEvent e) {
[Link]("Mouse clicked on button");
}
// Implement other methods if needed
});
3. MouseMotionListener
4. KeyListener
java
Copy code
[Link](new KeyListener() {
public void keyPressed(KeyEvent e) {
[Link]("Key pressed: " + [Link]());
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
});
5. WindowListener
o Purpose: Handles events related to window state (e.g., open, close, minimize).
o Methods:
void windowOpened(WindowEvent e)
void windowClosing(WindowEvent e)
void windowClosed(WindowEvent e)
void windowIconified(WindowEvent e)
void windowDeiconified(WindowEvent e)
void windowActivated(WindowEvent e)
void windowDeactivated(WindowEvent e)
java
Copy code
[Link](new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link]("Window is closing");
[Link](0);
}
});
6. FocusListener
o Purpose: Responds to focus events, like gaining or losing focus.
o Methods:
1. void focusGained(FocusEvent e)
2. void focusLost(FocusEvent e)
7. ItemListener
o Purpose: Handles item selection events (e.g., checkboxes, combo boxes).
o Method: void itemStateChanged(ItemEvent e)
java
Copy code
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if ([Link]() == [Link]) {
[Link]("Checkbox selected");
}
}
});
8. ChangeListener
o Purpose: Handles change events, used with components like sliders or
spinners.
o Method: void stateChanged(ChangeEvent e)
➢ Some listeners have multiple methods, but sometimes you only need one or two.
Adapter classes provide default implementations, so you only override the methods
you need. Common adapters include:
java
Copy code
[Link](new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
[Link]("Window closing");
}
});
➢ Since Java 8, lambda expressions can be used to write shorter code for single-method
listeners (like ActionListener or ItemListener):
java
Copy code
[Link](e -> [Link]("Button clicked!"));
[Link](e -> [Link]("Checkbox state changed"));
Example Program: Using Multiple Event Listeners
This example program creates a GUI with a button, a text field, and a checkbox, each with
their own event listeners:
import [Link].*;
import [Link].*;
public class EventListenerExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Event Listener Example");
JButton button = new JButton("Click Me");
JTextField textField = new JTextField(20);
JCheckBox checkBox = new JCheckBox("Check Me");
[Link](panel);
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
➢ The Event Delegation Model (EDM) is a design approach used in Java (and other
event-driven frameworks) to handle events in a more organized and efficient way.
➢ The model is built around three core concepts: event sources, events, and event
listeners.
➢ Rather than every UI component processing its own events, the Event Delegation
Model delegates responsibility for handling events to a dedicated listener object.
➢ This approach enhances code modularity, scalability, and performance.
➢ In the EDM, when an event occurs (e.g., a button is clicked), the event source
generates an event object that contains information about the event.
➢ This event object is then passed to one or more listeners that are registered to handle
the event.
➢ The model follows the Observer pattern, where listeners (observers) "listen" for
events from event sources (subjects) and respond accordingly.
1. Event Source
o The component that generates the event, such as a button, text field, or
window.
o Registers listeners to notify them when a specific event occurs.
2. Event Object
o An object that encapsulates information about an event, such as its type (e.g.,
ActionEvent, MouseEvent) and additional data (e.g., mouse coordinates or key
codes).
o Provides methods to access event details and identify the event source.
3. Event Listener
o An interface or class with methods to respond to specific event types.
o Listens to events generated by the event source and defines how to handle
them.
o Registered with an event source through methods like addActionListener,
addMouseListener, etc.
Here’s a simple Java example demonstrating the Event Delegation Model using JButton as an
event source and ActionListener as an event listener:
java
Copy code
import [Link].*;
import [Link];
import [Link];
public class EventDelegationExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Event Delegation Model Example");
JButton button = new JButton("Click Me");
[Link](button);
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
Explanation:
java
Copy code
➢ Java Swing and AWT aren’t the only UI frameworks that use EDM. Other
frameworks with similar models include:
• JavaScript DOM Events: In JavaScript, events such as click or keyup use an event
delegation model. Event listeners are registered with DOM elements, and event
handlers respond when events are triggered.
• Android: In Android, events are handled by [Link],
[Link], and similar interfaces for touch and sensor events.
Best Practices in the Event Delegation Model
MouseListener Interface
This interface has five methods, which respond to specific mouse actions:
MouseMotionListener Interface
@Override
public void mousePressed(MouseEvent e) {
[Link]("Mouse pressed");
}
@Override
public void mouseReleased(MouseEvent e) {
[Link]("Mouse released");
}
@Override
public void mouseEntered(MouseEvent e) {
[Link]("Mouse entered the button area");
}
@Override
public void mouseExited(MouseEvent e) {
[Link]("Mouse exited the button area");
}
});
@Override
public void mouseMoved(MouseEvent e) {
[Link]("Mouse moved at coordinates: " + [Link]() + ", " +
[Link]());
}
});
add(button);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
1. Using MouseAdapter
If you only need to handle some mouse events, you can use the MouseAdapter class, which
provides default implementations for MouseListener and MouseMotionListener methods, so
you can override only the ones you need.
[Link](new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
[Link]("Mouse clicked!");
}
});
The KeyListener interface is used to handle keyboard events. This interface has three
methods:
KeyEvent Methods
@Override
public void keyReleased(KeyEvent e) {
[Link]("Key released: " +
[Link]([Link]()));
}
@Override
public void keyTyped(KeyEvent e) {
[Link]("Key typed: " + [Link]());
}
});
add(textField);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
Keyboard Shortcuts
In some applications, you may want specific keys to trigger actions. KeyBindings can be a
more modern approach than KeyListener for complex key shortcuts, as it allows assigning
actions directly to components using key-stroke mappings.
[Link](JComponent.WHEN_FOCUSED).put([Link]
e("ctrl Z"), "Undo");
[Link]().put("Undo", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
[Link]("Undo action performed");
}
});
Handling mouse and keyboard events in Java allows you to make applications interactive by
responding to user actions, such as mouse clicks, movements, and keyboard presses. These
events are managed by event listeners, specifically MouseListener, MouseMotionListener,
and KeyListener for mouse and keyboard events, respectively.
This interface has five methods, which respond to specific mouse actions:
MouseMotionListener Interface
@Override
public void mousePressed(MouseEvent e) {
[Link]("Mouse pressed");
}
@Override
public void mouseReleased(MouseEvent e) {
[Link]("Mouse released");
}
@Override
public void mouseEntered(MouseEvent e) {
[Link]("Mouse entered the button area");
}
@Override
public void mouseExited(MouseEvent e) {
[Link]("Mouse exited the button area");
}
});
@Override
public void mouseMoved(MouseEvent e) {
[Link]("Mouse moved at coordinates: " + [Link]() + ", " + [Link]());
}
});
add(button);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
Using MouseAdapter
➢ If you only need to handle some mouse events, you can use the MouseAdapter class,
which provides default implementations for MouseListener and
MouseMotionListener methods, so you can override only the ones you need.
java
Copy code
[Link](new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
[Link]("Mouse clicked!");
}
});
The KeyListener interface is used to handle keyboard events. This interface has three
methods:
KeyEvent Methods
@Override
public void keyReleased(KeyEvent e) {
[Link]("Key released: " + [Link]([Link]()));
}
@Override
public void keyTyped(KeyEvent e) {
[Link]("Key typed: " + [Link]());
}
});
add(textField);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
➢ In some applications, you may want specific keys to trigger actions. KeyBindings can
be a more modern approach than KeyListener for complex key shortcuts, as it allows
assigning actions directly to components using key-stroke mappings.
java
Copy code
[Link](JComponent.WHEN_FOCUSED).put([Link]("ctrl
Z"), "Undo");
[Link]().put("Undo", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
[Link]("Undo action performed");
}
});
1. Use Adapters if Needed: For complex listeners, use MouseAdapter and KeyAdapter
to override only necessary methods.
2. Keep Event Handlers Lightweight: Avoid long-running tasks within event methods
to keep the UI responsive.
3. Use Lambda Expressions: In Java 8+, lambdas make it easier to write concise
listener code for simple actions.
4. Consider Accessibility: Ensure that keyboard shortcuts and mouse interactions are
intuitive and that alternative inputs are accessible.
Adapter Classes
➢ Adapter classes are abstract classes in Java that provide empty implementations of all
methods in an interface.
➢ They are commonly used with event listener interfaces that have multiple methods,
such as MouseListener, MouseMotionListener, or WindowListener.
➢ Adapter classes allow you to override only the methods you need, rather than
implementing every method in the interface, even if you don't use them.
➢ Adapter classes reduce the need to implement all methods in an interface when only a
few are relevant.
➢ They simplify code by providing default implementations for methods you don’t
need, allowing you to focus on those you do.
Examples of Adapter Classes in Java
add(button);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
Explanation: Here, MouseAdapter allows you to implement only the mouseClicked method
without the need to override mousePressed, mouseReleased, etc., which MouseListener
would require if you implemented it directly.
Inner Classes
➢ Inner classes are classes defined within another class. They have access to the fields
and methods of the outer class, even if they are private. Java supports several types of
inner classes:
1. Non-static Inner Classes (or Regular Inner Classes): These are tied to an instance
of the outer class and can access its instance variables and methods.
2. Static Inner Classes: Defined with the static keyword, they do not require an instance
of the outer class and can only access static members of the outer class.
3. Anonymous Inner Classes: These are inner classes without a name, typically used to
define one-off event listeners or interface implementations.
4. Local Inner Classes: Defined within a method or block, these classes are accessible
only within the scope of that method or block.
➢ Inner classes are useful when you need to create small helper classes, especially for
event handling, that are tightly coupled with an outer class. They help organize code
by keeping classes that are only relevant to a specific part of your application
contained within that scope.
➢ A regular inner class can be useful if you want to handle events in a dedicated listener
class that still has access to the outer class's fields and methods.
import [Link].*;
import [Link].*;
public InnerClassExample() {
button = new JButton("Click Me");
[Link](new ButtonClickListener());
add(button);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
➢ Anonymous inner classes are often used for quick event handling because they are
concise and only require one-time use.
java
Copy code
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
[Link]("Button clicked!");
}
});
In Java 8 and later, you can simplify this further with a lambda expression if the interface has
only one method:
java
Copy code
[Link](e -> [Link]("Button clicked!"));
➢ Local inner classes are defined inside a method, and they’re often used when the logic
is specific to that method.
java
Copy code
public void createButtonWithListener() {
class ButtonClickListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
[Link]("Button clicked from a local inner class!");
}
}
• Adapter Classes are useful for selectively overriding specific methods in interfaces
with multiple methods, like MouseListener. They’re typically used when you want to
simplify code by avoiding the implementation of unnecessary methods.
• Inner Classes are suitable when you want to create a helper class closely tied to the
outer class. They provide access to the outer class's methods and fields, making them
useful for event handling and other tasks that require access to the outer class.
Best Practices
MCQ’S
1. What is the purpose of a Label in AWT?
a) To display text b) To receive user input
c) To perform an action d) To display an image
2. Which method is used to set the text of a Label?
a) setText() b) getText() c) setLabel() d) getLabel()
3. Which class is the superclass of Button and TextField?
a) Component b) Container c) Panel d) Frame
4. What is the purpose of the ActionListener interface?
a) To handle mouse events b) To handle keyboard events
c) To handle button clicks d) To handle text input
5. What is the purpose of a CheckBox?
a) To select multiple options b) To select a single option
c) To display text d) To receive user input
6. Which class is used to group CheckBoxes?
a) CheckboxGroup b) RadioButton c) Choice d) List
7. What is the purpose of a Choice?
a) To select a single option b) To select multiple options
c) To display text d) To receive user input
8. Which method is used to add items to a List?
a) add() b) addItem() c) addElement() d) addList()
9. What is the purpose of a Panel?
a) To group components b) To display text
c) To receive user input d) To perform an action
10. Which class is used to add scrolling capability to a component?
a) ScrollPane b) ScrollBar c) Panel d) Frame
11. What is the purpose of a Menu?
a) To provide options to the user b) To display text
c) To receive user input d) To perform an action
12. Which class is used to create a menu item?
a) MenuItem b) Menu c) MenuBar d) CheckboxMenuItem
13. What is the purpose of a ScrollBar?
a) To add scrolling capability to a component b) To display text
c) To receive user input d) To perform an action
14. Which method is used to set the scroll bar's minimum value?
a) setMinimum() b) setMaximum() c) setValue() d) setUnitIncrement()
15. What is the purpose of a Frame?
a) To provide a window for an application b) To display text
c) To receive user input d) To perform an action
16. Which method is used to set the title of a Frame?
a) setTitle() b) getTitle() c) setLabel() d) getLabel()
17. Which class is used to represent color?
a) Color b) Font c) Graphics d) FontMetrics
18. Which method is used to set the font of a component?
a) setFont() b) getFont() c) setLabel() d) getLabel()
19. What is the purpose of a Layout Manager?
a) To arrange components in a container b) To display text
c) To receive user input d) To perform an action
20. Which layout manager is used to arrange components in a grid?
a) GridLayout b) FlowLayout c) BorderLayout d) CardLayout
21. What is an event in Java?
a) A user interaction with a GUI component b) A system-generated notification
c) A method call d) A variable declaration
22. Which of the following is an example of an event?
a) Button click b) Variable assignment c) Method invocation d) Loop iteration
23. What is an event source in Java?
a) A GUI component that generates events b) A listener interface
c) A handler method d) A event object
24. Which of the following is an example of an event source?
a) JButton b) ActionListener c) actionPerformed() d) ActionEvent
25. What is an event listener in Java?
a) A method that handles events b) A GUI component that generates events
c) An interface that defines event handling methods d) An event object
26. Which of the following is an example of an event listener interface?
a) ActionListener b) ActionEvent c) JButton d) JFrame
27. What is the purpose of the actionPerformed() method?
a) To handle action events b) To handle mouse events
c) To handle keyboard events d) To handle window events
8. Which method is called when a button is clicked?
a) actionPerformed() b) mouseClicked() c) keyTyped() d) windowOpened()
29. How do you register an event listener with a GUI component?
a) Using the addListener() method b) Using the addActionListener() method
c) Using the addMouseListener() method d) Using the addKeyListener() method
30. What happens when an event listener is not registered with a GUI component?
a) The event is ignored b) The event is handled by a default listener
c) The event is propagated to the parent component d) An exception is thrown
31. What is the primary purpose of the Event Delegation Model?
a) To handle events directly by GUI components
b) To delegate event handling to separate objects
c) To propagate events to parent components d) To ignore events
32. Which of the following is a key benefit of using EDM?
a) Improved performance b) Simplified event handling
c) Increased complexity d) Reduced flexibility
33. In EDM, what is the role of an event source?
a) To handle events b) To generate events
c) To delegate events d) To ignore events
34. What is the role of an event listener in EDM?
a) To generate events b) To handle events c) To delegate events d) To ignore events
35. How do you register an event listener with an event source in EDM?
a) Using the addListener() method b) Using the addActionListener() method
c) Using the addMouseListener() method d) Using the registerListener() method
36. What happens when an event is received by an event listener?
a) It is ignored b) It is propagated to the parent component
c) It is handled by the listener d) It is delegated to another listener
37. What is a primary advantage of using EDM?
a) Improved performance b) Simplified event handling
c) Increased complexity d) Reduced flexibility
38. What is a potential disadvantage of using EDM?
a) Increased flexibility b) Improved performance
c) Tight coupling between components d) Reduced complexity
39. How does EDM differ from the Event-Inheritance Model?
a) EDM uses inheritance, while Event-Inheritance Model does not
b) EDM uses delegation, while Event-Inheritance Model uses inheritance
c) EDM is more complex, while Event-Inheritance Model is simpler
d) EDM is less flexible, while Event-Inheritance Model is more flexible
40. What is a key similarity between EDM and the Observer Pattern?
a) Both use inheritance b) Both use delegation
c) Both use event handling d) Both use observer-subject relationships
41. Which interface is used to handle mouse events in Java?
a) MouseListener b) MouseMotionListener c) KeyListener d) ActionListener
42. What method is called when the mouse is clicked?
a) mouseClicked() b) mousePressed() c) mouseReleased() d) mouseEntered()
43. Which method is used to track mouse movements?
a) mouseMoved() b) mouseDragged() c) mousePressed() d) mouseReleased()
44. Which interface is used to handle keyboard events in Java?
a) KeyListener b) MouseListener c) ActionListener d) WindowListener
45. What method is called when a key is pressed?
a) keyPressed() b) keyReleased() c) keyTyped() d) mouseClicked()
46. What is the purpose of an adapter class?
a) To provide a default implementation for an interfaceb) To extend an abstract class
c) To implement multiple interfaces d) To override a method
47. Which adapter class is used for mouse events?
a) MouseAdapter b) KeyAdapter c) WindowAdapter d) ActionListener
48. What is an inner class in Java?
a) A class within another class b) A subclass of another class
c) An interface implementation d) An abstract class
49. What is the benefit of using inner classes?
a) Improved encapsulation b) Increased complexity
c) Reduced flexibility d) Simplified inheritance
50. Which type of inner class is used to handle events?
a) Nested class b) Static inner class
c) Anonymous inner class d) Local inner class
5 MARK QUESTIONS
10-MARK QUESTIONS
UNIT V
SWING
➢ Swing is a Java Foundation Classes [JFC] library and an extension of the
Abstract Window Toolkit [AWT].
➢ Java Swing offers much-improved functionality over AWT, new components,
expanded components features, and excellent event handling with drag-and-
drop support.
➢ There are certain points from which Java Swing is different than Java AWT
as mentioned below:
Java AWT Java Swing
Execution Time is more than Swing. Execution Time is less than AWT.
What is JFC?
➢ JFC stands for Java Foundation Classes. JFC is the set of GUI components
that simplify desktop Applications.
➢ Many programmers think that JFC and Swing are one and the same thing, but
that is not so.
➢ JFC contains Swing [A UI component package] and quite a number of other
items:
• Cut and paste: Clipboard support.
• Accessibility features: Aimed at developing GUIs for users with disabilities.
• The Desktop Colors Features were first introduced in Java 1.1
• Java 2D: it has Improved colors, images, and text support.
• Pluggable Look and Feel: This feature enable the user to switch the look and
feel of Swing components without restarting an application. The Swing library
supports components’ look and feels that remain the same across all platforms
wherever the program runs. The Swing library provides an API that gives real
flexibility in determining the look and feel of the GUI of an application
• Rich controls– Swing provides a rich set of advanced controls like Tree
TabbedPane, slider, colorpicker, and table controls.
1. JFrame
• Description: A window with title, borders, and buttons (e.g., close, minimize).
• Usage: Used for creating main application windows.
• Key Features:
o Can contain menus, panels, and other components.
o Provides methods like setSize(), setVisible(),
setDefaultCloseOperation().
Example:
java
Copy code
import [Link].*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("My JFrame");
[Link](400, 300);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
2. JApplet
Note: Java Applets are obsolete as modern browsers no longer support them.
3. JDialog
Example:
java
Copy code
import [Link].*;
Example:
java
Copy code
import [Link].*;
These top-level containers act as the foundation for building Java desktop
applications. Each serves different purposes, and their choice depends on the specific
requirements of your GUI.
1. JFrame
Example:
java
Copy code
JFrame frame = new JFrame("My JFrame");
[Link](400, 300);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
2. JWindow
Example:
java
Copy code
JWindow window = new JWindow();
[Link](300, 200);
[Link](true);
3. JDialog
Example:
java
Copy code
JDialog dialog = new JDialog(frame, "My Dialog", true);
[Link](200, 100);
[Link](true);
4. JPanel
Example:
java
Copy code
JPanel panel = new JPanel();
[Link](new JButton("Click Me"));
[Link](panel);
5. JButton
Example:
java
Copy code
JButton button = new JButton("Click Me");
[Link](e -> [Link]("Button clicked"));
6. JToggleButton
Example:
java
Copy code
JToggleButton toggleButton = new JToggleButton("Toggle Me");
[Link](e -> [Link]("State changed!"));
7. JCheckBox
Example:
java
Copy code
JCheckBox checkBox = new JCheckBox("Enable Feature");
[Link](e -> [Link]("Checked: " +
[Link]()));
8. JRadioButton
Example:
java
Copy code
JRadioButton radioButton1 = new JRadioButton("Option 1");
JRadioButton radioButton2 = new JRadioButton("Option 2");
ButtonGroup group = new ButtonGroup();
[Link](radioButton1);
[Link](radioButton2);
9. JLabel
Example:
java
Copy code
JLabel label = new JLabel("Enter your name:");
10. JTextField
Example:
java
Copy code
JTextField textField = new JTextField(20);
11. JTextArea
Example:
java
Copy code
JTextArea textArea = new JTextArea(5, 20);
12. JList
Example:
java
Copy code
JList<String> list = new JList<>(new String[] {"Item 1", "Item 2", "Item 3"});
13. JComboBox
Example:
java
Copy code
JComboBox<String> comboBox = new JComboBox<>(new String[] {"Option
1", "Option 2", "Option 3"});
14. JScrollPane
Example:
java
Copy code
JTextArea textArea = new JTextArea(5, 20);
JScrollPane scrollPane = new JScrollPane(textArea);
[Link](scrollPane);
MCQ’S
1. Swing is a part of which Java package?
a. [Link] b. [Link] c. [Link] d. [Link]
2. Swing components are:
a. Heavyweight b. Lightweight
c. Both heavyweight and lightweight d. None of the above
3. Which is the parent class of all Swing components?
a. Component b. Container c. JComponent d. Object
4. What is the key difference between AWT and Swing?
a. Swing is platform-dependent.
b. AWT uses a lightweight UI toolkit.
c. Swing provides pluggable look-and-feel.
d. AWT has more components than Swing.
5. Which method is used to make a Swing component visible?
a. setShow(true) b. setVisible(true) c. show(true) d. display(true)
6. Which of these is a top-level container in Swing?
a. JPanel b. JFrame c. JButton d. JLabel
7. The hierarchy of Swing components starts with which class?
a. [Link] b. [Link]
c. [Link] d. [Link]
8. Which of the following is not a Swing top-level container?
a. JFrame b. JDialog c. JWindow d. JToggleButton
9. Which component can hold other components?
a. JLabel b. JButton c. JPanel d. JComboBox
10. What is the purpose of [Link]?
a. Handles layout management.
b. Provides base for building GUI components.
c. Manages event handling.
d. None of the above.
11. JFrame is used for:
a. Pop-up dialogs b. Embedding web content
c. Creating the main window d. Adding scrollable content
12. What method is used to set the default close operation in JFrame?
a. setCloseOperation() b. setDefaultOperation()
c. setDefaultCloseOperation() d. setCloseAction()
13. JDialog is typically used for:
a. Splash screens b. Alerts and confirmations
c. Primary application windows d. Embedding media content
14. What distinguishes JWindow from JFrame?
a. JWindow does not have a title bar. b. JWindow is heavier than JFrame.
c. JWindow supports menus. d. JWindow can be a top-level container.
15. Which method is common in all top-level containers for adding components?
a. setComponent() b. add() c. insert() d. append()
16. JPanel is primarily used for:
a. Displaying text b. Organizing components
c. Handling events d. Creating pop-up menus
17. JButton generates which type of event?
a. FocusEvent b. KeyEvent c. ActionEvent d. MouseEvent
18. To set the label of a JButton, which method is used?
a. setLabel() b. setText() c. setName() d. setTitle()
19. JToggleButton maintains:
a. A single state b. Two states (selected/unselected)
c. A counter d. None of the above
20. Which of the following is true for JCheckBox?
a. It supports only one selection at a time.
b. It can toggle between checked and unchecked states.
c. It is used for radio button groups.
d. None of the above.
21. Which class is used to group JRadioButton components?
a. JPanel b. ButtonGroup c. RadioGroup d. JCheckBoxGroup
22. JLabel is:
a. Clickable b. Editable c. Non-interactive d. Resizable
23. Which method retrieves the text from a JTextField?
a. getInput() b. getValue() c. getText() d. retrieveText()
24. JTextArea supports:
a. Single-line input b. Multi-line input c. Dropdowns d. Checkboxes
25. Which of these can JList display?
a. A single item only b. Multiple items with or without selection
c. A dropdown d. Radio buttons
26. JComboBox combines:
a. Radio buttons and lists b. Dropdowns and checkboxes
c. Editable fields and dropdowns d. Labels and buttons
27. To add scrolling functionality to a JTextArea, which component is used?
a. JScrollPane b. JScrollField c. JScrollArea d. JTextScroll
28. Which layout manager is default in JPanel?
a. FlowLayout b. BorderLayout c. GridLayout d. CardLayout
29. What is the return type of add() method in Swing components?
a. void b. Boolean c. Component d. Container
30. What happens if you set the JFrame layout to null?
a. Components are automatically placed. b. Layout manager is disabled.
c. Program throws an exception. d. Nothing changes.
31. What method is used to set the text of a JLabel?
a. setLabel() b. setText() c. setTitle() d. setValue()
32. To add an icon to a JButton, you use:
a. setIcon() b. setImage() c. setGraphics() d. setPicture()
33. Which of these is not a valid constructor for JTextField?
a. JTextField() b. JTextField(int columns)
c. JTextField(String text) d. JTextField(String text, boolean editable)
34. Which method is used to add items to a JComboBox?
a. insertItem() b. add() c. addItem() d. appendItem()
35. JScrollPane can be added to which of the following components?
a. JTextArea b. JList c. JTable d. All of the above
36. Which listener is used to handle button click events?
a. ActionListener b. FocusListener c. KeyListener d. MouseListener
37. What is the method implemented by the ActionListener interface?
a. action() b. actionPerformed() c. performAction() d. onAction()
38. Which listener handles changes in a JToggleButton state?
a. ActionListener b. ItemListener c. ChangeListener d. KeyListener
39. What type of event does a JCheckBox generate when clicked?
a. ItemEvent b. ActionEvent c. FocusEvent d. KeyEvent
40. How do you add an event listener to a JButton?
a. [Link]() b. [Link]()
c. [Link]() d. [Link]()
41. Which layout manager arranges components in a single row or column?
a. BorderLayout b. FlowLayout c. GridLayout d. BoxLayout
42. What is the default layout for JFrame?
a. FlowLayout b. BorderLayout c. GridLayout d. BoxLayout
43. To divide a container into equal-sized cells, which layout manager is used?
a. FlowLayout b. GridLayout c. BorderLayout d. CardLayout
44. Which component provides a tabbed interface?
a. JTabbedPane b. JTabbedView c. JTabbedPanel d. JTabPane
45. What is JTable primarily used for?
a. Displaying text b. Displaying rows and columns of data
c. Managing layout d. Handling events
46. Which Swing component allows horizontal and vertical splitting of panes?
a. JViewport b. JSplitPane c. JScrollPane d. JPanel
47. Which method is used to pack a JFrame to fit its components?
a. setFit() b. autoResize() c. pack() d. setAutoSize()
48. What does setEditable(false) do for a JTextField?
a. Makes the text field unselectable.
b. Prevents user input but allows text selection.
c. Disables the text field completely.
d. Clears the content of the text field.
49. What is the primary difference between JList and JComboBox?
a. JList supports scrolling, but JComboBox doesn’t.
b. JComboBox is a dropdown, while JList is a scrollable list.
c. JComboBox allows multiple selections.
d. JList can’t be editable.
50. Which Swing component is suitable for displaying a multi-line label or rich text?
a. JTextField b. JLabel c. JTextArea d. JEditorPane
5 MARK QUESTIONS
*****UNIT V COMPLETED*****
UNIT I – SHORT NOTES
Object-Oriented Concepts:
➢ Object-oriented programming (OOP) is a programming paradigm that revolves around the
concept of objects and classes. Here are some key OOP concepts:
1. Classes: A class is a blueprint or a template that defines the properties and behavior of an object.
2. Objects: An object is an instance of a class, and it has its own set of attributes (data) and methods
(functions).
3. Inheritance: Inheritance is the mechanism by which one class can inherit the properties and
behavior of another class.
4. Polymorphism: Polymorphism is the ability of an object to take on multiple forms, depending on
the context.
5. Encapsulation: Encapsulation is the concept of hiding an object's internal details and exposing
only the necessary information.
6. Abstraction: Abstraction is the concept of showing only the essential features of an object and
hiding the internal details.
History of Java:
Java is an object-oriented programming language developed by James Gosling and his team at Sun
Microsystems (now owned by Oracle Corporation). Here's a brief history of Java:
1. 1991: James Gosling begins working on a project called "Oak," which later becomes Java.
2. 1995: Java 1.0 is released, and it quickly gains popularity as a platform-independent language.
3. 1997: Java 1.1 is released, which adds important features like inner classes and reflection.
4. 2000: Java 2 is released, which introduces a new namespace and package system.
5. 2004: Java 5 is released, which adds important features like generics and annotations.
6. 2011: Oracle Corporation acquires Sun Microsystems and takes over Java development.
7. 2017: Java 9 is released, which introduces a new module system and improves performance.
Today, Java is one of the most popular programming languages in the world, widely used in
enterprise software development, Android app development, and web development
Java buzzwords:
1. Platform Independence: Java is known for its "write once, run anywhere" capability, meaning
that Java code can run on any device that has a Java Virtual Machine (JVM) installed.
2. Object-Oriented: Java is an object-oriented language that supports the principles of
encapsulation, inheritance, and polymorphism.
3. Robust Security: Java has built-in security features like memory management and secure class
loading to prevent common programming errors like null pointer exceptions and data corruption.
4. Multithreading: Java has built-in support for multithreading, which allows developers to create
high-performance applications that can run multiple tasks concurrently.
5. Dynamic Loading of Classes: Java's dynamic class loading capability allows classes to be loaded
into memory only when they are needed, which improves performance and reduces memory usage.
6. Autoboxing and Unboxing: Java's autoboxing and unboxing feature allows developers to
automatically convert between primitive types and their corresponding object wrapper classes.
7. Annotations: Java's annotation feature allows developers to add metadata to their code that can
be used by the compiler or other tools to generate code or perform other tasks.
8. Generics: Java's generics feature allows developers to create type-safe collections and other data
structures that can be reused across different types.
9. Lambda Expressions: Java's lambda expression feature allows developers to create concise and
expressive representations of functional interfaces.
10. Functional Programming: Java's functional programming features, such as lambda expressions
and method references, allow developers to write more concise and expressive code.
11. Modular Programming: Java's modular programming feature, introduced in Java 9, allows
developers to create and maintain large-scale applications more easily.
12. Reactive Programming: Java's reactive programming features, such as Reactive Streams and
Flow, allow developers to create applications that can handle high volumes of data and events.
JVMarchitectureDatatypes
JVM Architecture:
1. Class Loader: Loads classes into memory
2. Bytecode Verifier: Checks bytecode for correctness
3. Execution Engine: Executes bytecode
4. Runtime Data Areas: Stores data during execution
❖ Method Area: Stores class and method data
❖ Heap: Stores objects
❖ Stack: Stores method invocation and local variables
❖ PC Register: Stores current instruction address
5. Native Method Interface: Allows Java code to call native methods
Data Types:
1. Primitive Types:
❖ Integer: int, short, byte, long
❖ Floating Point: float, double
❖ Character: char
❖ Boolean: boolean
2. Reference Types:
❖ Class: User-defined classes
❖ Interface: Abstract classes with methods
❖ Array: Collections of primitive or reference types
3. Wrapper Classes:
❖ Integer: int
❖ Byte: byte
❖ Short: short
❖ Long: long
❖ Float: float
❖ Double: double
❖ Character: char
❖ Boolean: boolean
Note: The JVM also has a garbage collector that automatically manages memory and avoids
memory leaks.
Variables
Variables are named locations in memory that store values. In Java, variables are declared with a
specific data type and can be assigned a value. Here are the basics of variables in Java:
Declaration:
❖ Declare a variable by specifying its data type and name.
❖ Example: int x; (declares an integer variable named x)
Assignment:
❖ Assign a value to a variable using the assignment operator (=).
❖ Example: x = 10; (assigns the value 10 to the variable x)
Data Types:
- Java has several data types, including:
❖ Primitive types (int, double, boolean, etc.)
❖ Reference types (String, Array, etc.)
Scope:
❖ Variables have a scope, which determines their visibility and accessibility.
❖ Local variables are declared inside a method and are only accessible within that
method.
❖ Instance variables are declared inside a class and are accessible by all methods in
that class.
❖ Static variables are shared by all instances of a class.
Modifiers:
❖ Variables can have modifiers that affect their behavior.
❖ Final variables cannot be changed once assigned.
❖ Static variables are shared by all instances of a class.
❖ Public variables are accessible from outside the class.
Operations:
❖ Variables can be used in expressions and statements.
❖ Arithmetic operations (+, -, *, /, %)
❖ Comparison operations (==, !=, <, >, <=, >=)
❖ Logical operations (&&, ||, !)
Best Practices:
❖ Use meaningful variable names that indicate their purpose.
❖ Use proper data types to ensure type safety.
❖ Declare variables close to their usage.
❖ Avoid using public variables; use getters and setters instead.
Scope:
❖ Scope refers to the region of the code where a variable is defined and accessible.
❖ Variables can have different scopes, including:
▪ Local scope: Variables declared inside a method or block.
▪ Instance scope: Variables declared inside a class, but outside a method.
▪ Static scope: Variables declared with the static keyword.
▪ Global scope: Variables declared outside any class or method.
Lifetime:
14. What will be the output of the following code 20. Which statement is true about static methods?
snippet? a) They can access non-static variables.
```java b) They belong to the class rather than an object.
int[] arr = {1, 2, 3, 4}; c) They cannot be called without creating an object.
[Link](arr[4]); d) They cannot have a return value.
``` **Answer:** b
a) 0
b) 4 21. What is inheritance in Java?
c) ArrayIndexOutOfBoundsException a) A way to reuse code from other classes
d) Compilation Error b) A mechanism to access private variables
**Answer:** c c) A way to write multiple classes
d) None of the above
15. Which control statement is used to exit a loop **Answer:** a
prematurely?
a) continue 22. Which type of inheritance is not supported in
b) break Java?
c) exit a) Single inheritance
d) stop b) Multiple inheritance using classes
**Answer:** b c) Multilevel inheritance
d) Hierarchical inheritance
16. What does a `switch` statement use to compare **Answer:** b
values?
a) Floating-point comparisons 23. What does the `this` keyword represent?
b) Integer comparisons a) A reference to the current object
c) String comparisons b) A reference to the parent object
d) Both b and c c) A method to invoke the constructor
**Answer:** d d) None of the above
**Answer:** a
17. What is type casting in Java?
a) Automatic conversion of data types 24. What is the purpose of the `super` keyword?
b) Explicit conversion of one data type to another a) To create a superclass
c) Copying one variable to another b) To call the constructor of the current class
d) Checking data types at runtime c) To access members of the parent class
**Answer:** b d) To create private methods
**Answer:** c
18. Which of the following is an example of implicit
type conversion? 25. Which is true about method overloading in Java?
a) int a = (int) 10.5; a) It allows the same method name with different
b) float b = 5; parameter types
c) String s = (String) object; b) It allows methods in subclasses to override
d) None of the above methods in the superclass
**Answer:** b c) It requires the `final` keyword
d) None of the above
19. What is a constructor in Java? **Answer:** a
a) A method used to destroy objects
b) A method that initializes objects 26. What is dynamic method dispatch?
c) A method to execute static code a) A way to call static methods dynamically
d) None of the above
b) A mechanism to resolve overridden methods at 33. Can an interface extend another interface?
runtime a) Yes, using the `extends` keyword
c) A process to dispatch exceptions dynamically b) No, interfaces cannot extend another interface
d) None of the above c) Yes, using the `implements` keyword
**Answer:** b d) None of the above
**Answer:** a
27. What is the purpose of an abstract class?
a) To provide a blueprint for other classes 34. Which statement is true about implementing an
b) To create concrete methods interface?
c) To bypass inheritance a) A class can implement multiple interfaces
d) None of the above b) A class can implement only one interface
**Answer:** a c) Interfaces cannot be implemented
d) None of the above
28. Which of the following is true about the `final` **Answer:** a
keyword?
a) It can be applied to variables, methods, and classes 35. What is the purpose of the `try` block in Java?
b) It makes a variable mutable a) To catch exceptions
c) It allows method overriding b) To test for exceptions
d) None of the above c) To execute code that might throw exceptions
**Answer:** a d) None of the above
**Answer:** c
29. What is a package in Java?
a) A collection of classes and interfaces 36. What happens if a `finally` block is defined in a
b) A way to organize Java files try-catch structure?
c) Both a and b a) It is executed only if an exception is thrown
d) None of the above b) It is executed always
**Answer:** c c) It is executed only if no exception is thrown
d) None of the above
30. Which keyword is used to import a package in **Answer:** b
Java?
a) `package` 37. Which keyword is used to throw an exception in
b) `import` Java?
c) `include` a) `throws`
d) `extend` b) `throw`
**Answer:** b c) `catch`
d) `try`
31. What is access protection in packages? **Answer:** b
a) Controlling access to members within a package
b) Allowing only private methods 38. What is a built-in exception in Java?
c) Making all methods public a) User-defined exception classes
d) None of the above b) Predefined exceptions in Java libraries
**Answer:** a c) Errors caused by the JVM
d) None of the above
32. What is an interface in Java? **Answer:** b
a) A class that contains concrete methods
b) A class that contains abstract methods 39. What does the `throws` keyword indicate?
c) A blueprint for a class with only abstract methods a) It defines the exception to be thrown in a method
d) None of the above b) It creates a new exception
**Answer:** c c) It catches exceptions
d) None of the above
**Answer:** a A) New
B) Blocked
40. Which method is overridden to create a custom C) Running
exception? D) Destroyed
a) `toString()` Answer: D
b) `getMessage()`
c) Both a and b 47. What is inter-thread communication in Java?
d) None of the above A) Threads sharing their execution time
**Answer:** c B) Mechanism for threads to communicate using
wait(), notify(), notifyAll()
41. Which of the following is a valid way to create a C) Creating multiple threads to run concurrently
thread in Java? D) Deadlock prevention
A) Extending the Thread class Answer: B
B) Implementing the Runnable interface
C) Both A and B 48. Which method is NOT related to thread
D) Using ExecutorService only communication?
Answer: C A) wait()
B) notify()
42. What is the default priority of a thread in Java? C) notifyAll()
A) 1 D) sleep()
B) 5 Answer: D
C) 10
D) 0 49. Which condition can lead to a deadlock in Java?
Answer: B A) One thread releasing a lock while another thread
holds it
43. Which method is used to pause the execution of a B) Two or more threads waiting for each other's lock
thread? C) Only one thread being active
A) stop() D) Threads finishing execution simultaneously
B) yield() Answer: B
C) sleep()
D) pause() 50. What is the use of the synchronized block?
Answer: C A) To improve thread execution speed
B) To lock a specific section of code
44. In Java, what does the join() method do? C) To notify all threads to start execution
A) Joins two threads into one D) To stop a thread
B) Waits for a thread to die Answer: B
C) Stops a thread
D) Terminates all running threads I/O Streams
Answer: B 51. What is the main purpose of I/O streams in Java?
A) To manage threads
45. How can thread synchronization be achieved in B) To handle input and output operations
Java? C) To execute system commands
A) Using the synchronized keyword D) To create files
B) Using volatile keyword Answer: B
C) Using Thread class
D) Using notify() 52. Which of the following is a byte stream class in
Answer: A Java?
A) BufferedReader
46. Which of these is NOT a state in the thread B) FileOutputStream
lifecycle?
C) PrintWriter Answer: A
D) FileReader
Answer: B 59. What does the close() method do in Java I/O
streams?
53. Which of these classes is used for character A) Clears the buffer
streams? B) Terminates the program
A) DataInputStream C) Closes the stream and releases resources
B) FileWriter D) Stops the file from being used again
C) FileInputStream Answer: C
D) BufferedInputStream
Answer: B 60. Which class in Java provides methods to read
primitive data types directly from a stream?
54. What is the correct way to read a single character A) BufferedReader
from the console? B) DataInputStream
A) [Link]().readChar() C) InputStreamReader
B) [Link]() D) ObjectInputStream
C) [Link]() Answer: B
D) [Link]() 61. What does AWT stand for in Java?
Answer: B A) Abstract Window Toolkit
B) Advanced Window Toolkit
55. Which method is used to write to the console in C) Application Window Toolkit
Java? D) Advanced Widget Toolkit
A) [Link]() Answer: A
B) [Link]()
C) [Link]() 62. Which of the following is NOT a component in
D) [Link]().print() the AWT hierarchy?
Answer: B A) Label
B) Button
56. What is the difference between FileReader and C) ArrayList
FileInputStream? D) ScrollPane
A) FileReader is for binary data; FileInputStream is Answer: C
for text data.
B) FileReader is for text data; FileInputStream is for 63. Which AWT component is used to display
binary data. uneditable text?
C) Both handle binary data. A) TextField
D) Both handle text data. B) TextArea
Answer: B C) Label
D) Button
57. How do you create a file in Java? Answer: C
A) Using [Link]()
B) Using [Link]() 64. How do you group a set of CheckBoxes in Java?
C) Using [Link]() A) Using CheckBoxGroup
D) Using [Link]() B) Using GroupLayout
Answer: B C) Using Panel
D) Using List
58. Which class is used to read text files efficiently? Answer: A
A) BufferedReader
B) FileReader 65. Which AWT component allows selecting one
C) Scanner option from a drop-down menu?
D) DataInputStream
A) List C) A method to execute Java programs
B) Choice D) A process to manage layouts
C) Menu Answer: B
D) TextField
Answer: B 72. What is the role of an Event Listener in Java?
A) To generate events
66. What is the difference between List and Choice in B) To handle events
AWT? C) To display events
A) List supports multi-selection; Choice does not. D) To delegate events
B) List is for binary data; Choice is for text data. Answer: B
C) List supports single selection only; Choice
supports multi-selection. 73. What is the Event Delegation Model (EDM)?
D) List and Choice are functionally identical. A) A model for propagating events from source to
Answer: A listener
B) A method for creating events
67. Which class in AWT is used to create a container C) A tool for debugging event-driven applications
for other components? D) A model for synchronizing events across threads
A) Frame Answer: A
B) Panel
C) ScrollPane 74. Which method is called when a button is clicked
D) Menu in AWT?
Answer: B A) buttonClicked()
B) onClick()
68. Which method is used to add a menu to a Frame? C) actionPerformed()
A) setMenu() D) doClick()
B) addMenu() Answer: C
C) setMenuBar()
D) addMenuBar() 75. How do you handle mouse events in AWT?
Answer: C A) Using MouseEvent and MouseListener
B) Using KeyEvent and KeyListener
69. How can you add scrolling functionality to a large C) Using MouseListener and Adapter
component in AWT? D) Using ActionEvent and ActionListener
A) Using ScrollPane Answer: A
B) Using ScrollBar only
C) Using Panel 76. Which of these is NOT a method in the
D) Using Choice MouseListener interface?
Answer: A A) mousePressed()
B) mouseClicked()
70. Which layout manager arranges components in a C) mouseScrolled()
grid with fixed rows and columns? D) mouseReleased()
A) BorderLayout Answer: C
B) FlowLayout
C) GridLayout 77. What is the advantage of using Adapter classes in
D) CardLayout Java?
Answer: C A) To simplify handling only specific events
B) To add multiple listeners to an event
Event Handling C) To extend the functionality of all methods in a
71. What is an Event in Java? listener interface
A) A mechanism to handle exceptions D) To manage event sources efficiently
B) An object that describes a state change in a source Answer: A
B. JCheckBox
78. What are inner classes commonly used for in C. JRadioButton
event handling? D. JToggleButton
A) To increase program size Answer: A
B) To encapsulate event listener implementation
C) To slow down execution 85. What is the purpose of a JPanel in Swing?
D) To avoid using adapters A. To create a top-level container
Answer: B B. To group other components
C. To handle user inputs
79. Which method handles key typing events in the D. To display text
KeyListener interface? Answer: B
A) keyTyped()
B) keyPressed() 86. Which component allows selection of one option
C) keyReleased() from a set?
D) keyInput() A. JCheckBox
Answer: A B. JRadioButton
C. JButton
80. What does the addActionListener() method do in D. JComboBox
AWT? Answer: B
A) Adds an action listener to a component
B) Removes an action listener from a component 87. What does a JScrollPane provide?
C) Executes an action listener A. Text editing
D) Binds an action to multiple components B. Scrollable view for components
Answer: A C. Button functionality
D. Container hierarchy
81. Which of the following is NOT a top-level Answer: B
container in Swing?
A. JFrame 88. Which of the following is used to display a single
B. JWindow line of editable text?
C. JPanel A. JTextArea
D. JDialog B. JLabel
Answer: C C. JTextField
D. JPanel
82. What is the base class for all Swing components? Answer: C
A. Component
B. JComponent 89. What is the main difference between JCheckBox
C. Container and JRadioButton?
D. Object A. JCheckBox is selectable, JRadioButton is not
Answer: B B. JCheckBox allows multiple selections,
JRadioButton does not
83. Which method is used to make a JFrame visible? C. JRadioButton is for text input, JCheckBox is not
A. setShow() D. JCheckBox cannot be deselected, JRadioButton
B. display() can
C. setVisible() Answer: B
D. showFrame()
Answer: C 90. Which method is used to add components to a
JFrame?
84. Which component is used to create a button in A. append()
Swing? B. addComponent()
A. JButton C. add()
D. insert() Answer: B
Answer: C
96. How can you set the text of a JLabel?
91. What does a JLabel component do? A. setText()
A. Displays text or icons B. setLabel()
B. Accepts user input C. setTextValue()
C. Acts as a container D. setContent()
D. Provides scroll functionality Answer: A
Answer: A 97. Which Swing container does NOT require a
parent?
92. How do you create a JComboBox in Swing? A. JPanel
A. new JComboBox() B. JFrame
B. [Link]() C. JLabel
C. new JComboBox[] D. JTextField
D. createComboBox() Answer: B
Answer: A
98. What is the default layout manager for a JPanel?
93. Which component is used for multi-line text A. BorderLayout
editing? B. FlowLayout
A. JTextArea C. GridLayout
B. JTextField D. None
C. JLabel Answer: B
D. JPanel
Answer: A 99. How can you group JRadioButtons?
A. Add them to a JPanel
94. What is the purpose of a JToggleButton? B. Use a ButtonGroup
A. To toggle between enabled and disabled states C. Add them to a JFrame
B. To act as a switch between on and off states D. Use a JCheckBox
C. To display icons Answer: B
D. To scroll content
Answer: B 100. Which method adds an item to a JComboBox?
A. addItem()
95. Which component represents a scrollable list? B. add()
A. JScrollPane C. insertItem()
B. JList D. setItem()
C. JComboBox Answer: A
D. JTextArea
Write a Java program that displays the number of characters, lines and
3 words in a text
Generate random numbers between two given limits using Random class
4 and print messages according to the range of the value generated.
6 a. String Concatenation
b. Search a substring
c. To extract substring from given string
Write a program to perform string operations using String Buffer
class:
a. Length of a string
7
b. Reverse a string
c. Delete a substring from the given string
9 to print the numbers 1to10 using Thread1 and to print90 to100 using
Thread2.
a. Arithmetic Exception
c. ArrayIndexOutofBoundException
d. NegativeArraySizeException
Write a Java program that reads on file name from the user, then
displays information about whether the file exists, whether the file is
11 readable, whether the file is writable, the type of file and the length of
the file in bytes
Write a program to accept a text and change its size and font. Include
12 bold italic options. Use frames and controls.
Write a Java program that handles all mouse events and shows the
13 event name at the center of the window when a mouse event is fired.
(Use adapter classes).
14 Write a Java program that works as a simple calculator. Use a grid
layout to arrange buttons for the digits and for the +, -,*, % operations.
Add a text field to display the result. Handle any possible exceptions
like divide by zero.
Write a Java program that simulates a traffic light. The program lets
theuser select one of three lights: red, yellow, or green with radio
buttons. On selecting a button, an appropriate message with ―stop or
15
―ready or
―go should appear above the buttons in a selected color. Initially
there is no message shown.
[Link] NUMBERS
AIM:
To write a Java program that prompts the user for an integer and prints all prime numbers up
to that integer.
ALGORITHM:
1. Get User Input: Prompt user to enter an integer n.
2. Check Input Validity: Verify that n is a positive integer.
3. Initialize Prime List: Create an empty list to store prime numbers.
4. Check for Prime Numbers:
- Iterate from i = 2 to n.
- For each i, call the isPrime function to check if i is prime.
- If i is prime, add it to the prime list.
5. Print Prime List: Display the list of prime numbers up to n.
6. Exit: Terminate the program.
PROGRAM:
import [Link];
if (n < 2) {
[Link]("There are no prime numbers up to " + n);
} else {
[Link]("Prime numbers up to " + n + ":");
for (int i = 2; i <= n; i++) {
if (isPrime(i)) {
[Link](i + " ");
}
}
[Link](); // Add a newline after the primes
}
OUTPUT:
Enter an integer: 20
Prime numbers up to 20:
2 3 5 7 11 13 17 19
[Link] TWO MATRICES
AIM:
To multiply two given matrices using Java.
ALGORITHM:
1. Get Dimensions: Get the dimensions of matrices A and B (m, n, p)
2. Validate Dimensions: Check if the number of columns in A equals the number of rows in B
(n == n)
3. Create Result Matrix: Create a result matrix C (m x p) filled with zeros
4. Perform Matrix Multiplication:
- For each element C[i][j] in the result matrix
- Iterate over corresponding elements of A and B
- Multiply and accumulate products: C[i][j] += A[i][k] * B[k][j]
5. Return Result Matrix: Return the resulting product matrix C
PROGRAM:
import [Link];
[Link]();
}
}
OUTPUT:
Enter the number of rows in the first matrix: 2
Enter the number of columns in the first matrix: 3
Enter the number of rows in the second matrix: 3
Enter the number of columns in the second matrix: 2
Enter elements of the first matrix:
123
456
Enter elements of the second matrix:
78
9 10
11 12
The product of the matrices is:
58 64
139 154
3. DISPLAYS THE NUMBER OF CHARACTERS, LINES AND
WORDS IN A TEXT
AIM:
To displays the number of characters, lines and words in a text using Java Programming.
ALGORITHM:
1. Initialize the following variables:
• characterCount = 0 (To store the total number of characters)
int characterCount = 0;
int wordCount = 0;
int lineCount = 0;
while (true) {
String line = [Link]();
// Exit condition
if ([Link]("END")) {
break;
}
lineCount++;
characterCount += [Link]();
wordCount += [Link]("\\s+").length; // Split by whitespace
}
OUTPUT:
Enter the text (type 'END' on a new line to finish):
Hello, how are you?
I am doing fine.
Java programming is fun.
END
Text Statistics:
Number of lines: 3
Number of words: 10
Number of characters: 56
4. RANDOM NUMBER GENERATOR
AIM:
To generate random numbers between two given limits using Random class and print
messages according to the range of the value generated.
ALGORITHM:
Step 1: Import Necessary Libraries
1. Import [Link] for generating random numbers
2. Import [Link] for reading user input
Step 2: Initialize Variables
1. Initialize a Scanner object to read user input
2. Initialize a Random object to generate random numbers
Step 3: Get User Input
1. Prompt user to enter the lower limit
2. Read the lower limit using [Link]()
3. Prompt user to enter the upper limit
4. Read the upper limit using [Link]()
Step 4: Validate Input
1. Check if the lower limit is less than or equal to the upper limit
2. If invalid, display an error message and exit
Step 5: Generate Random Number
1. Use [Link]() to generate a random integer within the given range (inclusive)
2. Calculate the random number using the formula: randomNumber =
[Link](upperLimit - lowerLimit + 1) + lowerLimit
Step 6: Display Random Number
1. Print the generated random number to the console
Step 7: Determine Range
1. Calculate the range of the generated number
2. Check which range the generated number falls into (lower, middle, or upper)
3. Print a message indicating the range of the generated number
Step 8: Close Scanner
1. Close the Scanner object to prevent resource leaks
PROGRAM:
import [Link];
import [Link];
OUTPUT:
Enter the lower limit: 10
Enter the upper limit: 30
Generated Random Number: 17
The generated number is in the middle range.
5. STRING MANIPULATION
AIM:
The aim of this program is to perform basic string manipulations using CharacterArray in
Java. The program will:
1. Calculate the length of a given string by converting it into a character array.
2. Find a character at a specific position within the string using the character array.
3. Concatenate two strings and display the result.
ALGORITHM:
Step 1: Import Necessary Libraries
1. Import [Link] for reading user input
Step 2: Initialize Variables
1. Initialize a Scanner object to read user input
Step 3: Input Two Strings
1. Prompt user to enter the first string
2. Read the first string using [Link]()
3. Prompt user to enter the second string
4. Read the second string using [Link]()
Step 4: Convert Strings to Character Arrays
1. Convert the first string to a character array using toCharArray()
2. Convert the second string to a character array using toCharArray()
Step 5: Find the Length of the Strings
1. Print the length of the first string using length property
2. Print the length of the second string using length property
Step 6: Find a Character at a Particular Position
1. Prompt user to enter the position (index) to find the character
2. Read the position using [Link]()
3. Check if the position is valid for the first string
4. If valid, print the character at the specified position in the first string
5. Repeat steps 3-4 for the second string
Step 7: Concatenate Two Strings
1. Concatenate the first and second strings using the + operator
2. Print the concatenated string
Step 8: Close Scanner
1. Close the Scanner object to prevent resource leaks.
PROGRAM:
import [Link];
[Link]();
}
}
OUTPUT:
Enter the first string: Hello
Enter the second string: World
Enter the position (index) to find the character: 2
String Length:
Length of the first string: 5
Length of the second string: 5
Concatenated String:
HelloWorld
6. STRING OPERATIONS USING STRING CLASS
AIM:
To perform the following string operations using String class:
a. String Concatenation
b. Search a substring
c. To extract substring from given string
ALGORITHM:
Step 1: Import Necessary Libraries
1. Import [Link] for reading user input.
Step 2: Initialize Variables
1. Initialize a Scanner object to read user input.
Step 3: Input Strings
1. Prompt user to enter the first string.
2. Read the first string using [Link]().
3. Prompt user to enter the second string.
4. Read the second string using [Link]().
Step 4: String Concatenation
1. Concatenate the first and second strings using the concat() method.
2. Print the concatenated string.
Step 5: Search a Substring
1. Prompt user to enter a substring to search.
2. Read the substring using [Link]().
3. Check if the first string contains the substring using the contains() method.
4. Print the result of the search.
Step 6: Extract a Substring
1. Prompt user to enter the starting index for the substring extraction.
2. Read the starting index using [Link]().
3. Prompt user to enter the ending index for the substring extraction.
4. Read the ending index using [Link]().
5. Check if the indices are valid.
6. Extract the substring using the substring() method.
7. Print the extracted substring.
PROGRAM:
import [Link];
// Input strings
[Link]("Enter the first string: ");
String firstString = [Link]();
// 1. String Concatenation
String concatenatedString = [Link](secondString);
[Link]("\nConcatenated String:");
[Link](concatenatedString);
// 2. Search a Substring
[Link]("\nEnter a substring to search: ");
String substringToSearch = [Link]();
if ([Link](substringToSearch)) {
[Link]("The substring '" + substringToSearch + "' is found in the first
string.");
} else {
[Link]("The substring '" + substringToSearch + "' is not found in the first
string.");
}
// 3. Extract a Substring
[Link]("\nEnter the starting index for the substring extraction: ");
int startIndex = [Link]();
[Link]();
}
}
OUTPUT:
Enter the first string: HelloWorld
Enter the second string: Java
Enter a substring to search: World
Enter the starting index for the substring extraction: 5
Enter the ending index for the substring extraction: 10
Concatenated String:
HelloWorldJava
Extracted Substring:
World
1. 7. STRING OPERATIONS USING STRING BUFFER
CLASS
AIM:
The aim of this program is to demonstrate the use of the StringBuffer class in Java to perform
basic string operations, including:
1. Finding the length of a string.
2. Reversing the string.
3. Deleting a substring from the string.
ALGORITHM:
1. Input a string from the user.
2. Create a StringBuffer object from the input string.
3. Find the length of the string using the length() method.
4. Reverse the string using the reverse() method.
5. Delete a substring from the string:
- Input the start and end indices for deletion.
- Check if the indices are valid.
- Use the delete() method to delete the substring.
6. Print the results of each operation.
PROGRAM:
import [Link];
[Link]();
}
}
OUTPUT:
Enter a string: HelloWorld
Enter the start index to delete a substring: 5
Enter the end index to delete a substring: 10
Length of the string: 10
Reversed string: dlroWolleH
String after deletion: Hello
8. MULTI-THREADED APPLICATION FOR RANDOM
NUMBER GENERATION AND PROCESSING
AIM:
The aim of this program is to demonstrate a multi-threaded application.
ALGORITHM:
Step 1: Create Shared Object
1. Create a shared object RandomNumberGenerator to generate random numbers.
Step 2: Create Threads
1. Create three threads:
i. generatorThread: generates random numbers every 1 second.
ii. squareThread: computes the square of the generated number if
it's even.
iii. cubeThread: computes the cube of the generated number if it's
odd.
Step 3: Start Threads
1. Start all three threads.
Step 4: Generate Random Numbers
1. In generatorThread:
i. Generate a random integer between 1 and 100.
ii. Notify the other threads using [Link]().
iii. Wait 1 second before generating the next number.
Step 5: Compute Square and Cube
1. In squareThread and cubeThread:
I. Wait until a random number is generated using [Link]().
II. Get the generated number using getRandomNumber().
III. Compute the square or cube of the number based on its parity.
IV. Print the result.
Step 6: Repeat
1. Repeat steps 4-5 indefinitely.
PROGRAM:
import [Link];
[Link]();
[Link]();
[Link]();
}
}
OUTPUT:
Generated Number: 52
Square of 52: 2704
Generated Number: 19
Cube of 19: 6859
Generated Number: 37
Cube of 37: 50653
Generated Number: 40
Square of 40: 1600
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
9. THREADING PROGRAM TO PRINT NUMBERS
ASYNCHRONOUSLY USING TWO THREADS
AIM:
The aim of this program is to demonstrate asynchronous execution using two threads, where
Thread1 prints numbers from 1 to 10 and Thread2 prints numbers from 90 to 100.
ALGORITHM:
Step 5: Repeat step 4 until all numbers in the range have been printed.
PROGRAM:
class NumberPrinter implements Runnable {
private int start;
private int end;
OUTPUT:
1
90
2
91
3
92
4
93
5
94
6
95
7
96
8
97
9
98
10
99
100
10. DEMONSTRATING DIFFERENT EXCEPTIONS
AIM:
To demonstrate the use of following exceptions.
a. Arithmetic Exception
b. Number Format Exception
c. ArrayIndexOutofBoundException
d. NegativeArraySizeException
ALGORITHM:
1. Demonstrate ArithmeticException:
I. Attempt to divide by zero.
II. Catch ArithmeticException and print error message.
2. Demonstrate NumberFormatException:
I. Attempt to parse a string to an integer.
II. Catch NumberFormatException and print error message.
3. Demonstrate ArrayIndexOutOfBoundsException:
I. Create an array with a fixed size.
II. Attempt to access an index outside the array bounds.
III. Catch ArrayIndexOutOfBoundsException and print error message.
4. Demonstrate NegativeArraySizeException:
I. Attempt to create an array with a negative size.
II. Catch NegativeArraySizeException and print error message.
PROGRAM:
public class ExceptionDemo {
// Demonstrating ArithmeticException
try {
int result = 10 / 0; // Division by zero
} catch (ArithmeticException e) {
[Link]("ArithmeticException: " + [Link]());
}
// Demonstrating NumberFormatException
try {
int number = [Link]("abc"); // Invalid number format
} catch (NumberFormatException e) {
[Link]("NumberFormatException: " + [Link]());
}
// Demonstrating ArrayIndexOutOfBoundsException
try {
int[] arr = new int[3];
arr[5] = 10; // Trying to access an invalid index
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("ArrayIndexOutOfBoundsException: " + [Link]());
}
// Demonstrating NegativeArraySizeException
try {
int[] arr = new int[-5]; // Trying to create an array with negative size
} catch (NegativeArraySizeException e) {
[Link]("NegativeArraySizeException: " + [Link]());
}
}
}
OUTPUT:
ArithmeticException: / by zero
NumberFormatException: For input string: "abc"
ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
NegativeArraySizeException: Capacity cannot be negative
11. FILE INFORMATION VIEWER
AIM:
To read on file name from the user, then displays information about whether the file exists,
whether the file is readable, whether the file is writable, the type of file and the length of the
file in bytes using Java Programming.
ALGORITHM:
1. Create a scanner object to read input from the user.
2. Prompt the user to enter a file name.
3. Create a File object with the provided file name.
4. Check if the file exists using the exists() method.
5. If the file exists, perform the following checks:
I. Readability using the canRead() method.
II. Writability using the canWrite() method.
III. File type (directory or regular file) using the isDirectory() method.
IV. File length using the length() method.
6. If the file does not exist, print a message indicating that the file does not exist.
7. Close the scanner object.
PROGRAM:
import [Link];
import [Link];
AIM:
To accept a text and change its size and font. Include bold italic options. Use frames and
controls.
ALGORITHM:
1. Create a GUI application with a text area and controls for font size, font family, bold, and
italic.
2. Initialize the text area with a default font.
3. Create combo boxes for font size and font family.
4. Add action listeners to the combo boxes to update the font when a selection is made.
5. Create check boxes for bold and italic.
6. Add action listeners to the check boxes to update the font when a selection is made.
7. Create a method to update the font based on the current selections.
8. Use the [Link]() method to create and display the GUI application.
PROGRAM:
import [Link].*;
import [Link].*;
import [Link];
import [Link];
public TextEditor() {
// Set the title and layout of the frame
setTitle("Text Editor - Change Font and Size");
setLayout(new BorderLayout());
// Create a panel for controls (font size, font family, bold, italic)
JPanel controlsPanel = new JPanel();
add(controlsPanel, [Link]);
AIM:
To handles all mouse events and shows the event name at the center of the window when a
mouse event is fired using Java programming.
ALGORITHM:
1. Create a GUI application with a custom panel to handle and display mouse events.
2. Set up the frame with a title, size, and default close operation.
3. Create a custom panel (MousePanel) to handle and display mouse events.
4. Add mouse listeners to the panel using adapter classes (MouseAdapter and
MouseMotionAdapter).
5. Handle mouse events (e.g., clicked, pressed, released, entered, exited, moved, dragged) and
update the displayed event name.
6. Use the repaint() method to update the displayed event name.
7. Use the [Link]() method to create and display the GUI application.
PROGRAM:
import [Link].*;
import [Link].*;
import [Link].*;
public MouseEventDemo() {
// Set up the frame
setTitle("Mouse Event Handler");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
@Override
public void mousePressed(MouseEvent e) {
[Link]("Mouse Pressed");
}
@Override
public void mouseReleased(MouseEvent e) {
[Link]("Mouse Released");
}
@Override
public void mouseEntered(MouseEvent e) {
[Link]("Mouse Entered");
}
@Override
public void mouseExited(MouseEvent e) {
[Link]("Mouse Exited");
}
});
[Link](new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
[Link]("Mouse Moved");
}
@Override
public void mouseDragged(MouseEvent e) {
[Link]("Mouse Dragged");
}
});
}
@Override
protected void paintComponent(Graphics g) {
[Link](g);
[Link](new Font("Arial", [Link], 20));
[Link]([Link]);
// Draw the event name at the center of the panel
FontMetrics fm = [Link]();
int x = (getWidth() - [Link](eventName)) / 2;
int y = (getHeight() + [Link]()) / 2;
[Link](eventName, x, y);
}
}
AIM:
To design and implement a Java program for a simple calculator using a graphical user
interface (GUI) with Java Swing. The program should handle basic arithmetic operations (+, -
, *, /, %) and display the results in a text field, while also managing exceptions such as
division by zero. The layout should utilize a GridLayout for arranging the buttons.
ALGORITHM:
1. Create a GUI application with a text field for display and a panel for buttons.
2. Define the buttons for digits 0-9, operators (+, -, *, /, %), and equals (=).
3. Handle button clicks:
1. For digit buttons, append the digit to the current number.
2. For operator buttons, store the operator and the current number.
3. For equals button, perform the calculation using the stored operator and numbers.
4. Display the result of the calculation in the text field.
5. Handle errors:
1. For invalid numbers, display an error message.
2. For arithmetic exceptions (e.g., division by zero), display an error message.
PROGRAM:
import [Link].*;
import [Link].*;
import [Link];
import [Link];
public SimpleCalculator() {
// Set up the frame
setTitle("Simple Calculator");
setSize(400, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new BorderLayout());
add(buttonPanel, [Link]);
}
try {
if ("0123456789".contains(command)) {
// Append digit to the current number
currentNumber += command;
[Link](currentNumber);
} else if ("+-*/%".contains(command)) {
// Handle operator input
if (![Link]()) {
firstOperand = [Link](currentNumber);
currentNumber = "";
operator = command;
}
} else if ([Link]("=")) {
// Perform calculation
if (![Link]() && ![Link]()) {
double secondOperand = [Link](currentNumber);
double result;
switch (operator) {
case "+":
result = firstOperand + secondOperand;
break;
case "-":
result = firstOperand - secondOperand;
break;
case "*":
result = firstOperand * secondOperand;
break;
case "/":
if (secondOperand == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
result = firstOperand / secondOperand;
break;
case "%":
result = firstOperand % secondOperand;
break;
default:
throw new IllegalStateException("Unexpected operator: " + operator);
}
[Link]([Link](result));
currentNumber = ""; // Clear for the next calculation
operator = ""; // Clear operator
}
}
} catch (NumberFormatException ex) {
[Link]("Error: Invalid Number");
currentNumber = "";
operator = "";
} catch (ArithmeticException ex) {
[Link]("Error: " + [Link]());
currentNumber = "";
operator = "";
}
}
}
AIM:
To design and implement a Java program that simulates a traffic light system using GUI
components. The program should allow the user to select one of the three lights (Red, Yellow,
or Green) using radio buttons, and display an appropriate message ("Stop", "Ready", or "Go")
in the corresponding color. The initial state of the program should show no message.
ALGORITHM:
1. Create a GUI application with radio buttons for red, yellow, and green traffic lights.
2. Create a label to display the message corresponding to the selected traffic light.
3. Group the radio buttons to ensure only one can be selected at a time.
4. Add action listeners to the radio buttons to handle selection events.
5. When a radio button is selected:
- Update the message label with the corresponding message (e.g., "Stop", "Ready", "Go").
- Update the color of the message label to match the selected traffic light.
6. Display the GUI application.
PROGRAM:
import [Link].*;
import [Link].*;
import [Link];
import [Link];
public TrafficLightSimulator() {
// Set up the frame
setTitle("Traffic Light Simulator");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
add(buttonPanel, [Link]);
@Override
public void actionPerformed(ActionEvent e) {
[Link](message);
[Link](color);
}
}