0% found this document useful (0 votes)
4 views89 pages

Java Notes

Uploaded by

pushpamohanraj93
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views89 pages

Java Notes

Uploaded by

pushpamohanraj93
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 89

SYLLABUS

JAVA PROGRAMMING

UNIT I: Introduction:ReviewofObjectOrientedconcepts - HistoryofJava - Javabuzzwords -


JVMarchitecture - Datatypes - Variables - Scope and life timeofvariables - arrays - operators -
controlstatements - type conversion and casting - simple java program - constructors - methods - Static
block - Static Data - StaticMethodStringandStringBufferClasses.

UNIT II: Inheritance: Basic concepts - Types of inheritance - Member access rules - Usage of this and
Super key word - Method Overloading - Method overriding - Abstract classes - Dynamic method dispatch
- Usage of final keyword. Packages:Definition-AccessProtection -ImportingPackages.
Interfaces:Definition–Implementation–Extending Interfaces. Exception Handling: try – catch- throw -
throws – finally – Built-inexceptions - Creating own Exception classes.

UNIT III: Multithreaded Programming: Thread Class - Runnable interface – Synchronization–Using


synchronizedmethods– Using synchronized statement- InterthreadCommunication –Deadlock. I/O
Streams: Concepts of streams - Stream classes- Byte and Character stream - Reading console Input and
Writing Console output - File Handling.

UNIT IV: AWT Controls: The AWT class hierarchy - user interface components- Labels - Button - Text
Components - Check Box - Check Box Group - Choice - List Box - Panels – Scroll Pane - Menu - Scroll
Bar. Working with Frame class - Colour - Fonts and layout managers. Event Handling: Events - Event
sources - Event Listeners - Event Delegation Model (EDM) - Handling Mouse and Keyboard Events -
Adapter classes - Inner classes

UNIT V: Swing: Introduction to Swing - Hierarchy of swing components. Containers - Top level
containers - JFrame - JWindow - JDialog - JPanel - JButton - JToggleButton - JCheckBox - JRadioButton
- JLabel,JTextField - JTextArea - JList - JComboBox - JScrollPane.
UNIT-I

Introduction to Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a programming paradigm that revolves around the concept of
"objects." An object is an instance of a class, which encapsulates data (attributes) and behavior (methods).
This approach promotes modularity, reusability, and maintainability in software development.

Key OOP Concepts:

 Encapsulation: Bundling data and methods within a single unit (class).


 Inheritance: Creating new classes (child classes) from existing ones (parent classes), inheriting
their attributes and methods.
 Polymorphism: The ability of objects to take on many forms, allowing different objects to be
treated as if they were the same.
 Abstraction: Focusing on the essential features of an object, hiding unnecessary implementation
details.

History of Java

Java, created by Sun Microsystems (now owned by Oracle), was introduced in 1995. It was designed to be
platform-independent, "write once, run anywhere" language, making it highly portable. Java's popularity
soared due to its robustness, security, and versatility, leading to its widespread use in various domains,
including web development, enterprise applications, and mobile app development.

Java Buzzwords

 Platform Independent: Java code can run on any platform with a Java Virtual Machine (JVM).
 Object-Oriented: Java is a pure object-oriented language.
 Robust: Java's strong type checking and exception handling mechanisms help prevent runtime
errors.
 Secure: Java's security features, such as bytecode verification, protect against malicious code.
 High Performance: Java's Just-In-Time (JIT) compilation and optimized bytecode execution
provide efficient performance.
 Multi-threaded: Java supports concurrent programming, allowing multiple tasks to run
simultaneously.
 Distributed: Java provides networking capabilities for distributed applications.

JVM Architecture

The Java Virtual Machine (JVM) is a virtual machine that executes Java bytecode. It consists of the
following components:

 Classloader: Loads class files into memory.


 Bytecode Verifier: Verifies the correctness of bytecode to ensure security.
 Runtime Data Area: Stores data and code during program execution.
 Execution Engine: Interprets or compiles bytecode into machine code.
 Native Method Interface (JNI): Allows Java code to interact with native code (e.g., C, C++).

Data Types in Java

Java has two types of data types:


1. Primitive Data Types:

These are built-in data types that represent basic data values. They are directly stored in memory.

 byte: 8-bit signed integer (-128 to 127)


 short: 16-bit signed integer (-32768 to 32767)
 int: 32-bit signed integer (-2147483648 to 2147483647)
 long: 64-bit signed integer (-9223372036854775808 to 9223372036854775807)
 float: 32-bit single-precision floating-point number
 double: 64-bit double-precision floating-point number
 char: 16-bit Unicode character
 boolean: true or false

2. Reference Data Types:

These are data types that refer to objects, which are instances of classes. They are stored in the heap
memory.

 String: Sequence of characters


 Arrays: Collection of elements of the same data type
 Classes and Interfaces: User-defined data types

Example:

public class DataTypesExample {


public static void main(String[] args) {
// Primitive data types
byte age = 25;
short salary = 20000;
int population = 1000000;
long distance = 1234567890L;
float pi = 3.14f;
double avogadroNumber = 6.02214076e23;
char initial = 'A';
boolean isAdult = true;

// Reference data type


String name = "Alice";
int[] numbers = {1, 2, 3, 4, 5};

System.out.println("Age: " + age);


System.out.println("Salary: " + salary);
// ... and so on
}
}

Key Points:

 Primitive data types are stored directly in memory, while reference data types store references to
objects in the heap.
 The size of primitive data types is fixed, while the size of reference data types can vary.
 Primitive data types are passed by value, while reference data types are passed by reference.
By understanding these data types, you can effectively represent and manipulate data in your Java
programs.

Variables:

variable in Java is a named storage location that holds a value. It's like a container that can store
different types of data.

Declaration and Initialization:

To use a variable, you must first declare it. This involves specifying the data type and the variable
name. You can also initialize a variable by assigning it a value at the time of declaration.

data_type variable_name;
data_type variable_name = value;

Example:

int age = 25;


double pi = 3.14159;
char initial = 'A';
boolean isStudent = true;
String name = "Alice";

Scope and Lifetime of Variables

Scope refers to the region of a program where a variable is accessible. Lifetime refers to the period during
which a variable exists in memory.

Types of Variables and Their Scope and Lifetime:

1. Local Variables:
o Scope: Declared within a method or block. Accessible only within that block.
o Lifetime: Exists only while the method or block is executing. Once the block ends, the
variable is destroyed.

2. Instance Variables:
o Scope: Declared within a class but outside any method. Accessible to all methods within
the class.
o Lifetime: Exists as long as the object of the class exists. When the object is destroyed, the
instance variables are also destroyed.

3. Static Variables:
o Scope: Declared with the static keyword. Accessible to all instances of the class, as well as
from outside the class.
o Lifetime: Exists as long as the class is loaded. They are created when the class is loaded
and destroyed when the class is unloaded.

Example:

public class VariableScopeExample {


static int count = 0; // Static variable

public void method1() {


int x = 10; // Local variable
System.out.println(x);
System.out.println(count);
}
}

In this example:

 x is a local variable, accessible only within the method1() method.


 count is a static variable, accessible from any instance of the VariableScopeExample class.

Arrays:

An array is a collection of elements of the same data type. It provides a way to store multiple
values under a single variable name.

Types of Arrays:

1. One-Dimensional Arrays:
o A simple array that stores elements in a linear sequence.
o Declared using data_type[] array_name;
o Example:

int[] numbers = {1, 2, 3, 4, 5};

2. Multi-Dimensional Arrays:
o Arrays of arrays, used to represent matrices or tables.
o Declared using data_type[][] array_name;
o Example:

int[][] matrix = {{1, 2, 3}, {4, 5, 6}};

Accessing Array Elements:

Array elements are accessed using an index, which starts from 0.

int[] numbers = {10, 20, 30, 40, 50};


int firstElement = numbers[0]; // Accessing the first element
int lastElement = numbers[4]; // Accessing the last element

Array Operations:

 Iterating through an array:

for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); }

- **Enhanced for loop (for-each loop):**


```java
for (int number : numbers) {
System.out.println(number);

}
 Sorting an array:

Arrays.sort(numbers);

 Searching for an element:

int index = Arrays.binarySearch(numbers, 30);

Operators

Operators in Java

Operators are symbols that perform specific operations on variables and values. They are the
building blocks of expressions in Java, allowing you to perform calculations, comparisons, and more.

Types of Operators in Java

Java offers a rich set of operators, categorized into several types:

1. Arithmetic Operators:

 + (Addition): Adds two operands.


 - (Subtraction): Subtracts the second operand from the first.
 *** (Multiplication):** Multiplies two operands.
 / (Division): Divides the first operand by the second.
 % (Modulo): Returns the remainder of the division of the first operand by the second.

2. Assignment Operators:

 = (Assignment): Assigns a value to a variable.


 += (Addition Assignment): Adds a value to a variable and assigns the result to the variable.
 -= (Subtraction Assignment): Subtracts a value from a variable and assigns the result to the
variable.
 *= (Multiplication Assignment): Multiplies a value with a variable and assigns the result to the
variable.
 /= (Division Assignment): Divides a variable by a value and assigns the result to the variable.
 %= (Modulo Assignment): Calculates the modulo of a variable with a value and assigns the
result to the variable. \

3. Relational Operators:

 == (Equal to): Checks if two operands are equal.


 != (Not Equal to): Checks if two operands are not equal.
 > (Greater than): Checks if the first operand is greater than the second.
 < (Less than): Checks if the first operand is less than the second.
 >= (Greater than or Equal to): Checks if the first operand is greater than or equal to the second.
 <= (Less than or Equal to): Checks if the first operand is less than or equal to the second.

4. Logical Operators:

 && (Logical AND): Returns true if both operands are true.


 || (Logical OR): Returns true if at least one operand is true.
 ! (Logical NOT): Reverses the logical state of its operand.

5. Unary Operators:

 ++ (Increment): Increments a value by 1.


 -- (Decrement): Decrements a value by 1.
 + (Unary Plus): Unary plus operator, usually used for positive numbers.
 - (Unary Minus): Unary minus operator, used to negate a value.
 ! (Logical NOT): Reverses the logical state of its operand.

6. Bitwise Operators:

 & (Bitwise AND): Performs bitwise AND operation on two operands.


 | (Bitwise OR): Performs bitwise OR operation on two operands.
 ^ (Bitwise XOR): Performs bitwise XOR operation on two operands.
 ~ (Bitwise NOT): Performs bitwise NOT operation on an operand.
 << (Left Shift): Shifts the bits of an operand to the left.
 >> (Right Shift): Shifts the bits of an operand to the right.
 >>> (Unsigned Right Shift): Shifts the bits of an operand to the right, filling the leftmost bits with
zeros.

7. Ternary Operator:

 ?: A conditional operator that evaluates an expression and returns one of two values based on the
result.

Control Statements

Control statements are essential in programming to alter the normal flow of execution based on certain
conditions or to repeat a block of code multiple times. Java provides a variety of control statements to
achieve these objectives:

1. Decision Making Statements:

 if Statement:
o Executes a block of code if a specified condition is true.

if (condition) {
// code to be executed if condition is true
}

 if-else Statement:
o Executes one block of code if a condition is true, and another block if it's false.

if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}

 if-else-if Ladder:
o Allows for multiple conditions to be checked sequentially.

if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else if (condition3) {
// code to be executed if condition3 is true
} else {
// code to be executed if all conditions are false

 switch Statement:
o Efficiently handles multiple choices based on the value of an expression.

switch (expression) {
case value1:
// code to be executed if expression equals value1
break;
case value2:
// code to be executed if expression equals value2
break;
default:
// code to be executed
if no case matches
}

2. Looping Statements:

 for Loop:
o Repeats a block of code a specific number of times.

for (initialization; condition; increment/decrement) {


// code to be repeated
}

 while Loop:
o Repeats a block of code as long as a specified condition is true.

while (condition) {
// code to be repeated
}

 do-while Loop:
o Executes a block of code at least once, and then repeats as long as a specified condition is
true.

do {
// code to be repeated
} while (condition);

By effectively using these control statements, you can create dynamic and flexible Java programs
that can make decisions, repeat actions, and control the flow of execution based on specific conditions.

Type Conversion and Casting


In Java, type conversion is the process of converting a data type to another. This is crucial for
various operations, such as arithmetic calculations, assignments, and method calls.

Implicit Type Conversion (Widening Conversion)

Java automatically performs implicit type conversion when assigning a smaller data type to a
larger one. This is known as widening conversion. Here's an example:

byte b = 10;
int i = b; // Implicit conversion from byte to int

In this case, the byte value 10 is automatically converted to an int value.

Explicit Type Conversion (Narrowing Conversion)

When converting a larger data type to a smaller one, explicit type conversion is required. This is
known as narrowing conversion. It's important to note that narrowing conversion can lead to loss of
precision or data. Here's an example:

double d = 3.14;
int i = (int) d; // Explicit conversion from double to int

In this case, the double value 3.14 is explicitly converted to an int value. However, the decimal part is
truncated, resulting in the value 3.

Casting

Casting is the process of converting one data type to another explicitly using the cast operator (). It's often
used in narrowing conversions to avoid potential errors.

Example:

double d = 3.14;
int i = (int) d; // Casting double to int

Common Pitfalls and Best Practices:

 Loss of Precision: Be aware of potential loss of precision when converting larger data types to
smaller ones.
 Data Overflow: Ensure that the target data type can accommodate the value being converted.
 Use Casting Judiciously: Cast only when necessary and be mindful of the potential consequences.
 Check for Potential Errors: Always verify the correctness of the conversion, especially when
dealing with complex expressions.

Simple Java Program

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Constructors
A constructor is a special method in Java that is automatically called when an object of a class is
created. It's primarily used to initialize the object's state.

Key Points about Constructors:

1. Name: The constructor's name must be the same as the class name.
2. Return Type: Constructors do not have a return type, not even void.
3. Invocation: Constructors are invoked automatically when you create an object using the new
keyword.

Types of Constructors:

1. Default Constructor:
o A default constructor is a no-argument constructor that is automatically provided by the
compiler if you don't explicitly define any constructors.
o It initializes the object's instance variables to their default values.

2. Parameterized Constructor:
o A parameterized constructor accepts arguments to initialize the object's instance variables.
o You can define multiple parameterized constructors with different argument lists to provide
flexibility in object creation.

Example:

class Car {
String color;
int year;

// Default constructor
public Car() {
color = "White";
year = 2023;
}

// Parameterized constructor
public Car(String color, int year) {
this.color = color;
this.year = year;
}
}

public class Main {


public static void main(String[] args) {
// Creating objects using different constructors
Car car1 = new Car(); // Using default constructor
Car car2 = new Car("Red", 2022); // Using parameterized constructor

// Accessing object properties


System.out.println("Car 1 color: " + car1.color + ", year: " + car1.year);
System.out.println("Car 2 color: " + car2.color + ", year: " + car2.year);
}
}

Why Use Constructors?


 Initialization: Ensure that objects are created in a valid state.
 Flexibility: Provide different ways to create objects with various initializations.
 Code Reusability: Centralize object initialization logic in one place.

Methods

Methods are the building blocks of Java programs. They encapsulate a specific task or behavior and can
be reused throughout your code.

Basic Structure of a Method:

public static return_type method_name(parameter_list) {


// Method body
// ...
return value; // If the method has a return type
}

Explanation of the components:

 public: Access modifier, making the method accessible from anywhere.


 static: Keyword indicating that the method belongs to the class itself, not to any specific object.
 return_type: The data type of the value returned by the method. If the method doesn't return
anything, the return type is void.
 method_name: The unique name of the method.
 parameter_list: A comma-separated list of parameters, each with its data type and name.
 Method body: The code that implements the method's functionality.
 return value: The value returned by the method, if any.

Example:

public class Calculator {


public static int add(int a, int b) {
int sum = a + b;
return sum;
}

public static void greet(String name) {


System.out.println("Hello, " + name + "!");
}

public static void main(String[] args) {


int result = add(5, 3);
System.out.println("The sum is: " + result);

greet("Alice");
}
}

Key Points:

 Method Overloading: You can define multiple methods with the same name but different
parameter lists.
 Method Overriding: You can redefine a method in a subclass to provide a specific
implementation.
 Recursion: A method can call itself directly or indirectly.
 Method Signatures: The method signature consists of the method name and the parameter list. It's
used to uniquely identify a method.

Static Block

A static block is a block of code that is executed only once, when the class is first loaded into memory. It's
often used to initialize static variables or perform other one-time setup tasks.

Syntax:

static {
// Code to be executed once
}

Example:

public class MyClass {


static {
System.out.println("Static block executed.");
}

public static void main(String[] args) {


System.out.println("Main method executed.");

}
}

Output:

Static block executed.


Main method executed.

Static Data

In Java, static data members are associated with the class itself, rather than with individual objects of the
class. This means that they are shared by all instances of the class.

Key Points:

 Declaration:
o Static data members are declared using the static keyword.
o They can be variables or methods.
 Memory Allocation:
o Static data members are allocated memory only once, when the class is loaded into
memory.
 Access:
o They can be accessed directly using the class name, without creating an object.
 Persistence:
o Static data members retain their values across different object instances.

Example:
public class MyClass {
static int count = 0; // Static variable
public void incrementCount() {
count++;
}

public static void main(String[] args) {


MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();

obj1.incrementCount();
obj2.incrementCount();

System.out.println("Count: " + count); // Output: 2


}
}

Static Method

Static Methods in Java

A static method is a method that belongs to a class rather than an instance of a class. This means that you
can call a static method without creating an object of the class.

Key Points:

 Declaration:
o Declared using the static keyword.
 Access:
o Can be accessed directly using the class name.
 No this Keyword:
o Cannot access instance variables or methods directly.
 Common Use Cases:
o Utility methods: Methods that perform common tasks like mathematical calculations, string
manipulation, etc.
o Factory methods: Methods that create and return objects.
o Main method: The entry point of every Java application.

Example:

public class MathUtils {


public static int add(int a, int b) {
return a + b;
}

public static double calculateArea(double radius) {


return Math.PI * radius * radius;
}
}

public class Main {


public static void main(String[] args) {
int sum = MathUtils.add(5, 3);
double area = MathUtils.calculateArea(2.5);
System.out.println("Sum: " + sum);
System.out.println("Area: " + area);
}
}

Explanation:

 The add and calculateArea methods are static methods of the MathUtils class.
 They can be called directly using the class name, without creating an object of the MathUtils class.
 This is because static methods belong to the class itself, not to individual objects.

Key Considerations:

 Static methods cannot access instance variables or methods directly.


 Static methods are often used for utility functions that are independent of object state.
 Static methods can be useful for creating reusable code that can be called from anywhere in your
application.

String and String Buffer Classes

String Class

 Immutable: Once a String object is created, its value cannot be changed.


 Used for representing fixed character sequences.

Key Methods:

 length(): Returns the length of the string.


 charAt(index): Returns the character at the specified index.
 concat(str): Concatenates the specified string to the end of this string.
 substring(beginIndex): Returns a new string that is a substring of this string.
 substring(beginIndex, endIndex): Returns a new string that is a substring of this string.
 indexOf(str): Returns the index within this string of the first occurrence of the specified substring.
 toLowerCase(): Converts all of the characters in this String to lowercase.
 toUpperCase(): Converts all of the characters in this String to uppercase.
 trim(): Returns a copy of the string, with leading and trailing whitespace omitted.

StringBuffer Class

 Mutable: The contents of a StringBuffer object can be modified.


 Used for manipulating character sequences efficiently.

Key Methods:

 append(str): Appends the specified string to the end of this character sequence.
 insert(offset, str): Inserts the specified string into this character sequence.
 deleteCharAt(index): Deletes the character at the specified index.
 delete(startIndex, endIndex): Deletes the characters in a specified range.
 replace(startIndex, endIndex, str): Replaces the characters in a specified range with a new
string.
 reverse(): Reverses the character sequence.

Example:
public class StringAndStringBufferExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";

// String concatenation
String str3 = str1 + " " + str2;
System.out.println(str3);

// StringBuffer
StringBuffer sb = new StringBuffer("Java");
sb.append(" Programming");
sb.insert(5, " is ");
System.out.println(sb);
}
}

Choosing Between String and StringBuffer:

 String: Use for fixed character sequences that don't require modification.
 StringBuffer: Use for frequent modifications to character sequences.

1 MARK:

1. Which of the following is NOT a core principle of OOP?

a) Inheritance

b) Polymorphism

c) Encapsulation

d) Compilation

2. What is the process of binding data members and member functions together into a single
unit?

a) Inheritance

b) Encapsulation

c) Polymorphism

d) Abstraction
3. Who is the creator of Java?

a) Dennis Ritchie

b) James Gosling

c) Bjarne Stroustrup

d) Linus Torvalds
4. What does WORA stand for in the context of Java?

a) Write Once, Run Anywhere

b) World Object, Real Architecture

c) Web Object, Remote Access

d) World Oriented, Real Application

5. Which component of the JVM is responsible for executing bytecode?

a) ClassLoader

b) Runtime Data Area

c) Execution Engine

d) Native Method Interface

6. Which data type is used to represent decimal numbers with a fractional part?

a) int

b) float

c) char

d) boolean

7. What is the scope of a variable declared inside a method?

a) Class-level

b) Method-level

c) Block-level

d) Global-level

8. What is the index of the first element in a Java array?

a) 0

b) 1

c) -1

d) Array size

9. Which operator is used to perform logical AND operation?

a) ||
b) &&

c) |

d) &

10. Which loop is best suited for iterating a fixed number of times?

a) while loop

b) do-while loop

c) for loop

d) switch-case
11. What is the process of converting a larger data type to a smaller data type called?

a) Widening conversion

b) Narrowing conversion

c) Implicit conversion

d) Explicit conversion

12. Which method is automatically called when an object of a class is created?

a) main method

b) static method

c) constructor

d) destructor

13. What is the purpose of the this keyword in Java?

a) To refer to the current class

b) To refer to the parent class

c) To refer to the current object

d) To refer to a static variable

14. When is a static block executed?

a) When an object of the class is created

b) When the class is loaded into memory

c) When a static method is called


d) When the program starts

15. Can a static method access instance variables directly?


a) Yes

b) No

c) Only if the instance variable is declared as public

d) Only if the instance variable is declared as static

5-Mark and 10-Mark Questions:

1. Explain about Object-Oriented Programming (OOP) Concepts


2. Explain about Java Basics
3. Explain about Control Flow Statements
4. Explain about Arrays
5. Explain about Classes and Objects
6. Define Inheritance and Polymorphism

7. Explain about Exception Handling

8. Define Input/Output Operations

UNIT-II:

Inheritance: A Fundamental OOP Concept

Inheritance is a powerful mechanism in object-oriented programming (OOP) that allows one class to
inherit the properties and behaviors of another class. This promotes code reusability and creates a
hierarchical relationship between classes.

Key Concepts

 Parent Class (Superclass): The class whose properties and methods are inherited.
 Child Class (Subclass): The class that inherits from the parent class.

Types of Inheritance

1. Single Inheritance: A class inherits from only one parent class.

class Animal {
// ...
}

class Dog extends Animal {


// ...
}
2. Multiple Inheritance: A class inherits from multiple parent classes (not directly supported in Java
but can be achieved using interfaces).
3. Hierarchical Inheritance: Multiple child classes inherit from a single parent class.

class Vehicle {
// ...
}

class Car extends Vehicle {


// ...
}

class Bike extends Vehicle {


// ...
}

4. Multilevel Inheritance: A class inherits from a child class of another class.

class Vehicle {
// ...
}

class Car extends Vehicle {


// ...
}

class SportsCar extends Car {


// ...
}

5. Hybrid Inheritance: A combination of multiple inheritance and hierarchical inheritance.

Member Access Rules in Inheritance

 Public members: Inherited and accessible from anywhere.


 Protected members: Inherited and accessible within the package and subclasses.
 Private members: Not inherited.
 Default members: Inherited and accessible within the package.

this and super Keywords

 this keyword:
o Refers to the current object.
o Used to distinguish between instance variables and parameters with the same name.
o Used to call other constructors of the same class.
 super keyword:
o Refers to the parent class object.
o Used to call parent class constructors.
o Used to access parent class members when there's a name conflict with child class
members.

Example:

class Animal {
void makeSound() {
System.out.println("Generic animal sound");
}
}

class Dog extends Animal {


@Override
void makeSound() {
System.out.println("Woof!");

}
}

In this example, the Dog class inherits from the Animal class. It overrides the makeSound() method to
provide a specific implementation for dogs.

Key Benefits of Inheritance:

 Code Reusability: Avoids redundant code by inheriting common properties and behaviors.
 Polymorphism: Enables objects to take on many forms, promoting flexibility and extensibility.
 Modularity: Encourages breaking down complex systems into smaller, more manageable units.

Member Access Rules in Java Inheritance

In Java, member access rules determine the visibility of class members (fields and methods) to
other classes. This is crucial for understanding how inheritance works and controlling the exposure of
your class's internals.

Here are the four primary access modifiers and their visibility rules:

1. Public:
o Accessible from anywhere: within the same class, package, or other classes.
o Declared using the public keyword.
2. Protected:
o Accessible within the same package and subclasses.
o Declared using the protected keyword.
3. Default (Package-Private):
o Accessible within the same package.
o Declared without any access modifier.
4. Private:
o Accessible only within the same class.
o Declared using the private keyword.

Inheritance and Member Access:

 Public members: Inherited and accessible from anywhere.


 Protected members: Inherited and accessible within the same package and subclasses.
 Default members: Inherited and accessible within the same package.
 Private members: Not inherited.

Example:

class Animal {
public String name; // Accessible anywhere
protected int age; // Accessible within the package and subclasses
private String color; // Accessible only within the Animal class
}

class Dog extends Animal {


public void bark() {
System.out.println("Woof!");
// Can access name and age, but not color
}
}

The this and super Keywords in Java

In Java, the this and super keywords are essential for understanding object-oriented programming
concepts. They provide a way to refer to specific objects and their members.

The this Keyword

The this keyword refers to the current object. It's used in various scenarios:

1. Distinguishing Between Instance Variables and Parameters: When an instance variable and a
parameter have the same name, the this keyword can be used to differentiate between them.

class Person {
String name;

public Person(String name) {


this.name = name; // `this.name` refers to the instance variable
}
}

2. Calling Other Constructors: You can use this() to call another constructor of the same class.

class Person {
String name;
int age;

public Person(String name) {


this(name, 25); // Calls the constructor with two arguments
}

public Person(String name, int age) {


this.name = name;
this.age = age;
}
}

3. Returning the Current Object: You can use this to return the current object itself, often used in
method chaining.

Java

class StringBuilder {
// ...
public StringBuilder append(String str) {
// ...
return this; // Returns the current StringBuilder object
}
}

The super Keyword

The super keyword refers to the parent class object. It's primarily used in the following scenarios:

1. Calling Parent Class Constructors: You can use super() to call the parent class's constructor.

class Child extends Parent {


public Child() {
super(); // Calls the default constructor of the Parent class
}
}

2. Accessing Parent Class Members: You can use super to access members of the parent class when
there's a name conflict with a member in the child class.

class Animal {
void makeSound() {
System.out.println("Generic animal sound");
}
}

class Dog extends Animal {


void makeSound() {
super.makeSound(); // Calls the parent class's makeSound() method
System.out.println("Woof!");
}
}

Method Overloading

Method overloading is a technique in Java that allows you to define multiple methods with the same
name but different parameter lists within the same class. The compiler differentiates between these
methods based on the number, type, and order of their parameters.

Key Points:

 Same Method Name: All overloaded methods must have the same name.
 Different Parameter Lists: The parameter lists must differ in terms of the number, type, or order
of parameters.
 Return Type: The return type can be the same or different.

Example:

class Calculator {
public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {


return a + b;
}

public int add(int a, int b, int c) {


return a + b + c;

}
}

In this example, we have three add methods with different parameter lists:

1. add(int, int): Adds two integers.


2. add(double, double): Adds two doubles.
3. add(int, int, int): Adds three integers.

How the Compiler Distinguishes:

The compiler determines which overloaded method to call based on the arguments passed at the call site.
It matches the number, type, and order of the arguments with the parameter lists of the available methods.

Example Usage:

Calculator calculator = new Calculator();


int sum1 = calculator.add(5, 3); // Calls add(int, int)
double sum2 = calculator.add(2.5, 3.7); // Calls add(double, double)
int sum3 = calculator.add(1, 2, 3); // Calls add(int, int, int)

Key Points to Remember:

 Overloaded methods must have different parameter lists, not just different return types.
 Overloading does not involve inheritance. It's a technique within a single class.
 Overloading can make code more flexible and readable by providing different ways to perform the
same operation.

Method Overriding

Method overriding is a feature in object-oriented programming where a subclass provides a


specific implementation of a method that is already defined in its parent class. This allows the subclass to
customize the behavior of the inherited method.

Key Points:

 Same Method Signature: The overriding method in the subclass must have the same name, return
type, and parameter list as the original method in the parent class.
 Access Modifiers: The overriding method's access modifier can be the same or more permissive
than the original method's access modifier. For example, a protected method can be overridden
with a public method.
 Dynamic Binding: The appropriate method to be called is determined at runtime based on the
actual object type, not the declared type. This is known as polymorphism.

Example:
class Animal {
public void makeSound() {
System.out.println("Generic animal sound");
}
}

class Dog extends Animal {


@Override
public void makeSound() {
System.out.println("Woof!");

}
}

In this example:

1. The Animal class has a makeSound() method that prints a generic sound.
2. The Dog class inherits from Animal and overrides the makeSound() method to print a specific
sound for dogs.

When we create a Dog object and call the makeSound() method on it, the overridden version from the Dog
class will be executed.

Key Benefits of Method Overriding:

 Polymorphism: Allows objects of different types to be treated as objects of a common superclass.


 Code Reusability: Inherits the common behavior from the parent class and overrides it to provide
specific implementations.
 Flexibility: Enables customization of behavior based on the specific needs of subclasses.

Abstract Classes

An abstract class is a class that cannot be instantiated directly. It serves as a blueprint for other classes,
defining common attributes and behaviors. Abstract classes often contain one or more abstract methods,
which are methods declared without a body. Subclasses must provide implementations for these abstract
methods.

Key characteristics of abstract classes:

 Cannot be instantiated: You cannot create objects of an abstract class directly.


 Can contain abstract methods: These methods have no body and must be implemented by
subclasses.
 Can contain concrete methods: These methods have a body and can be directly inherited or
overridden by subclasses.

Example:

abstract class Shape {


abstract void draw(); // Abstract method

public void erase() {


System.out.println("Erasing shape"); // Concrete method
}
}

class Circle extends Shape {


@Override
void draw() {
System.out.println("Drawing a circle");
}
}

Dynamic Method Dispatch

Dynamic method dispatch, also known as late binding or runtime polymorphism, is the process of
determining the appropriate method to call at runtime based on the actual object type, not the declared
type. This allows for flexible and extensible code.

Key points about dynamic method dispatch:

 Based on object type: The method to be called is determined by the object's actual type, not the
reference variable's declared type.
 Occurs at runtime: The decision is made at runtime, not at compile time.
 Requires inheritance: Dynamic method dispatch relies on inheritance to create a hierarchy of
classes.

Example:

Shape shape = new Circle();


shape.draw(); // Calls the `draw()` method of the Circle class

The final Keyword

The final keyword in Java has multiple uses:

1. Final Variables:
o Declares a constant variable whose value cannot be changed after initialization.
o Can be used with primitive data types and reference types.

2. Final Methods:
o Prevents a method from being overridden by subclasses.
o Ensures that the method's behavior remains consistent across the inheritance hierarchy.

3. Final Classes:
o Prevents a class from being subclassed.
o Ensures that the class's behavior cannot be modified by inheritance.

Example:

final class ImmutableClass {


private final int x;

public ImmutableClass(int x) {
this.x = x;
}
public int getX() {
return x;
}
}

Combining Concepts

Abstract classes, dynamic method dispatch, and the final keyword work together to create
powerful and flexible object-oriented designs. By using abstract classes to define common interfaces and
dynamic method dispatch to select the appropriate implementation at runtime, you can create code that is
both adaptable and efficient. The final keyword can be used to control the mutability of variables, the
overridability of methods, and the subclassability of classes.

PACKAGE:

In Java, a package is a mechanism to group related classes, interfaces, and sub-packages. It's like a
container that organizes your code into a hierarchical structure, making it more manageable and reusable.

Key Purposes of Packages:

1. Namespace Management:
o Prevents naming conflicts between classes with the same name but different functionalities.
o Each class belongs to a specific package, creating a unique identifier.

2. Code Organization:
o Groups related classes and interfaces together, improving code readability and
maintainability.
o Makes it easier to find and understand specific classes within a project.

3. Access Control:
o Provides control over the visibility of classes and interfaces.
o Packages can define access levels (public, protected, default, private) to restrict access to
certain parts of your code.

4. Reusability:
o Encapsulates reusable code components into packages that can be shared across different
projects.

Example:

package com.example.myproject;

public class MyClass {


// ...
}

In this example, com.example.myproject is the package name. All classes defined within this file belong
to this package.

To use a class from another package, you need to import it:


import com.example.myproject.MyClass;

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass();
// ...
}
}
Common Java Packages:

 java.lang: Contains fundamental classes like String, Integer, System, etc.


 java.util: Provides utility classes like Date, Calendar, Random, and collections framework classes.
 java.io: Offers classes for input/output operations like file handling and network programming.
 java.net: Contains classes for network programming, such as sockets and URLs.
 java.sql: Provides classes for database connectivity and operations.

ACCESS PROTECTION IN JAVA:

In Java, access protection refers to the control over the visibility of classes, interfaces, and their members
(methods and variables) across different packages. This is achieved through the use of access modifiers.

Here are the four access modifiers in Java:

1. Public:
o Accessible from anywhere, including other packages.
o Declared using the public keyword.
2. Protected:
o Accessible within the same package and subclasses in other packages.
o Declared using the protected keyword.
3. Default (Package-Private):
o Accessible within the same package only.
o No keyword is used to declare it.
4. Private:
o Accessible only within the same class.
o Declared using the private keyword.

Example:

package com.example.package1;

public class ParentClass {


public int publicVariable;
protected int protectedVariable;
int defaultVariable;
private int privateVariable;

public void publicMethod()


{
// ...
}

protected void protectedMethod() {


// ...
}
void defaultMethod() {
// ...
}

private void privateMethod() {


// ...
}
}

package
com.example.package2;

public class ChildClass extends ParentClass {


public void accessMembers() {
publicVariable = 10; // Accessible
protectedVariable = 20; // Accessible
// defaultVariable = 30; // Not accessible
// privateVariable = 40; // Not accessible

publicMethod(); // Accessible
protectedMethod(); // Accessible
// defaultMethod(); // Not accessible
// privateMethod(); // Not accessible
}
}

IMPORTING PACKAGES:

n Java, you can import classes and interfaces from other packages to use them in your code. This is
done using the import statement.

Syntax:

import package_name.class_name;

Example:

import java.util.Scanner;

public class MyClass {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter
a number: ");
int number = scanner.nextInt();
System.out.println("You entered: " + number);
}
}

In this example, we import the Scanner class from the java.util package. This allows us to create a
Scanner object to read input from the user.

Importing All Classes from a Package:


You can also import all classes from a package using the * wildcard:

import java.util.*;

public class MyClass {


// ...
}

However, it's generally recommended to import only the specific classes you need. Importing all
classes can make your code less readable and can potentially introduce naming conflicts.

Package Hierarchy:

Java packages can be organized in a hierarchical structure. To import a class from a subpackage,
you can use the following syntax:

import package_name.subpackage_name.class_name;

Example:

import java.util.ArrayList;
import java.util.List;

public class MyClass {


public static void main(String[] args) {
List<String> names = new ArrayList<>();

// ...
}
}

Important Considerations:

 Default Package: If a class is not explicitly declared in a package, it belongs to the default
package. Classes in the default package can only be accessed from other classes in the same
package.
 Fully Qualified Names: If you don't import a class, you can still use it by specifying its fully
qualified name:

java.util.Scanner scanner = new java.util.Scanner(System.in);

INTERFACES:

Definition:

An interface in Java is a blueprint of a class. It defines a set of abstract methods that a class must
implement. Interfaces are used to achieve abstraction and polymorphism.

Key Points:

 Interfaces cannot have constructors.


 All methods in an interface are public and abstract by default, even if not explicitly declared.
 Interfaces can contain static final variables.
 A class can implement multiple interfaces.
 Interfaces can extend other interfaces.

Implementation:

A class implements an interface using the implements keyword. It must provide implementations for all
the abstract methods defined in the interface.

Example:

interface Drawable {
void draw();
}

class Rectangle implements Drawable {


@Override
public void draw() {
System.out.println("Drawing a rectangle.");

}
}

Extending Interfaces:

Interfaces can extend other interfaces. This allows for creating hierarchical relationships between
interfaces.

Example:

interface Shape {
void draw();
}

interface Colorable {
void setColor(String color);
}

interface ColoredShape extends Shape, Colorable {


// Inherits methods from Shape and Colorable
}

class ColoredRectangle implements ColoredShape {


@Override
public void draw() {
System.out.println("Drawing a colored rectangle.");
}

@Override
public void setColor(String color) {
System.out.println("Setting color to " + color);
}
}
Advantages of Using Interfaces:

 Abstraction: Interfaces provide a clear abstraction of what a class should be able to do, without
specifying how it's done.
 Polymorphism: Different classes can implement the same interface, allowing for polymorphic
behavior.
 Loose Coupling: Interfaces promote loose coupling between classes, making code more modular
and easier to maintain.
 Multiple Inheritance: A class can implement multiple interfaces, unlike class inheritance, which
is single.
 Design Patterns: Interfaces are essential in many design patterns, such as the Strategy, Observer,
and Factory patterns.

Exception Handling in Java

Exception handling is a mechanism to handle errors and unexpected events that may occur during program
execution. It helps in preventing program crashes and provides a graceful way to handle errors.

Key Concepts:

1. Try-Catch Block:
o The try block encloses the code that might throw an exception.
o The catch block handles the exception if it occurs.

try {
// Code that might throw an exception
} catch (ExceptionType exceptionObject) {
// Handle the exception
}

2. Throw Keyword:
o The throw keyword is used to explicitly throw an exception.

if (age < 18) {


throw new IllegalArgumentException("Age must be 18 or older");
}

3. Throws Keyword:
o The throws keyword is used to declare that a method might throw an exception.

public void myMethod() throws IOException {


// Code that might throw an IOException
}

4. Finally Block:
o The finally block is executed regardless of whether an exception is thrown or caught. It's
often used for cleanup tasks like closing files or database connections.

try {
// Code that might throw an exception
} catch (Exception e) {
// Handle the exception
} finally {
// Code to be executed always
}

Built-in Exceptions:

Java provides a rich set of built-in exceptions, categorized into different hierarchies. Some common
exceptions include:

 ArithmeticException: Occurs when an arithmetic operation fails, like division by zero.


 NullPointerException: Occurs when trying to access a member of an object that is null.
 ArrayIndexOutOfBoundsException: Occurs when trying to access an array element with an
invalid index.
 IOException: Occurs during input/output operations.
 ClassNotFoundException: Occurs when a class cannot be found.

Creating Custom Exception Classes:

You can create your own custom exception classes by extending the Exception class or one of its
subclasses.

public class MyCustomException extends Exception {


public MyCustomException(String message) {
super(message);
}
}

Best Practices for Exception Handling:

 Catch Specific Exceptions: Catch specific exceptions to handle them appropriately.


 Avoid Empty Catch Blocks: Always provide meaningful error handling within catch blocks.
 Use finally Block for Cleanup: Ensure resources are released properly.
 Throw Exceptions Appropriately: Throw exceptions only when necessary.
 Provide Informative Error Messages: Include relevant details in exception messages.
 Test Exception Handling: Write unit tests to verify exception handling behavior.

By following these guidelines and using exception handling effectively, you can write robust and reliable
Java applications.

1 Mark:

Inheritance:

1. Which of the following is not a type of inheritance in Java?

a) Single inheritance

b) Multiple inheritance

c) Hierarchical inheritance

d) Hybrid inheritance

2. Which access modifier can be used to make a member accessible within the same package
and subclasses?
a) public

b) private

c) protected

d) default

3. What is the purpose of the super keyword?

a) To refer to the current object

b) To refer to the parent class object

c) To declare a variable as final

d) To declare a method as abstract

4. What is the difference between method overloading and method overriding?

a) Method overloading involves different return types, while method overriding involves different
parameter lists.

b) Method overloading involves different parameter lists, while method overriding involves
the same method signature but different implementations.

c) Method overloading involves the same method signature but different implementations, while
method overriding involves different parameter lists.

d) Both involve the same method signature but different implementations.

5. What is an abstract class?

a) A class that cannot be instantiated directly.

b) A class that can only contain abstract methods.

c) A class that is fully implemented.

d) A class that can only be inherited once.

6. Which of the following is not an access modifier for packages?

a) public

b) private

c) protected

d) default

7. What is the purpose of the import statement?

a) To create a new package.


b) To import classes and interfaces from other packages.

c) To declare a class as public.

d) To define a package-private class.

8. Can an interface extend another interface?

a) Yes

b) No

9. Can a class implement multiple interfaces?

a) Yes

b) No

10. What is the purpose of the finally block?

a) To handle exceptions.

b) To throw exceptions.

c) To execute a block of code regardless of whether an exception is thrown or caught.

d) To declare that a method might throw an exception.

11. Which keyword is used to inherit a class?

a) extends

b) implements

c) inherits

d) derives

12. What is the process of creating new classes from existing ones called?

a) Polymorphism

b) Encapsulation

c) Inheritance

d) Abstraction

13. What is the access specifier that allows a class to be accessed from any package?

a) public

b) private
c) protected

d) default

14. Which keyword is used to refer to the current object?

a) self

b) this

c) current

d) instance

14. What is the process of having two or more methods with the same name but different
parameters called?

a) Method overriding

b) Method overloading

c) Method hiding

d) Method binding

15. Which type of inheritance involves a class inheriting from multiple parent classes?

a) Single inheritance

b) Multiple inheritance

c) Hierarchical inheritance

d) Multilevel inheritance

Answer: b) Multiple inheritance (Note: Java doesn't directly support multiple inheritance, but
it can be achieved using interfaces.)

16. What is an abstract class?

a) A class that cannot be instantiated

b) A class that has only abstract methods

c) A class that is fully implemented

d) A class that is used for inheritance only

17. What is an interface in Java?

a) A class that contains only abstract methods

b) A class that contains only concrete methods


c) A class that can be inherited by other classes

d) A class that is used to define constants

18. Which keyword is used to throw an exception explicitly?

a) catch

b) throw

c) throws

d) finally

19. Which block of code is always executed, regardless of whether an exception occurs?

a) try

b) catch

c) finally

d) throw

5 MARKS AND 10 MARKS QUESTIONS:

1. What is inheritance? Explain its types with examples.


2. What is the difference between method overloading and method overriding? Explain with code
examples.
3. What is the difference between this and super keywords?
4. What is an abstract class? How is it different from an interface?
5. What is the role of the super keyword in Java inheritance?
6. Explain the concept of dynamic method dispatch with a code example.
7. Discuss the use of the final keyword in the context of inheritance.
8. What is a package in Java? How does it help in organizing code?
9. Explain the different access modifiers used in packages.
10. What is the purpose of the import statement?
11. What is an interface in Java? How is it different from an abstract class?
12. Explain the try-catch-finally block in Java exception handling.
13. What is the difference between checked and unchecked exceptions?
14. What is the purpose of the this keyword? Explain with a code example.
15. How do you implement an interface?
16. Can an interface extend another interface?
17. What is exception handling in Java?
18. Explain the try-catch-finally block.
19. What is the difference between throw and throws keywords?
20. How can you create a custom exception class?

UNIT-III

Multithreaded Programming:

Multithreading is a programming technique that allows multiple threads of execution to run


concurrently within a single process. This enables efficient utilization of system resources, especially in
CPU-bound or I/O-bound applications.

Key Concepts:

1. Thread:
o A basic unit of execution within a process.
o Each thread has its own program counter, stack, and local variables.
o Multiple threads can share the same heap memory.

2. Thread Creation:
o Extending the Thread class: Create a new class that extends the Thread class and override
the run() method.
o Implementing the Runnable interface: Create a new class that implements the Runnable
interface and implement the run() method.

3. Thread Lifecycle:
o New: Thread is created but not yet started.
o Runnable: Thread is ready to run but waiting for CPU time.
o Running: Thread is currently executing.
o Blocked: Thread is waiting for a resource or event.
o Terminated: Thread has finished execution.

4. Thread Synchronization:
o Ensures that multiple threads access shared resources in a controlled manner.
o Techniques:
 Synchronized methods: Only one thread can execute a synchronized method on a
particular object at a time.
 Synchronized blocks: A specific block of code is synchronized, allowing multiple
threads to access other parts of the object concurrently.
 Volatile keyword: Ensures that changes to a variable are visible to all threads.

5. Inter-Thread Communication:
o wait() and notify(): Used to pause and resume threads.
o join(): Waits for a thread to finish execution.

6. Deadlock:
o Occurs when two or more threads are blocked, waiting for each other to release a resource.
o To avoid deadlock:
 Acquire locks in a specific order.
 Use timeouts for acquiring locks.
 Avoid nested locks.

Example:

class MyThread extends Thread {


public void run() {
// Thread's execution code
}
}

class MyRunnable implements Runnable {


public void run() {
// Thread's execution code
}
}

// Creating and starting a thread using Thread class:


Thread t1 = new MyThread();
t1.start();

// Creating and starting a thread using Runnable interface:


Thread t2 = new Thread(new MyRunnable());
t2.start();

Benefits of Multithreading:

 Improved application responsiveness.


 Efficient utilization of system resources.
 Enhanced performance for CPU-bound and I/O-bound tasks.
 Ability to handle multiple tasks concurrently.

Challenges of Multithreading:

 Complexity: Multithreaded programming can be complex due to issues like synchronization,


deadlock, and race conditions.
 Debugging: Debugging multithreaded applications can be challenging.
 Performance overhead: Excessive thread creation and context switching can impact performance.

By understanding these concepts and best practices, you can effectively leverage multithreading to create
efficient and responsive applications.

Thread Class in Java

The Thread class in Java represents an individual thread of execution. It provides a way to create and
manage multiple threads within a single process.

Creating a Thread:

1. Extending the Thread class:


o Create a new class that extends the Thread class.
o Override the run() method to define the thread's behavior.

class MyThread extends Thread {


public void run() {
// Thread's execution code
}
}

2. Implementing the Runnable interface:


o Create a new class that implements the Runnable interface.
o Implement the run() method to define the thread's behavior.
o Pass an instance of this class to a Thread object.

class MyRunnable implements Runnable {


public void run() {
// Thread's execution code
}
}

Thread t = new Thread(new MyRunnable());

Starting a Thread:

To start a thread, call the start() method on the Thread object. This method creates a new thread and
invokes the run() method.

MyThread t = new MyThread();


t.start();

Thread Lifecycle:

A thread goes through the following states:

1. New: The thread is created but not yet started.


2. Runnable: The thread is ready to run but waiting for CPU time.
3. Running: The thread is currently executing.
4. Blocked: The thread is waiting for a resource or event.
5. Terminated: The thread has finished execution.

Thread Synchronization:

To ensure thread safety when multiple threads access shared resources, you can use synchronization
mechanisms like:

 Synchronized methods:
o Only one thread can execute a synchronized method on a particular object at a time.
 Synchronized blocks:
o A specific block of code is synchronized, allowing multiple threads to access other parts of
the object concurrently.
 Volatile keyword:
o Ensures that changes to a variable are visible to all threads.

Inter-Thread Communication:

 wait() and notify(): Used to pause and resume threads.


 join(): Waits for a thread to finish execution.
Runnable Interface

In Java, the Runnable interface is a fundamental building block for creating and managing threads. It
defines a single method, run(), which contains the code to be executed by the thread.

Implementing the Runnable Interface:

To create a thread using the Runnable interface, you follow these steps:

1. Create a class:
o Define a class that implements the Runnable interface.

2. Implement the run() method:


o Override the run() method to specify the actions the thread should perform.

3. Create a Thread object:


o Instantiate a Thread object and pass an instance of the class that implements Runnable to its
constructor.

4. Start the thread:


o Call the start() method on the Thread object to initiate execution.

Example:

class MyRunnable implements Runnable {


public void run() {
System.out.println("Thread is running");
// Add more code to be executed by the thread
}
}

public class Main {


public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();

}
}

Advantages of using Runnable interface:

 Multiple inheritance: A class can implement multiple interfaces, including Runnable, whereas
Java doesn't support multiple inheritance for classes.
 Flexibility: You can create multiple Thread objects with the same Runnable object, sharing the
same run() method.

Key Points to Remember:

 The run() method is the entry point for a thread.


 Multiple threads can share the same Runnable object.
 The start() method initiates the thread's execution.
 The Thread class provides various methods for controlling thread execution, such as join(), sleep(),
and interrupt().
 Synchronization is essential for handling shared resources and preventing race conditions.

Synchronization in Java

Synchronization is a crucial concept in multithreaded programming to ensure that multiple threads access
shared resources in a controlled manner. It prevents race conditions and data corruption.Methods of
Synchronization:

1. Synchronized Methods:
o Declared with the synchronized keyword.
o Only one thread can execute a synchronized method on a particular object at a time.

public synchronized void synchronizedMethod() {


// Critical section of code

2. Synchronized Blocks:
o More granular control over synchronization.
o A specific block of code is synchronized, allowing multiple threads to access other parts of
the object concurrently.

public void someMethod() {


synchronized(object) {
// Critical section of code
}
}

3. Volatile Keyword:
o Ensures that changes to a variable are visible to all threads.
o It's useful for simple shared variables that don't require complex synchronization.

Inter-Thread Communication:

 wait() and notify():


o Used to pause and resume threads.
o wait() releases the lock and waits for a notification.
o notify() wakes up a waiting thread.
 join():
o Waits for a thread to finish execution.

Deadlocks:

 Occur when two or more threads are blocked, waiting for each other to release a resource.
 To avoid deadlocks:
o Acquire locks in a specific order.
o Use timeouts for acquiring locks.
o Avoid nested locks.

Example:
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}

public int getCount() {


return count;
}
}

public class Main {


public static void main(String[] args)
{
Counter counter = new Counter();

Thread t1 = new Thread(() -> {


for (int i = 0; i < 10000; i++) {
counter.increment();
}
});

Thread t2 = new Thread(() -> {


for (int i = 0; i < 10000; i++) {
counter.increment();

}
});

t1.start();
t2.start();

try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Final
count: " + counter.getCount());
}
}

Using Synchronized Methods

Synchronized methods are a powerful tool in Java for ensuring thread safety when multiple threads
access shared resources. By declaring a method as synchronized, you guarantee that only one thread can
execute that method on a specific object at a time.

How it works:

1. Implicit Locking: When a thread enters a synchronized method, it acquires a lock on the object
associated with that method.
2. Exclusive Access: While one thread holds the lock, other threads attempting to enter the same
synchronized method on the same object are blocked.
3. Releasing the Lock: Once the thread finishes executing the synchronized method, it releases the
lock, allowing other waiting threads to acquire it.

Example:

class Counter {
private int count = 0;

public synchronized void increment() {


count++;
}

public int getCount() {


return count;

}
}

In this example, the increment() method is synchronized, ensuring that only one thread can modify
the count variable at a time. This prevents race conditions and ensures that the count value is accurate.

When to Use Synchronized Methods:

 Protecting shared mutable state: When multiple threads access and modify the same shared
object.
 Simple synchronization scenarios: For straightforward synchronization needs, synchronized
methods can be a convenient solution.

Considerations and Best Practices:

 Granularity: Use synchronized methods judiciously. Overusing them can lead to performance
bottlenecks.
 Deadlocks: Be careful to avoid deadlocks, especially when using multiple locks.
 Performance Impact: Synchronized methods can impact performance, so use them only when
necessary.
 Alternative Approaches: Consider using higher-level concurrency utilities like
java.util.concurrent for more complex synchronization scenarios.

Remember:

 Synchronized methods can be applied to both instance methods and static methods.
 For static methods, the lock is associated with the class object.
 While synchronized methods are a useful tool, it's essential to balance synchronization with
performance considerations.

Using Synchronized Statements

Synchronized statements provide a more granular approach to synchronization than synchronized


methods. They allow you to specify a specific block of code within a method that needs to be
synchronized, rather than synchronizing the entire method.

Syntax:

synchronized (object) {
// Critical section of code
}

How it works:

1. Acquiring the Lock: When a thread enters a synchronized block, it acquires a lock on the
specified object.
2. Exclusive Access: Only one thread can hold the lock at a time. Other threads trying to enter the
same synchronized block will be blocked until the lock is released.
3. Releasing the Lock: Once the thread finishes executing the critical section, it releases the lock

Example:

class Counter {
private int count = 0;

public void increment() {


synchronized (this) {
count++;
}
}

public int getCount() {


return count;
}
}

In this example, the increment() method synchronizes only the critical section of code that
modifies the count variable. This allows other parts of the method to execute concurrently without
blocking.

Advantages of Synchronized Statements:

 Granular Control: You can synchronize specific parts of your code, reducing the impact on
performance.
 Flexibility: You can use different objects as locks to synchronize different sections of code.

Considerations:

 Deadlocks: Be careful to avoid deadlocks, especially when using multiple locks.


 Performance Impact: Excessive synchronization can degrade performance.
 Alternative Approaches: Consider using higher-level concurrency utilities like
java.util.concurrent for more complex synchronization scenarios.

Best Practices:

 Use synchronized statements only when necessary.


 Keep synchronized blocks as short as possible.
 Use appropriate objects as locks.
 Test your code thoroughly to ensure correct synchronization.

Inter-Thread Communication
Inter-thread communication refers to the mechanisms by which threads can interact and synchronize with
each other. It's essential for coordinating the activities of multiple threads and ensuring proper data sharing
and synchronization.

Key Techniques:

1. wait() and notify():


o wait(): Pauses the current thread and releases the lock on the object.
o notify(): Wakes up a single waiting thread.
o notifyAll(): Wakes up all waiting threads.

public class ProducerConsumer {


private int value;
private boolean produced = false;

public synchronized void produce() {


while (produced) {
try {
wait();
} catch (InterruptedException e) {
// Handle exception
}
}
// Produce value
produced = true;
notify();
}

public synchronized void consume() {


while (!produced) {
try {
wait();
} catch (InterruptedException e) {
// Handle exception
}
}
// Consume value
produced = false;
notify();
}
}

2. join():
o Waits for a thread to finish execution before proceeding.

Thread t = new Thread(new MyRunnable());


t.start();
t.join(); // Waits for t to finish

3. volatile Keyword:
o Ensures that changes to a variable are visible to all threads.
o Useful for simple shared variables that don't require complex synchronization.
Important Considerations:

 Synchronization: Always use synchronization mechanisms to protect shared resources and


prevent race conditions.
 Deadlocks: Be careful to avoid deadlocks by acquiring locks in a specific order and using
timeouts.
 Liveness: Ensure that threads can make progress and avoid starvation.
 Performance: Excessive synchronization can impact performance, so use it judiciously

Deadlock

A deadlock occurs when two or more threads are blocked indefinitely, each waiting for a resource held by
another thread. This creates a circular dependency, preventing any thread from making progress.

Causes of Deadlock:

1. Mutual Exclusion: Multiple threads need to access shared resources exclusively.


2. Hold and Wait: A thread holds a resource and waits for another resource.
3. No Preemption: Resources cannot be forcibly taken away from a thread.
4. Circular Wait: A circular chain of threads exists, where each thread is waiting for a resource held
by the next thread in the chain.

Preventing Deadlocks:

1. Careful Resource Allocation:


o Acquire locks in a specific order to avoid circular wait.
o Release locks as soon as possible.
2. Timeout Mechanisms:
o Set timeouts for acquiring locks to prevent indefinite waiting.
o If a lock cannot be acquired within the timeout, the thread can release other held locks and
retry.
3. Deadlock Detection and Recovery:
o Monitor the system for deadlock conditions.
o Use algorithms to detect and break deadlocks by preempting resources or terminating
threads.

Example:

class DeadlockExample {
public static void main(String[] args) {
Object lock1 = new Object();
Object lock2 = new Object();

Thread t1 = new Thread(()


-> {
synchronized (lock1) {
System.out.println("Thread 1: Acquired lock1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock2) {
System.out.println("Thread 1: Acquired lock2");
}
}
});

Thread
t2 = new Thread(() -> {
synchronized (lock2) {
System.out.println("Thread 2: Acquired lock2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock1) {
System.out.println("Thread 2: Acquired lock1");

}
}
});

t1.start();
t2.start();
}
}

In this example, both threads try to acquire locks on lock1 and lock2 in different orders, leading to a
deadlock.

To avoid deadlocks in this scenario, you can acquire locks in a consistent order across all threads
or use more advanced synchronization mechanisms like semaphores or condition variables.

I/O Streams

In Java, I/O streams provide a mechanism for reading and writing data to various sources and destinations.
They are categorized into two main types:

1. Byte Streams:

 Deal with raw bytes.


 Used for binary data like images, audio, and executable files.

Common Classes:

 InputStream: Abstract class for reading byte streams.


 OutputStream: Abstract class for writing byte streams.
 FileInputStream: Reads bytes from a file.
 FileOutputStream: Writes bytes to a file.
 BufferedInputStream: Reads bytes from a buffer.
 BufferedOutputStream: Writes bytes to a buffer.

2. Character Streams:

 Deal with characters.


 Used for text-based data like plain text files, HTML, and XML.
Common Classes:

 Reader: Abstract class for reading character streams.


 Writer: Abstract class for writing character streams.
 FileReader: Reads characters from a file.
 FileWriter: Writes characters to a file.
 BufferedReader: Reads characters from a buffer.
 BufferedWriter: Writes characters to a buffer.
 InputStreamReader: Converts byte streams to character streams.
 OutputStreamWriter: Converts character streams to byte streams.

Reading Console Input:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ConsoleInput {


public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter your name: ");


String name = reader.readLine();
System.out.println("Hello,
" + name + "!");
}
}

Writing Console Output:

System.out.println("Hello, World!");
System.out.print("This is a line of text.");

File Handling:

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileHandling {


public static void main(String[] args) throws IOException {
File
file = new File("output.txt");
FileWriter writer = new FileWriter(file);
writer.write("This is a line of text.");
writer.close();
}

Concepts of Streams

In Java, streams are a sequence of data that flows from a source to a destination. They provide a
convenient way to read and write data.
Key Concepts:

1. Byte Streams:
o Deal with raw bytes.
o Used for binary data like images, audio, and executable files.
o Common classes: FileInputStream, FileOutputStream, BufferedInputStream,
BufferedOutputStream.
2. Character Streams:
o Deal with characters.
o Used for text-based data like plain text files, HTML, and XML.
o Common classes: FileReader, FileWriter, BufferedReader, BufferedWriter,
InputStreamReader, OutputStreamWriter.
3. Buffered Streams:
o Improve performance by reading or writing data in large chunks.
o Reduce the number of system calls.
4. Piped Streams:
o Allow communication between threads using pipes.
o One thread writes to the pipe, and another thread reads from it.
5. Filter Streams:
o Modify or filter the data being read or written.
o Examples: DataInputStream, DataOutputStream, PrintWriter, BufferedReader.

Common Operations:

 Reading:
o Read a single byte or character.
o Read a specific number of bytes or characters.
o Read a line of text.
 Writing:
o Write a single byte or character.
o Write a specific number of bytes or characters.
o Write a line of text.

Example: Reading and Writing to a File

import java.io.*;

public class FileIOExample {


public static void main(String[] args) throws IOException {
// Write to a file
FileWriter writer = new FileWriter("output.txt");
writer.write("Hello, world!");
writer.close();

// Read from a file


FileReader reader = new FileReader("output.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);

}
bufferedReader.close();
reader.close();
}
}

Stream Classes in Java

In Java, streams are a sequence of data that flows from a source to a destination. They are used for
input and output operations. Java provides two types of streams:

Byte Streams

Byte streams are used to handle raw binary data.

Key Classes:

 InputStream: Abstract class for reading byte streams.


o FileInputStream: Reads bytes from a file.
o BufferedInputStream: Reads bytes from a buffer for efficient reading.
o ByteArrayInputStream: Reads bytes from a byte array.
o PipedInputStream: Reads bytes from a pipe.

 OutputStream: Abstract class for writing byte streams.


o FileOutputStream: Writes bytes to a file.
o BufferedOutputStream: Writes bytes to a buffer for efficient writing.
o ByteArrayOutputStream: Writes bytes to a byte array.
o PipedOutputStream: Writes bytes to a pipe.

Character Streams

Character streams are used to handle textual data.

Key Classes:

 Reader: Abstract class for reading character streams.


o FileReader: Reads characters from a file.
o BufferedReader: Reads characters from a buffer for efficient reading.
o StringReader: Reads characters from a string.
o PipedReader: Reads characters from a pipe.

 Writer: Abstract class for writing character streams.


o FileWriter: Writes characters to a file.
o BufferedWriter: Writes characters to a buffer for efficient writing.
o StringWriter: Writes characters to a string.
o PipedWriter: Writes characters to a pipe.

Common Operations:

 Reading:
o read(): Reads a single character or byte.
o read(char[] buffer): Reads a block of characters or bytes into a buffer.
o readLine(): Reads a line of text.
 Writing:
o write(int c): Writes a single character or byte.
o write(char[] cbuf): Writes an array of characters or bytes.
o write(String str): Writes a string.

Example: Reading and Writing to a File

import java.io.*;

public class FileIOExample {


public static void main(String[] args) throws IOException {
// Write to a file
FileWriter writer = new FileWriter("output.txt");
writer.write("Hello, world!");
writer.close();

// Read from a file


FileReader reader = new FileReader("output.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);

}
bufferedReader.close();

reader.close();
}
}

Byte and Character Streams

In Java, I/O operations are primarily handled through streams. These streams are categorized into two
types: byte streams and character streams.

Byte Streams

Byte streams deal with raw bytes of data. They are suitable for handling binary data like images, audio,
and executable files.

Key classes:

 InputStream: Abstract class for reading byte streams.


o FileInputStream: Reads bytes from a file.
o BufferedInputStream: Reads bytes from a buffer for efficient reading.
o ByteArrayInputStream: Reads bytes from a byte array.
o PipedInputStream: Reads bytes from a pipe.

 OutputStream: Abstract class for writing byte streams.


o FileOutputStream: Writes bytes to a file.
o BufferedOutputStream: Writes bytes to a buffer for efficient writing.
o ByteArrayOutputStream: Writes bytes to a byte array.
o PipedOutputStream: Writes bytes to a pipe.
Character Streams

Character streams deal with text data. They are suitable for handling text files, HTML, and other text-
based formats.

Key classes:

 Reader: Abstract class for reading character streams.


o FileReader: Reads characters from a file.
o BufferedReader: Reads characters from a buffer for efficient reading.
o StringReader: Reads characters from a string.
o PipedReader: Reads characters from a pipe.

 Writer: Abstract class for writing character streams.


o FileWriter: Writes characters to a file.
o BufferedWriter: Writes characters to a buffer for efficient writing.
o StringWriter: Writes characters to a string.
o PipedWriter: Writes characters to a pipe.

Key Differences:

Feature Byte Stream Character Stream


Data
Byte Character
Unit
Usage Binary data Textual data
InputStream,
Classes Reader, Writer
OutputStream

Example: Reading and Writing Text to a File

import java.io.*;

public class FileIOExample {


public static void main(String[] args) throws IOException {
// Write to a file
FileWriter writer = new FileWriter("output.txt");
writer.write("Hello, world!");
writer.close();

// Read from a file


FileReader reader = new FileReader("output.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);

}
bufferedReader.close();

reader.close();
}
}

Important Considerations:

 Close Streams: Always close streams after use to release system resources.
 Error Handling: Use try-catch blocks to handle potential exceptions like IOException.
 Buffering: Use buffered streams to improve performance by reducing the number of system calls.
 Encoding: Specify the character encoding when working with character streams.

By understanding the differences between byte and character streams and using the appropriate classes,
you can effectively handle various I/O operations in Java.

Reading Console Input

Using Scanner class:

import java.util.Scanner;

public class ReadConsoleInput {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter your name: ");


String name = scanner.nextLine();

System.out.println("Hello, " + name


+ "!");
}
}

Explanation:

1. Import Scanner: Import the Scanner class from the java.util package.
2. Create a Scanner object: Create a Scanner object to read input from the standard input stream
(System.in).
3. Read input: Use the nextLine() method to read a complete line of input from the console.
4. Process the input: Process the input as needed. In this example, we simply print a greeting
message.

Using Buffered Reader:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class
ReadConsoleInput {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter your name: ");


String name = reader.readLine();

System.out.println("Hello,
" + name + "!");
}
}

Explanation:

1. Import classes: Import the necessary classes for reading console input.
2. Create a BufferedReader object: Create a BufferedReader object to read input from the standard
input stream.
3. Read input: Use the readLine() method to read a complete line of input.
4. Process the input: Process the input as needed.

Writing Console Output:

Using System.out.println():

public class WriteConsoleOutput {


public static void main(String[] args) {
System.out.println("Hello, World!");
System.out.println("This is a new line.");
}
}

Explanation:

 System.out.println() prints the specified text to the console and adds a newline character.

Using System.out.print():

public class WriteConsoleOutput {


public static void main(String[] args) {
System.out.print("Hello, ");
System.out.print("World!");
}
}

 System.out.print() prints the specified text to the console without adding a newline character.

1 MARK:

1. What is the primary difference between extending Thread and implementing Runnable?

a) One allows multiple inheritance, the other doesn't.

b) One is faster, the other is slower.

c) One is for background tasks, the other is for foreground tasks.

d) Both are equivalent in functionality.

2. What is the purpose of the synchronized keyword in Java?

a) To make a method execute faster.

b) To ensure thread safety for shared resources.

c) To create multiple threads.

d) To pause the execution of a thread.

3. What is a deadlock?

a) A state where two or more threads are blocked, waiting for each other.

b) A condition where a thread is waiting for itself.

c) A state where a thread is waiting for an infinite loop.

d) A condition where a thread is waiting for a resource that is never released.

4. Which of the following is a byte stream class?

a) FileReader

b) FileWriter

c) FileInputStream

d) BufferedReader
5. What is the purpose of a buffer in I/O operations?

a) To reduce the number of system calls.

b) To increase the size of the file.

c) To encrypt the data.

d) To compress the data.

6. Which method is used to read a line of text from a BufferedReader?

a) read()

b) readLine()

c) next()

d) get()

7. What is a thread?

a) A lightweight process

b) A heavy-weight process

c) A function

d) A variable

8. Which interface is implemented to create a thread?

a) Runnable

b) Thread

c) Process

d) Task

9. What is the purpose of the synchronized keyword?

a) To create a new thread

b) To stop a running thread

c) To control access to shared resources

d) To measure the execution time of a thread


10. What is deadlock?

a) A state where two or more threads are blocked, waiting for each other

b) A state where a thread is waiting for an infinite loop

c) A state where a thread is terminated abruptly

d) A state where a thread is suspended indefinitely

11. What is a stream in Java?

a) A sequence of bytes

b) A sequence of characters

c) A sequence of objects

d) A sequence of data

12. Which class is used to read characters from a character-based input stream?

a) InputStreamReader

b) BufferedReader

c) FileReader

d) DataInputStream

13. Which class is used to write characters to a character-based output stream?

a) PrintWriter

b) FileWriter

c) BufferedWriter

d) DataOutputStream

14. Which class is used to read and write primitive data types to a file?

a) DataInputStream

b) DataOutputStream

c) FileInputStream

d) FileOutputStream
5-MARK & 10 MARK

1. Explain the importance of synchronization to prevent race conditions.


2. Describe synchronized methods and synchronized blocks.
3. Discuss the use of the volatile keyword.
4. Explain inter-thread communication using wait(), notify(), and notifyAll() methods.
5. Discuss the concept of deadlock and how to avoid it.

6. Explain the difference between byte streams and character streams. Provide examples of their
usage.
7. Discuss the concept of buffering in I/O operations. How does it improve performance?
8. Write a Java program to read a file line by line and print each line to the console.
9. Explain the concept of file handling in Java. Discuss the use of File, FileReader, and FileWriter
classes.
10. How can you read user input from the console in Java? Provide a code example.

UNIT-IV:

AWT Class Hierarchy:

The Abstract Window Toolkit (AWT) is a platform-independent API for creating graphical user
interfaces (GUIs) in Java. It provides a hierarchy of classes to build various UI components.

Here's a simplified view of the AWT class hierarchy:

java.lang.Object
|- java.awt.Component
|- java.awt.Container
|- java.awt.Panel
|- java.awt.Window
|- java.awt.Frame
|- java.awt.Dialog

Key Components and Their Roles:


1. Component:
o The base class for all AWT components.
o Defines common properties like size, location, visibility, and event handling.
2. Container:
o A component that can hold other components.
o Used to organize and group UI elements.
o Examples: Panel, Window, Frame, and Dialog.
3. Panel:
o A lightweight container used to group components.
o Often used to create custom layouts and organize complex UI elements.
4. Window:
o A top-level container with a title bar and borders.
o Can be either a frame or a dialog.
5. Frame:
o A standalone window with a title bar, menu bar, and borders.
o Used to create independent applications.
6. Dialog:
o A modal or modeless window that depends on a parent frame.
o Used for displaying messages, asking for user input, or providing additional information.

Additional Components:

 Button: A clickable button to trigger actions.


 Label: A display area for text or images.
 TextField: A single-line text input field.
 TextArea: A multi-line text input area.
 Checkbox: A toggle button to select or deselect an option.
 CheckboxGroup: A group of checkboxes where only one can be selected at a time.
 Choice: A drop-down list of options.
 List: A scrollable list of items.
 Menu: A hierarchical menu structure.
 MenuItem: An individual item in a menu.
 PopupMenu: A context menu that appears when the user right-clicks.
 Scrollbar: A control for scrolling through content.

User Interface Components:

Java provides a rich set of tools and libraries for creating user interfaces. Two primary toolkits are
commonly used:

1. AWT (Abstract Window Toolkit):

 Basic Components:
o Label: Displays text or images.
o Button: Triggers actions when clicked.
o TextField: Allows single-line text input.
o TextArea: Allows multi-line text input.
o Checkbox: Selects or deselects an option.
o CheckboxGroup: Groups checkboxes for exclusive selection.
o Choice: Presents a dropdown list of options.
o List: Displays a scrollable list of items.
o Scrollbar: Allows scrolling through content.
o Menu: Creates hierarchical menus.
oPopupMenu: Displays a context menu on right-click.
oPanel: Organizes and groups components.
oFrame: Creates a top-level window.
oDialog: Creates a modal or modeless dialog box.
 Layout Managers:
o FlowLayout: Arranges components in a row or column.
o BorderLayout: Divides the container into five regions: North, South, East, West, and
Center.
o GridLayout: Arranges components in a grid.
o CardLayout: Displays one component at a time.
o GridBagLayout: Provides flexible layout with precise control over component placement.

2. Swing:

 Basic Components:
o JButton: Similar to AWT Button, but more customizable.
o JLabel: Similar to AWT Label, but more flexible.
o JTextField: Similar to AWT TextField, but with additional features.
o JTextArea: Similar to AWT TextArea, but with additional features.
o JCheckBox: Similar to AWT Checkbox, but more customizable.
o JRadioButton: Similar to AWT CheckboxGroup, but for radio buttons.
o JComboBox: Similar to AWT Choice, but more flexible.
o JList: Similar to AWT List, but more customizable.
o JScrollPane: Provides scrollable views of large components.
o JMenu: Creates hierarchical menus.
o JMenuItem: An individual item in a menu.
o JPanel: Organizes and groups components.
o JFrame: Creates a top-level window.
o JDialog: Creates a modal or modeless dialog box.
 Advanced Components:
o JTable: Displays tabular data.
o JTree: Displays hierarchical data.
o JProgressBar: Displays progress.
o JSlider: Allows users to select a value from a range.
o JSplitPane: Divides a container into two scrollable panes.
o JTabbedPane: Displays multiple components in tabs.

Choosing the Right Toolkit:

 AWT: Simpler and lightweight, but less flexible and platform-dependent.


 Swing: More powerful, flexible, and platform-independent, but more complex.

Key Considerations:

 Layout Managers: Use them to organize components effectively within a container.


 Event Handling: Implement event listeners to respond to user actions.
 User Experience: Design intuitive and visually appealing interfaces.
 Accessibility: Ensure your UI is accessible to users with disabilities.
 Testing: Thoroughly test your UI to identify and fix issues.

Labels:
In Java, labels are used to identify specific points within a code block, primarily to control the flow of
nested loops using break and continue statements.

Syntax:

label: statement;

Buttons:

Buttons are essential UI components in Java that trigger specific actions when clicked. They are used to
initiate various operations, such as submitting forms, opening dialogs, or executing commands.

Two Primary Toolkits for Buttons:

1. AWT (Abstract Window Toolkit):


o Button Class:
 Creates a simple button with a label.
 Used to trigger actions when clicked.
2. Swing:
o JButton Class:
 More flexible and customizable than AWT buttons.
 Supports various styles, icons, and tooltips.

Example (Swing):

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ButtonExample {


public static void main(String[] args)
{
JFrame frame = new JFrame("Button Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);

JButton
button = new JButton("Click Me");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent
e) {
System.out.println("Button clicked!");
}
});

frame.add(button);
frame.setVisible(true);

}
}
Text Components:

Text components are essential UI elements that allow users to input and display text. Java provides
various text components, primarily through the AWT and Swing libraries.

AWT Text Components:

 TextField: A single-line text input field.


 TextArea: A multi-line text input area.

Swing Text Components:

 JTextField: A more flexible version of the AWT TextField.


 JTextArea: A more flexible version of the AWT TextArea.
 JPasswordField: A specialized text field that masks input characters.
 JFormattedTextField: A text field with formatting capabilities.
 JTextPane: A text pane that supports rich text formatting.

Key Concepts:

 Text Input and Output: Text components can be used to both display text to the user and receive
input from the user.
 Event Handling: Event listeners can be attached to text components to handle user input events,
such as keystrokes and mouse clicks.
 Formatting: Text components can be formatted using fonts, colors, and styles.
 Validation: Input can be validated to ensure it meets specific criteria.

Check Boxes

Check boxes are UI elements that allow users to select or deselect an option. They are commonly used to
represent binary choices or to enable multiple selections.

AWT Check Box:

 Checkbox Class: Creates a single check box.

Swing Check Box:

 JCheckBox Class: Provides more flexibility and customization options.

Check Box Groups:

Check box groups allow you to group multiple check boxes together, often to restrict the selection to a
specific number of options.

AWT Check Box Group:

 CheckboxGroup Class: Groups check boxes together, allowing only one to be selected at a time.

Swing Check Box Group:

 ButtonGroup Class: Groups check boxes together, allowing multiple selections.

Example (Swing):
Java
import javax.swing.*;

public class CheckBoxGroupExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Check Box Group Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);

ButtonGroup group = new ButtonGroup();

JCheckBox checkBox1 = new JCheckBox("Option 1");


JCheckBox checkBox2 = new JCheckBox("Option 2");
JCheckBox checkBox3 = new JCheckBox("Option
3");

group.add(checkBox1);
group.add(checkBox2);
group.add(checkBox3);

frame.add(checkBox1);
frame.add(checkBox2);
frame.add(checkBox3);

frame.setVisible(true);
}
}

Choice:

A Choice component presents a drop-down list of options. The user can select one option from the list.

List Box:

A List component displays a scrollable list of items. The user can select one or multiple items from
the list.

Example (Swing):

import javax.swing.*;

public class ChoiceListExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Choice and List Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);

Choice choice = new Choice();


choice.add("Option 1");
choice.add("Option 2");
choice.add("Option 3");

JList<String> list = new JList<>(new String[]{"Item 1", "Item 2", "Item 3"});

frame.add(choice, BorderLayout.NORTH);
frame.add(new JScrollPane(list), BorderLayout.CENTER);

frame.setVisible(true);
}
}

Panels and Scroll Pane:

Panels: Panels are container components that organize other components. They are used to group related
components and to create complex layouts.

Scroll Pane: A JScrollPane provides scrollable views of large components. It is often used with
JTextArea, JList, and other components that may exceed the visible area.

Menu and Scroll Bar:

Menu: A Menu component creates a hierarchical menu structure. It can be a menu bar or a popup menu.

Scroll Bar: A Scrollbar component allows users to scroll through content that exceeds the visible area.

Frame, Color, Fonts, and Layout Managers:

Frame: A Frame is a top-level window with a title bar, menu bar, and borders. It is used to create
standalone applications.

Color: You can set the color of components using the Color class.

Fonts: You can customize the font of text using the Font class.

Layout Managers: Layout managers are used to organize components within a container. Java provides
several layout managers:

 FlowLayout: Arranges components in a row or column.


 BorderLayout: Divides the container into five regions: North, South, East, West, and Center.
 GridLayout: Arranges components in a grid of rows and columns.
 CardLayout: Displays one component at a time, like cards in a deck.
 GridBagLayout: Provides flexible layout with precise control over component placement.

Event Handling:

Event handling is a fundamental concept in Java programming that allows applications to respond
to user interactions and system events. It involves three main components:

Event Sources :

In Java, event sources are objects that can generate events. These events can be triggered by user
interactions, system events, or other actions. Once an event is generated, it's sent to registered listeners for
processing.
Common Event Sources:

1. UI Components:
o Buttons
o Text fields
o Text areas
o Checkboxes
o Radio buttons
o Combo boxes
o Lists
o Menus
o Scrollbars
2. Window Events:
o Window opening
o Window closing
o Window resizing
o Window activation/deactivation
3. Mouse Events:
o Mouse clicks
o Mouse drags
o Mouse movements
4. Keyboard Events:
o Key presses
o Key releases
5. Timer Events:
o Time intervals

Example: A Button Click Event

import javax.swing.*;
import java.awt.event.*;

public class ButtonClickExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Button Click Example");
JButton button = new JButton("Click Me");

button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent
e) {
System.out.println("Button clicked!");
}
});

frame.add(button);
frame.setSize(300, 200);
frame.setVisible(true);
}
}

Event Listeners:

Event listeners are objects that implement specific interfaces to listen for and handle events generated by
event sources. When an event occurs, the event source notifies the registered listeners, and their respective
methods are invoked.

Common Event Listener Interfaces:

1. ActionListener:
o Listens for action events, such as button clicks.
o actionPerformed() method is invoked when the event occurs.
2. MouseListener:
o Listens for mouse events, such as clicks, presses, releases, and movements.
o Methods like mouseClicked(), mousePressed(), mouseReleased(), mouseEntered(), and
mouseExited() are invoked.
3. MouseMotionListener:
o Listens for mouse motion events, such as dragging and moving.
o Methods like mouseDragged() and mouseMoved() are invoked.
4. KeyListener:
o Listens for keyboard events, such as key presses and releases.
o Methods like keyPressed(), keyReleased(), and keyTyped() are invoked.
5. ItemListener:
o Listens for item events, such as selecting an item from a list or a choice.
o itemStateChanged() method is invoked when the item's state changes.

Event Delegation Model (EDM)

The Event Delegation Model (EDM) is a design pattern used in Java to handle events efficiently. It
involves the following steps:

1. Event Source: An object generates an event, such as a button click or a mouse movement.
2. Event Object: The event source creates an event object that encapsulates information about the
event, like the type of event and the source object.
3. Event Listener: An object that implements a specific listener interface, such as ActionListener,
MouseListener, or KeyListener.
4. Event Registration: The event listener is registered with the event source using methods like
addActionListener(), addMouseListener(), etc.
5. Event Dispatching: When the event occurs, the event source dispatches the event object to all
registered listeners.
6. Event Handling: Each registered listener receives the event object and processes it according to
its implementation.
Key Benefits of EDM:

 Decoupling: It separates the event source from the event handler, promoting loose coupling and
modularity.
 Flexibility: It allows multiple listeners to be registered to a single event source, enabling complex
event handling scenarios.
 Reusability: Event listeners can be reused in different parts of the application.
 Efficiency: The event source handles the dispatching of events, reducing the overhead on
individual components.

Handling Mouse and Keyboard Events :

Java provides a robust mechanism for handling mouse and keyboard events. By using appropriate
event listeners, you can create interactive applications that respond to user input.

Mouse Events:

To handle mouse events, you can use the MouseListener and MouseMotionListener interfaces.

MouseListener:

 mouseClicked(MouseEvent e): Invoked when the mouse button is clicked and released.
 mousePressed(MouseEvent e): Invoked when the mouse button is pressed.
 mouseReleased(MouseEvent e): Invoked when the mouse button is released.
 mouseEntered(MouseEvent e): Invoked when the mouse enters a component's bounds.
 mouseExited(MouseEvent e): Invoked when the mouse exits a component's bounds.

MouseMotionListener:

 mouseDragged(MouseEvent e): Invoked when the mouse is dragged while a button is pressed.
 mouseMoved(MouseEvent e): Invoked when the mouse is moved without a button pressed.

Example (Swing):

import javax.swing.*;
import java.awt.event.*;

public class MouseEventExample extends JFrame {


public MouseEventExample() {
setTitle("Mouse Event Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel panel = new JPanel();


panel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse
clicked at: " + e.getX()
+ ", " + e.getY());
}
});

add(panel);
setVisible(true);
}

public static void main(String[] args) {


new MouseEventExample();
}
}

Keyboard Events:

To handle keyboard events, you can use the KeyListener interface.

KeyListener:

 keyTyped(KeyEvent e): Invoked when a key is typed.


 ** keyPressed(KeyEvent e):** Invoked when a key is pressed.
 keyReleased(KeyEvent e): Invoked when a key is released.

Example (Swing):

import javax.swing.*;
import java.awt.event.*;

public class KeyEventExample extends JFrame {


public KeyEventExample() {
setTitle("Keyboard Event Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JTextField textField = new JTextField();


textField.addKeyListener(new KeyAdapter()
{
@Override
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();

System.out.println("Key typed: " + c);


}
});

add(textField);
setVisible(true);
}

public static void main(String[] args) {


new KeyEventExample();
}
}

Adapter Classes:

Adapter classes are a design pattern used to adapt an existing interface to a new one. In the context
of Java event handling, adapter classes provide a convenient way to implement only the necessary
methods of an interface.

For example, if you want to handle only a few specific mouse events, you can create an adapter class that
extends the MouseAdapter class and override only the required methods. This avoids the need to
implement all the methods of the MouseListener interface, which can be tedious and unnecessary in many
cases.

Example:

import java.awt.event.*;

public class MouseClickAdapter extends MouseAdapter {


@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked at: " + e.getX() + ", " + e.getY());
}
}

In this example, the MouseClickAdapter class extends MouseAdapter and overrides only the
mouseClicked() method. This allows you to handle mouse clicks without having to implement the other
methods of the MouseListener interface.

Benefits of Using Adapter Classes:

 Reduced Boilerplate Code: You only need to implement the methods you're interested in.
 Improved Readability: The code becomes more focused and easier to understand.
 Increased Flexibility: You can create custom adapter classes for specific use cases.

Inner Classes:

Inner classes are classes defined within another class. They provide a way to encapsulate code and data
within a larger class, promoting modularity and code organization.

Java supports four types of inner classes:

1. Static Nested Classes:


o Declared with the static keyword.
o Can access static members of the outer class but not instance members.
o Can be instantiated without creating an instance of the outer class.
2. Instance Inner Classes:
o Declared without the static keyword.
o Can access both static and instance members of the outer class.
o Can be instantiated only after creating an instance of the outer class.
3. Local Inner Classes:
o Declared within a method or block of code.
o Can access local variables of the enclosing method or block.
o Can only be instantiated within the enclosing method or block.
4. Anonymous Inner Classes:
o A special type of inner class that is declared and instantiated in a single statement.
o Often used to create event listeners or implement interfaces concisely.

Example:

public class OuterClass {


private int outerVariable = 10;

public class InnerClass {


public void innerMethod() {
System.out.println("Inner class method: " + outerVariable);
}
}

public void outerMethod() {


InnerClass innerObject = new InnerClass();
innerObject.innerMethod();
}
}

1 MARK:

1) Which of the following is a top-level container in AWT?

a) Panel

b) Label

c) Frame

d) Button
2) Which layout manager positions components in a flow-like manner, wrapping to the next line if
necessary?

a) Border Layout

b) Grid Layout

c) Card Layout

d) Flow Layout

3) Which event listener is used to handle mouse movement events?

a) Mouse Listener

b) Mouse Motion Listener

c) Key Listener

d) Action Listener

4) What is the purpose of an inner class in Java?

a) To define a class within another class

b) To create standalone classes

c) To inherit from multiple classes

d) To override static methods

5) Which AWT component is used to display a scrollable list of items?

a) Choice

b) List

c) Panel

d) Scroll Pane

6) What is an event source in Java?

a) A class that generates events

b) A method that handles events

c) An object that triggers events

d) A listener that waits for events

7) Which event listener interface is used to handle mouse clicks?

a) Action Listener
b) Mouse Listener

c) Key Listener

d) Item Listener

8) What is the purpose of an adapter class in Java event handling?

a) To create new event types

b) To handle all events of a specific type

c) To implement only the necessary methods of an event listener interface

d) To dispatch events to the appropriate listeners

9) Which event listener interface is used to handle keyboard events?

a) Action Listener

b) Mouse Listener

c) Key Listener

d) Item Listener

10) What is the Event Delegation Model (EDM)?

a) A design pattern for handling events in Java

b) A specific type of event listener

c) A method for creating custom events

d) A way to prioritize event handling

11) What is an inner class in Java?

a) A class defined within another class

b) A class that extends another class

c) A class that implements multiple interfaces

d) A class that is not part of any package

12) Which type of inner class can access both static and instance members of the outer class?

a) Static nested class


b) Instance inner class

c) Local inner class

d) Anonymous inner class

13) What is an anonymous inner class in Java?

a) A class without a name

b) A class that is declared and instantiated in a single statement

c) A class that is inherited from another class

d) A class that is defined outside of any other class

10-MARK & 5-MARK:

1. Explain the concept of layout managers in AWT.

2. Discuss the five primary layout managers and their use cases.

3. Describe the following AWT components and their purpose:

4. Explain the Event Delegation Model (EDM) in Java.

5. Describe the following event listener interfaces and their corresponding events:

6. Explain the role of the Frame class in AWT.

7. Describe how to set the title, size, and visibility of a Frame.

8. Write a Java program to create a Frame with a label, a text field, and a button.

9. How do you set the foreground and background colors of a component in AWT?

10. Explain the concept of font metrics in AWT.

11. Write a Java program to create a Frame with a label and a button. The label should display a message
in a specific font and color.

12. What is an inner class in Java?

13. Explain the different types of inner classes.

14. How can inner classes be used to handle events in AWT?

15. Write a Java program to create a Frame with a button. Use an inner class to handle the button click
event and display a message in a dialog box.
UNIT-V:

Swing: A Powerful GUI Toolkit:

Swing is a powerful and flexible GUI toolkit in Java that provides a rich set of components for creating
user interfaces. It offers a more advanced and customizable approach to building GUIs compared to AWT.

Key Features of Swing:

 Platform Independence: Swing components can be rendered consistently across different


operating systems.
 Customizability: You can customize the appearance and behavior of Swing components using
various properties and methods.
 Pluggable Look and Feel: Swing supports different look and feels, allowing you to mimic the
appearance of native platforms or create custom looks.
 Model-View-Controller (MVC) Architecture: Swing components follow the MVC pattern,
separating concerns and promoting modularity.
 Event Handling: Swing provides a robust event handling mechanism to respond to user
interactions.

Core Swing Components:

 Top-Level Containers:
o JFrame: A standalone window with a title bar, menu bar, and borders.
o JDialog: A modal or modeless dialog box.
o JWindow: A lightweight window without a title bar or borders.
 Containers:
o JPanel: A lightweight container for grouping components.
o JScrollPane: Provides scrollable views of large components.
 Basic Components:
o JButton: A clickable button.
o JToggleButton: A button that can be toggled on and off.
o JCheckBox: A check box for selecting or deselecting options.
o JRadioButton: A radio button for selecting one option from a group.
o JLabel: A label for displaying text or images.
o JTextField: A single-line text input field.
o JTextArea: A multi-line text input area.
o JList: A list of items that can be selected.
o JComboBox: A drop-down list of options.

Example: A Simple Swing Application

import javax.swing.*;

public class SwingExample {


public static void main(String[] args) {
JFrame frame = new JFrame("My Swing Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);

JLabel label = new JLabel("Hello, Swing!");


JButton button = new JButton("Click me");

frame.add(label);
frame.add(button);

frame.setVisible(true);

}
}

This code creates a simple JFrame with a label and a button. The JFrame is the top-level container,
and the JLabel and JButton are added to it.

Key Advantages of Swing:


 Flexibility: Swing offers a wide range of components and customization options.
 Performance: Swing components are lightweight and efficient.
 Cross-Platform Compatibility: Swing applications can run on different operating systems with a
consistent look and feel.

Hierarchy of swing components:

Swing components are organized in a hierarchical structure, with JComponent as the base class for
most components. This hierarchical structure allows for efficient event handling, layout management, and
customization.

Key Components and Their Hierarchy:

1. Top-Level Containers:
o JFrame: A standalone window with a title bar, menu bar, and borders.
o JDialog: A modal or modeless dialog box.
o JWindow: A lightweight window without a title bar or borders.
2. Containers:
o JPanel: A lightweight container for grouping components.
o JScrollPane: Provides scrollable views of large components.
o JSplitPane: Divides a container into two scrollable panes.
o JTabbedPane: Displays multiple components in tabs.
o JLayeredPane: Manages the layering of components.
o JInternalFrame: A window-like component that can be docked, floated, or maximized
within a container.
3. Basic Components:
o JButton: A clickable button.
o JToggleButton: A button that can be toggled on and off.
o JCheckBox: A check box for selecting or deselecting options.
o JRadioButton: A radio button for selecting one option from a group.
o JLabel: A label for displaying text or images.
o JTextField: A single-line text input field.
o JTextArea: A multi-line text input area.
o JList: A list of items that can be selected.
o JComboBox: A drop-down list of options.
o JProgressBar: A progress bar.
o JSlider: A slider for selecting a value from a range.
o JSpinner: A spinner for selecting a value from a set of values.
o JColorChooser: A dialog for selecting a color.
o JFileChooser: A dialog for selecting files.
o JMenu: A menu item in a menu bar.
o JMenuItem: An individual item in a menu.
o JCheckBoxMenuItem: A checkable menu item.
o JRadioButtonMenuItem: A radio button menu item.

Top-Level Containers:

Top-level containers are the foundation of any Swing application. They provide the main window or
frame where other components are placed. Swing provides three primary top-level containers:

1. JFrame:
o A standalone window with a title bar, menu bar, and borders.
o Commonly used for creating independent applications.
o Can be resized, moved, and closed by the user.
2. JDialog:
o A modal or modeless dialog box.
o Used for displaying messages, asking for user input, or providing additional information.
o Can be modal (blocks interaction with the parent window) or modeless (allows interaction
with the parent window).
3. JWindow:
o A lightweight window without a title bar or borders.
o Often used for simple pop-up windows or custom window decorations.

JFrame: The Main Window

A JFrame is a top-level container in Swing, representing a standalone window with a title bar, menu bar,
and borders. It's the most commonly used container for creating desktop applications.

Key Features:

 Title Bar: Displays the window's title.


 Menu Bar: Can hold menus and menu items.
 Border: Defines the window's boundary.
 Resizable: Can be resized by the user.
 Closable: Can be closed by the user.
 Iconifiable: Can be minimized to the taskbar.

Creating a JFrame:

import javax.swing.*;

public class JFrameExample {


public static void main(String[] args) {
JFrame frame = new JFrame("My First JFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Set the default close operation
frame.setSize(300, 200); // Set the size of the frame
frame.setVisible(true); // Make the frame visible
}
}

Key Methods:

 setDefaultCloseOperation(int operation): Sets the default close operation.


 setSize(int width, int height): Sets the size of the frame.
 setVisible(boolean visible): Makes the frame visible or invisible.
 setTitle(String title): Sets the title of the frame.
 add(Component component): Adds a component to the frame.
 pack(): Automatically sizes the frame to fit its contents.

Layout Managers:

To organize components within a JFrame, you can use different layout managers:

 FlowLayout: Arranges components in a row or column, wrapping to the next line if necessary.
 BorderLayout: Divides the container into five regions: North, South, East, West, and Center.
 GridLayout: Arranges components in a grid of rows and columns.
 CardLayout: Displays one component at a time, like cards in a deck.
 GridBagLayout: Provides flexible layout with precise control over component placement.

Example with BorderLayout:

JFrame frame = new JFrame("BorderLayout Example");


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());

JLabel northLabel = new JLabel("North");


JButton eastButton = new JButton("East");
JButton westButton = new JButton("West");
JTextArea centerArea = new JTextArea("Center");
JButton southButton = new JButton("South");

frame.add(northLabel, BorderLayout.NORTH);
frame.add(eastButton, BorderLayout.EAST);
frame.add(westButton, BorderLayout.WEST);
frame.add(centerArea, BorderLayout.CENTER);
frame.add(southButton, BorderLayout.SOUTH);

frame.setSize(300, 200);
frame.setVisible(true);

JWindow:

A JWindow is a lightweight top-level container in Swing that doesn't have a title bar, menu bar, or
borders. It's often used for simple pop-up windows, tooltips, or custom window decorations.

Key Features:

 Lightweight: Doesn't require heavyweight components like AWT components.


 Customizable: Can be customized to have any shape or transparency.
 Modal and Modeless: Can be modal (blocks interaction with other windows) or modeless.

Common Use Cases:

 Tooltips: Small pop-up windows that display information about a component.


 Custom Dialogs: Creating custom dialogs with unique appearances.
 Splash Screens: Displaying a welcome screen while the application loads.

Example:

import javax.swing.*;
import java.awt.*;

public class JWindowExample {


public static void main(String[] args) {
JWindow window = new JWindow();
window.setSize(200, 100);
window.setLocationRelativeTo(null); // Center the window on the screen
JLabel label = new JLabel("Hello, World!");
window.add(label);

window.setVisible(true);
}
}

Key Points to Remember:

 JWindow is often used in conjunction with JFrame or JDialog to create more complex user
interfaces.
 You can customize the appearance of a JWindow using the setShape() method to create non-
rectangular windows.
 Be mindful of the platform-specific limitations and restrictions when using JWindow.

JDialog: A Modal or Modeless Dialog Box

A JDialog is a top-level container in Swing that represents a dialog box. It is often used for displaying
messages, asking for user input, or providing additional information.

Key Features:

 Modal or Modeless:
o Modal dialogs: Block interaction with the parent window until they are closed.
o Modeless dialogs: Allow interaction with the parent window while they are open.
 Title Bar: Displays a title.
 Close Button: Can be closed by the user.
 Customizable: Can be customized with various components and layouts.

Common Use Cases:

 Message Dialogs: Displaying simple messages to the user.


 Input Dialogs: Prompting the user for input.
 File Chooser Dialogs: Allowing the user to select files.
 Color Chooser Dialogs: Allowing the user to select colors.

Example:

import javax.swing.*;
import java.awt.*;

public class JDialogExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Main Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);

// Create a modal dialog


JDialog dialog = new JDialog(frame, "Modal Dialog", true);
dialog.setSize(200, 100);
dialog.setLayout(new FlowLayout());
dialog.add(new JLabel("This is a modal dialog."));
dialog.setVisible(true);
}
}

In this example, a modal dialog is created and displayed. The true argument in the JDialog constructor
makes the dialog modal, preventing interaction with the main frame until the dialog is closed.

Key Points:

 JDialog is often used to create custom dialogs for specific purposes.


 You can customize the appearance and behavior of a JDialog using various properties and
methods.
 Modal dialogs are useful for ensuring user input before proceeding with other actions.
 Modeless dialogs can be used for additional information or options that don't require immediate
user attention.

JPanel: A Versatile Container

A JPanel is a lightweight container in Swing that is used to group components together. It's a versatile
component that can be used to organize and structure your user interface.

Key Features:

 Lightweight: Doesn't require heavyweight components like AWT components.


 Customizable: Can be customized with various layouts, borders, and background colors.
 Flexible: Can be used to create complex layouts and group related components.

Common Use Cases:

 Grouping Components: Organizing related components into logical groups.


 Creating Custom Panels: Building reusable custom panels with specific layouts and components.
 Adding Scrolling: Using JScrollPane to create scrollable panels for large content.
 Card Layout: Implementing card-based layouts to switch between different views.

Example:

Java
import javax.swing.*;
import java.awt.*;

public class JPanelExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Panel Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);

JPanel panel = new JPanel();

panel.setLayout(new FlowLayout());

JLabel label = new JLabel("Hello, JPanel!");


JButton button = new JButton("Click Me");
panel.add(label);
panel.add(button);

frame.add(panel);
frame.setVisible(true);
}
}

JButton: The Clickable Button

A JButton is a fundamental Swing component that triggers an action when clicked. It's widely used in user
interfaces to initiate various tasks, such as submitting forms, opening dialogs, or performing calculations.

Key Features:

 Text Label: Displays text on the button.


 Icon: Can display an icon instead of or in addition to text.
 Enabled/Disabled State: Can be enabled or disabled to control user interaction.
 Focusable: Can receive keyboard focus.
 Tool Tips: Can display informative text when the mouse hovers over the button.

Example:

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JButtonExample {


public static void main(String[] args)
{
JFrame frame = new JFrame("Button Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);

JButton
button = new JButton("Click Me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent
e) {
System.out.println("Button clicked!");
}
});

frame.add(button);
frame.setVisible(true);

}
}

JToggleButton:

A JToggleButton is a type of button that can be toggled between two states: selected and
deselected. It's often used to represent on/off switches, checkboxes, or radio buttons.
Key Features:

 Two States: Selected and deselected.


 Customizable Appearance: Can be customized to display different text or icons in each state.
 Focusable: Can receive keyboard focus.
 Event Handling: Can trigger events when the button's state changes.

Common Use Cases:

 Toggle Switches: For turning features on and off.


 Checkboxes: For selecting multiple options.
 Radio Buttons: For selecting one option from a group.

JCheckBox: A Versatile Check Box

A JCheckBox is a Swing component that allows users to select or deselect an option. It's
commonly used to create checkboxes in forms and dialogs.

Key Features:

 Two States: Selected and deselected.


 Customizable Text: You can set a label to describe the option.
 Icon Support: You can add icons to visually represent the option.
 Event Handling: You can handle selection and deselection events using ItemListener.

JRadioButton: Selecting One Option

A JRadioButton is a Swing component that allows users to select one option from a group of
related options. It's often used in forms and dialogs to present mutually exclusive choices.

Key Features:

 Grouped Selection: Radio buttons are typically grouped together using a ButtonGroup to ensure
that only one button can be selected at a time.
 Customizable Text and Icons: You can set a label and icon for each radio button.
 Event Handling: You can handle selection events using an ItemListener.

Example:

import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

public class JRadioButtonExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JRadioButton Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);

ButtonGroup group = new ButtonGroup();

JRadioButton radioButton1 = new JRadioButton("Option 1");


JRadioButton radioButton2 = new JRadioButton("Option 2");
JRadioButton radioButton3 = new JRadioButton("Option 3");

group.add(radioButton1);
group.add(radioButton2);
group.add(radioButton3);

radioButton1.addItemListener(new ItemListener() { @Override


public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
System.out.println("Option 1 selected");
}
}
});

// Add similar listeners for other radio buttons

frame.add(radioButton1);
frame.add(radioButton2);
frame.add(radioButton3);

frame.setVisible(true);
}
}

JLabel

A JLabel is a simple component used to display text or images. It's often used to provide labels for other
components, such as text fields or buttons.

Example:

JLabel label = new JLabel("Name:");

JTextField

A JTextField is a single-line text input field. It allows users to enter text, which can then be retrieved and
processed by the application.

Example:

JTextField textField = new JTextField(20); // Creates a text field with a width of 20 characters

JTextArea

A JTextArea is a multi-line text input area. It's useful for displaying large amounts of text or allowing
users to input multiple lines of text.

Example:

JTextArea textArea = new JTextArea(5, 20); // Creates a text area with 5 rows and 20 columns
JList

A JList displays a list of items from which the user can select one or multiple items.

Example:

String[] items = {"Item 1", "Item 2", "Item 3"};


JList<String> list = new JList<>(items);

JComboBox

A JComboBox is a drop-down list that allows the user to select one item from a list of options.

Example:

String[] items = {"Item 1", "Item 2", "Item 3"};


JComboBox<String> comboBox = new JComboBox<>(items);

JScrollPane

A JScrollPane provides scrollable views of large components. It's often used with JTextArea, JList, and
other components that may exceed the visible area.

Example:

JTextArea textArea = new JTextArea(10, 20);


JScrollPane scrollPane = new JScrollPane(textArea);

1-Mark:

1. What is Swing?

a) A set of lightweight components for building graphical user interfaces.

b) A set of heavyweight components for building graphical user interfaces.


c) A programming language.

d) A database management system.

2. What is the base class for all Swing components?

a) Component

b) Container

c) JComponent

d) JFrame

3. Which of the following is a top-level container?

a) JPanel

b) JButton

c) JFrame

d) JLabel

4. What is the purpose of a JPanel?

a) To display text.

b) To group other components.

c) To create a menu bar.

d) To display images.

5. Which component is used to display text that cannot be edited?

a) JTextField

b) JTextArea

c) JLabel

d) JButton

6. Which component is used to display a list of items from which the user can select one or
more?

a) JComboBox

b) JList
c) JButton

d) JLabel

7. Which component is used to display a single line of editable text?

a) JTextArea

b) JTextField

c) JLabel

d) JButton

8. Which component is used to create a scrollable view of a large component?

a) JScrollPane

b) JScrollBar

c) JViewport

d) JLayeredPane

9. Which component is used to display a single line of non-editable text?

a) JTextField

b) JTextArea

c) JLabel

d) JButton

10. Which component is used to display multiple lines of text, both editable and non-editable?

a) JTextField

b) JTextArea

c) JLabel

d) JButton

11. Which component is used to display a single line of editable text?

a) JTextField

b) JTextArea

c) JLabel
d) JButton

12. Which component is used to display a list of items from which the user can select one or
more?

a) JComboBox

b) JList

c) JButton

d) JLabel

13. Which component is used to display a drop-down list of items from which the user can select
one?

a) JComboBox

b) JList

c) JButton

d) JLabel

14. Which component is used to create a scrollable view of a large component?

a) JScrollPane

b) JScrollBar

c) JViewport

d) JLayeredPane

15. Which of the following is a top-level container?

a) JPanel

b) JButton

c) JFrame

d) JLabel

16. Which of the following is a lightweight container?

a) JFrame

b) JDialog

c) JPanel
d) JWindow

17. Which of the following is a modal dialog box?

a) JWindow

b) JDialog

c) JFrame

d) JPanel

18. Which component is used to trigger an action when clicked?

a) JButton

b) JToggleButton

c) JCheckBox

d) JRadioButton

19. Which component can be in two states: selected or deselected?

a) JButton

b) JToggleButton

c) JCheckBox

d) JRadioButton

20. Which component is used to select multiple options from a group of options?

a) JButton

b) JToggleButton

c) JCheckBox

d) JRadioButton

5-MARK & 10-MARK QUESTION:

1. Explain the hierarchy of Swing components.

2. Give examples of top-level containers and lightweight components.


3. Discuss the role of the JComponent class in this hierarchy.

4. Explain the event handling mechanism in Swing.

5. Discuss the role of ActionListener, ItemListener, and KeyListener.

6. Explain the different layout managers available in Swing.

7. Provide code examples to demonstrate their usage.

8 . Customizing Swing Components.

You might also like