Java Notes with examples in detailed notes
Java Notes with examples in detailed notes
java
Copy code
class Car {
String color;
int speed;
void drive() {
System.out.println("Car is driving");
}
}
java
Copy code
Car myCar = new Car(); // Object creation
myCar.color = "Red"; // Assigning value
myCar.drive(); // Calling method
a. Encapsulation
o Bundling of data (fields) and methods (functions) together into a single unit
(class).
o Helps protect the data from unauthorized access by using access modifiers
like private, protected, public.
o Example:
java
Copy code
class BankAccount {
private double balance;
b. Inheritance
o A mechanism where one class (child) acquires the properties and behaviors of
another class (parent).
o Promotes code reusability.
o Example:
java
Copy code
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}
c. Polymorphism
java
Copy code
// Method Overloading
class Calculator {
int add(int a, int b) {
return a + b;
}
// Method Overriding
class Parent {
void show() {
System.out.println("Parent's show");
}
}
d. Abstraction
java
Copy code
abstract class Shape {
abstract void draw();
}
interface Animal {
void sound();
}
java
Copy code
class Book {
String title;
String author;
void displayBookInfo() {
System.out.println("Title: " + title + ", Author: " + author);
}
}
class Library {
ArrayList<Book> books = new ArrayList<>();
void displayBooks() {
for (Book book : books) {
book.displayBookInfo();
}
}
}
java
Copy code
import java.util.ArrayList;
library.displayBooks();
}
}
Conclusion
Object-Oriented Development in Java is a powerful paradigm for creating scalable, reusable, and
maintainable software. By understanding and applying the principles of OOP—encapsulation,
inheritance, polymorphism, and abstraction—you can create robust Java applications. Start with
simple projects and gradually work on larger, more complex systems to gain mastery.
Class
java
Copy code
class Car {
String color;
int speed;
void drive() {
System.out.println("The car is driving");
}
}
Object
java
Copy code
Car myCar = new Car(); // Create an object
myCar.color = "Red"; // Assign value to the object
myCar.drive(); // Call the method
2. Encapsulation
Encapsulation is the bundling of data (attributes) and methods (behaviors) within a class.
It ensures data hiding, meaning sensitive information can be hidden from unauthorized
access using access modifiers like private, protected, and public.
Example:
java
Copy code
class BankAccount {
private double balance; // Private variable (data hiding)
3. Inheritance
Inheritance allows a class (child) to inherit properties and methods from another class
(parent).
Promotes code reusability and helps create a hierarchical structure.
Example:
java
Copy code
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}
class Dog extends Animal { // Dog inherits from Animal
void bark() {
System.out.println("Dog barks");
}
}
4. Polymorphism
java
Copy code
class Calculator {
int add(int a, int b) {
return a + b;
}
java
Copy code
class Parent {
void show() {
System.out.println("Parent's show");
}
}
5. Abstraction
Abstraction focuses on hiding the complexity and showing only the essential features of
an object.
It can be achieved through:
o Abstract Classes: A class that cannot be instantiated and may contain abstract
methods (methods without implementation).
o Interfaces: A contract that classes must follow, defining methods that the class
must implement.
java
Copy code
abstract class Shape {
abstract void draw(); // Abstract method
}
Example: Interface:
java
Copy code
interface Animal {
void sound();
}
Represents a relationship between two classes where objects of one class can use objects
of another.
Example:
java
Copy code
class Student {
String name;
}
class School {
String schoolName;
}
Aggregation
A "has-a" relationship where one class is part of another, but can exist independently.
Example:
java
Copy code
class Department {
String deptName;
}
class University {
List<Department> departments; // Aggregation
}
Composition
A stronger form of aggregation where one class cannot exist without the other.
Example:
java
Copy code
class Engine {
void start() {
System.out.println("Engine starting");
}
}
class Car {
private Engine engine = new Engine(); // Composition
void startCar() {
engine.start();
}
}
7. Benefits of OOP
java
Copy code
class Book {
String title;
String author;
void display() {
System.out.println("Title: " + title + ", Author: " + author);
}
}
class Library {
List<Book> books = new ArrayList<>();
void showBooks() {
for (Book book : books) {
book.display();
}
}
}
Benefits of Object Oriented Development.
1. Modularity
Description: OOD organizes code into smaller, self-contained classes and objects, each
responsible for specific tasks.
Benefit: This modular approach makes the system easier to understand, develop, and
debug.
Example: In a Library Management System, you can have separate classes
for Book, Member, and Library, each handling their own functionality.
2. Reusability
Description: Through inheritance, you can reuse existing classes and extend their
functionality in new classes.
Benefit: Saves time and effort by reducing redundancy in code.
Example: A Vehicle class can define common properties
like speed and fuelCapacity, which can be reused in Car and Bike subclasses.
3. Maintainability
4. Scalability
5. Data Security
6. Code Readability
7. Flexibility
8. Real-World Mapping
Description: OOD reflects real-world entities and their relationships through classes and
objects.
Benefit: Makes problem-solving more natural and intuitive.
Example: A School system can have objects like Teacher, Student, and Classroom,
which directly map to real-world entities.
9. Collaboration and Teamwork
Description: OOD enables large systems to be broken into smaller components, allowing
multiple developers to work on different parts simultaneously.
Benefit: Speeds up development and improves collaboration.
Example: In a shopping application, one team can work on Product features while
another team focuses on Cartfunctionalities.
Description: Object-oriented systems are better organized, making them easier to test
and debug.
Benefit: Results in fewer errors and higher-quality software.
Example: Isolated and well-tested objects in a billing system reduce the chances of errors
in final invoices.
13. Interoperability
Java programming fundamentals refer to the basic building blocks and core concepts that are
essential to understanding and writing programs in Java. These fundamentals include the syntax,
data types, control structures, and object-oriented principles that form the foundation of Java
development. Here's a detailed breakdown:
java
Copy code
class Car {
String brand;
void drive() {
System.out.println("Driving " + brand);
}
}
7. Methods
o Methods are blocks of code designed to perform a specific task, with optional
parameters and a return type.
o Example:
java
Copy code
int add(int a, int b) {
return a + b;
}
8. Access Modifiers
o Define the visibility of classes, methods, and
variables: public, private, protected, and default.
9. Packages
o A package is a namespace that organizes related classes and interfaces,
like java.util or java.io.
10. Exception Handling
o Java provides mechanisms (try, catch, finally) to handle runtime errors
gracefully.
11. Java Standard Library
o A rich set of pre-defined classes and methods for tasks like file I/O, data
structures, networking, and more.
12. Basic Input and Output (I/O)
o Java supports user input and output using classes like Scanner and System.out.
13. Compilation and Execution
o Java code is written in a .java file, compiled into bytecode using javac, and
executed by the JVM.
java
Copy code
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Explanation
Java is a high-level, object-oriented, and versatile programming language widely used for
developing applications across various platforms. Created by James Gosling and his team at Sun
Microsystems in 1995, Java has become a cornerstone of software development due to its
simplicity, portability, and reliability.
Overview of Java
1. Java Editions
Java is available in several editions tailored to different development needs:
2. Java Architecture
6. Applications of Java
Data types:
Data types in Java are fundamental to defining the nature of the data a variable can hold. They
determine the size and type of values that can be stored and manipulated in a program. Java's
strict data typing ensures type safety and helps catch errors during compilation, making it a
reliable language for developing robust applications.
Reference data types store the reference (or address) of an object in memory rather than the
actual data.
java
Copy code
String greeting = "Hello, Java!";
java
Copy code
int[] numbers = {1, 2, 3, 4, 5};
java
Copy code
class Student {
String name;
int age;
}
Student s = new Student();
Java allows converting data from one type to another to ensure compatibility and efficient use of
resources.
java
Copy code
int a = 10;
double b = a; // Widening from int to double
java
Copy code
double x = 10.5;
int y = (int) x; // Narrowing from double to int
5. Wrapper Classes
Primitive types are not objects, but Java provides wrapper classes to treat them as objects when
needed. These classes are part of the java.lang package.
java
Copy code
int num = 100;
Integer obj = num; // Autoboxing (primitive to wrapper)
int num2 = obj; // Unboxing (wrapper to primitive)
Each data type has a default value when declared but not initialized:
Data Type Default Value
byte, short, int, long 0
float, double 0.0
char \u0000
boolean false
Reference Types null
In Java, variables and arrays are fundamental building blocks that allow developers to store,
manipulate, and organize data efficiently. They form the basis of memory management and
logical data structures in Java programming.
Variables in Java
Definition
A variable is a container for storing data values. Each variable has a data type, a name, and a
value, and it is stored in memory during program execution.
1. Local Variables:
o Declared inside a method, constructor, or block.
o Accessible only within the block in which they are defined.
o Must be initialized before use.
o Example:
java
Copy code
public void calculate() {
int sum = 10; // Local variable
System.out.println(sum);
}
2. Instance Variables:
o Declared inside a class but outside methods, constructors, or blocks.
o Each object has its own copy of instance variables.
o Automatically initialized with default values if not explicitly initialized.
o Example:
java
Copy code
class Student {
String name; // Instance variable
int age;
}
java
Copy code
class Student {
static String schoolName = "ABC School"; // Static variable
}
java
Copy code
int number;
java
Copy code
number = 10;
java
Copy code
int number = 10;
Arrays in Java
Definition
An array is a collection of variables of the same data type stored in contiguous memory
locations. Arrays allow efficient storage and manipulation of large datasets.
1. Characteristics of Arrays
2. Types of Arrays
1. Single-Dimensional Arrays:
o Stores data in a linear form.
o Example:
java
Copy code
int[] numbers = {10, 20, 30, 40};
2. Multi-Dimensional Arrays:
o Stores data in a tabular format (e.g., matrix).
o Example:
java
Copy code
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
3. Declaring, Instantiating, and Initializing Arrays
java
Copy code
int[] arr; // Declares an array
java
Copy code
arr = new int[5]; // Allocates memory for 5 integers
java
Copy code
arr[0] = 10; // Assigns value to the first element
java
Copy code
int[] arr = {1, 2, 3, 4, 5};
java
Copy code
int[] numbers = {10, 20, 30};
System.out.println(numbers[0]); // Outputs 10
java
Copy code
int[] arr = {10, 20, 30};
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
6. Multi-Dimensional Arrays
java
Copy code
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
2. Accessing Elements:
java
Copy code
System.out.println(matrix[1][2]); // Outputs 6
java
Copy code
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
Practical Example
java
Copy code
public class ArrayExample {
public static void main(String[] args) {
// Single Variable
int num = 10;
System.out.println("Single Variable: " + num);
// Array Example
int[] numbers = {10, 20, 30, 40};
System.out.println("Array Elements:");
for (int n : numbers) {
System.out.println(n);
}
// Multi-Dimensional Array
int[][] matrix = {
{1, 2},
{3, 4}
};
System.out.println("Multi-Dimensional Array Element: " + matrix[1]
[1]); // Outputs 4
}
}
Summary
Operators in Java
Operators in Java are special symbols or keywords used to perform operations on variables and
values. They help in tasks such as arithmetic computations, logical decision-making,
comparison, and more. Java operators are broadly classified into different categories based on
their purpose.
Categories of Operators
1. Arithmetic Operators
2. Relational (Comparison) Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Unary Operators
7. Ternary (Conditional) Operator
8. Special Operators
1. Arithmetic Operators
Example:
java
Copy code
int a = 10, b = 5;
System.out.println("Addition: " + (a + b)); // Outputs 15
System.out.println("Remainder: " + (a % b)); // Outputs 0
Used to compare two values. The result is always a boolean (true or false).
Example:
java
Copy code
int x = 10, y = 5;
System.out.println(x > y); // Outputs true
System.out.println(x == y); // Outputs false
3. Logical Operators
Example:
java
Copy code
int a = 10, b = 5, c = 20;
System.out.println((a > b) && (c > a)); // Outputs true
System.out.println((a > c) || (b < c)); // Outputs true
4. Bitwise Operators
Example:
java
Copy code
int a = 5, b = 3;
System.out.println(a & b); // Outputs 1
System.out.println(a | b); // Outputs 7
5. Assignment Operators
java
Copy code
int x = 10;
x += 5; // x becomes 15
System.out.println(x); // Outputs 15
6. Unary Operators
Example:
java
Copy code
int x = 5;
System.out.println(++x); // Outputs 6 (pre-increment)
System.out.println(x--); // Outputs 6 (post-decrement)
System.out.println(x); // Outputs 5
Example:
java
Copy code
int a = 10, b = 5;
String result = (a > b) ? "a is greater" : "b is greater";
System.out.println(result); // Outputs "a is greater"
8. Special Operators
1. Instanceof: Checks if an object is an instance of a specific class.
java
Copy code
String name = "Java";
System.out.println(name instanceof String); // Outputs true
java
Copy code
System.out.println(Math.PI); // Accesses PI from the Math class
java
Copy code
int[] nums = {10, 20, 30};
System.out.println(nums[0]); // Outputs 10
Operator Precedence
Operators have a specific order of evaluation. Higher precedence operators are evaluated first.
Control statements in Java are used to manage the flow of program execution. They allow
developers to direct the program's logic, based on conditions, repetitions, or explicit jumps in the
code.
1. Decision-Making Statements
Definition:
Decision-making statements allow the program to execute certain blocks of code based on
specified conditions.
a) if Statement
Definition: The if statement checks a condition and executes a block of code if the
condition evaluates to true.
Syntax:
java
Copy code
if (condition) {
// Code to execute
}
b) if-else Statement
Definition: The if-else statement executes one block of code if the condition
is true and another block if the condition is false.
Syntax:
java
Copy code
if (condition) {
// Code for true condition
} else {
// Code for false condition
}
c) if-else-if Ladder
java
Copy code
if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2
} else {
// Default code
}
d) switch Statement
Definition: The switch statement allows a variable to be tested against a list of values
(case), and executes the matching case block.
Syntax:
java
Copy code
switch (expression) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Default code
}
2. Looping Statements
Definition:
Looping statements are used to execute a block of code repeatedly until a specified condition is
met.
a) for Loop
Definition: The for loop is used when the number of iterations is known beforehand. It
initializes, checks the condition, and increments/decrements the counter in one statement.
Syntax:
java
Copy code
for (initialization; condition; increment/decrement) {
// Code to execute
}
b) while Loop
Definition: The while loop repeats a block of code as long as the condition evaluates
to true. The condition is checked before the loop executes.
Syntax:
java
Copy code
while (condition) {
// Code to execute
}
c) do-while Loop
Definition: The do-while loop executes a block of code at least once, and then continues
to repeat the block as long as the condition evaluates to true.
Syntax:
java
Copy code
do {
// Code to execute
} while (condition);
Definition: The enhanced for loop simplifies iteration over arrays or collections by
directly accessing each element.
Syntax:
java
Copy code
for (type variable : array) {
// Code to execute
}
3. Branching Statements
Definition:
Branching statements are used to change the normal flow of execution by jumping to specific
parts of the code.
a) break Statement
Definition: The break statement is used to exit a loop or switch statement prematurely,
skipping the remaining code.
Syntax:
java
Copy code
break;
b) continue Statement
Definition: The continue statement skips the current iteration of a loop and moves to the
next iteration.
Syntax:
java
Copy code
continue;
c) return Statement
Definition: The return statement is used to exit from a method and optionally return a
value.
Syntax:
java
Copy code
return value; // Optional value
Mastering control statements is essential for creating logic-driven and dynamic Java programs.
They enable developers to implement decision-making and repetitive tasks efficiently.
Classes in Java
A class is a blueprint or template for creating objects in Java. It defines the structure (fields or
attributes) and behavior (methods) that the objects created from the class will have. Classes are a
fundamental part of Object-Oriented Programming (OOP).
Definition of a Class
1. Fields (Attributes): Variables that hold the state or properties of the objects.
2. Methods: Functions that define the behavior or actions of the objects.
Syntax of a Class
java
Copy code
class ClassName {
// Fields (variables)
type fieldName;
// Methods (functions)
returnType methodName(parameters) {
// Method body
}
}
// Method
void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
Explanation
Objects are instances of a class. To create an object, use the new keyword.
Example:
java
Copy code
public class Main {
public static void main(String[] args) {
// Create an object of the Student class
Student student1 = new Student();
Output:
makefile
Copy code
Name: John
Age: 20
1. Fields
java
Copy code
String brand; // Field
int speed;
2. Methods
java
Copy code
void accelerate() {
System.out.println("Car is accelerating");
}
3. Constructor
Definition: A special method used to initialize objects. It has the same name as the class
and no return type.
Example:
java
Copy code
class Car {
String brand;
// Constructor
Car(String carBrand) {
brand = carBrand;
}
}
1. Concrete Class
A regular class with fully implemented methods.
Example:
java
Copy code
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
2. Abstract Class
A class that contains abstract (unimplemented) methods. Cannot be instantiated.
Example:
java
Copy code
abstract class Shape {
abstract void draw();
}
3. Inner Class
A class defined within another class.
Example:
java
Copy code
class Outer {
class Inner {
void display() {
System.out.println("Inner class method");
}
}
}
4. Static Class
A nested class marked with the static keyword. It does not require an instance of the
outer class.
Example:
java
Copy code
class Outer {
static class Inner {
void display() {
System.out.println("Static inner class method");
}
}
}
Real-World Example
Class: Car
java
Copy code
class Car {
// Fields
String brand;
int speed;
// Constructor
Car(String brand, int speed) {
this.brand = brand;
this.speed = speed;
}
// Method
void displayDetails() {
System.out.println("Brand: " + brand);
System.out.println("Speed: " + speed + " km/h");
}
}
public class Main {
public static void main(String[] args) {
// Create an object of Car
Car car1 = new Car("Tesla", 120);
Output:
makefile
Copy code
Brand: Tesla
Speed: 120 km/h
Methods in Java
A method in Java is a block of code or a function that performs a specific task. Methods are used
to define the behavior of a class and are invoked by objects or the class itself (if static). They
help achieve code reusability and modularity.
Definition of a Method
A method is a reusable set of statements designed to perform a specific task and return a result
(optional). It may take input parameters to operate on.
Syntax of a Method
java
Copy code
returnType methodName(parameters) {
// Method body (statements)
// Optional return statement
}
returnType: Specifies the data type of the value the method returns (use void if no value
is returned).
methodName: The name of the method.
parameters: Variables passed to the method for input (optional).
method body: The code inside the method that executes the desired functionality.
1. Predefined Methods
Methods already defined in Java libraries (e.g., System.out.println(), Math.max()).
2. User-Defined Methods
Methods created by the programmer to perform specific tasks.
Method Example
User-Defined Method:
java
Copy code
class Calculator {
// Method to add two numbers
int add(int a, int b) {
return a + b;
}
}
1. Method Declaration
java
Copy code
int multiply(int a, int b) {
return a * b;
}
2. Method Invocation
Calling the method using its name, either with an object or directly (if static).
Example:
java
Copy code
Calculator calc = new Calculator();
calc.multiply(4, 5);
3. Return Statement
Used to return a value from the method. If no return value is required, use void.
Example:
java
Copy code
double getArea(double radius) {
return 3.14 * radius * radius;
}
1. Parameterized Methods
java
Copy code
void greet(String name) {
System.out.println("Hello, " + name);
}
2. Non-Parameterized Methods
java
Copy code
void displayMessage() {
System.out.println("Welcome!");
}
3. Static Methods
Methods declared with the static keyword. These can be called without creating an object.
Example:
java
Copy code
static int square(int num) {
return num * num;
}
4. Instance Methods
java
Copy code
class Car {
void start() {
System.out.println("Car is starting...");
}
}
1. Method Overloading
Definition: Creating multiple methods with the same name but different parameter lists.
Example:
java
Copy code
class Calculator {
int add(int a, int b) {
return a + b;
}
2. Method Overriding
Definition: Redefining a method in a subclass that already exists in the parent class.
Example:
java
Copy code
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
java
Copy code
class MathOperations {
int square(int num) {
return num * num;
}
}
java
Copy code
class Utility {
static void printMessage(String message) {
System.out.println(message);
}
}
public class Main {
public static void main(String[] args) {
Utility.printMessage("Static method called!"); // Output: Static
method called!
}
}
java
Copy code
class Greeting {
void sayHello(String name) {
System.out.println("Hello, " + name + "!");
}
}
Advantages of Methods
Summary
Constructors in Java
A constructor in Java is a special method used to initialize objects. It is called when an object of
a class is created. Constructors are essential for setting up an object with initial values or
configurations.
Definition
A constructor is a block of code similar to a method that is executed when an object is created. It
has the same name as the class and does not have a return type, not even void.
Syntax of a Constructor
java
Copy code
class ClassName {
// Constructor
ClassName(parameters) {
// Constructor body
}
}
Types of Constructors
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor (Not supported directly but can be implemented)
1. Default Constructor
A default constructor is one that does not accept any parameters. If no constructor is explicitly
defined, Java provides a default constructor automatically.
Example:
java
Copy code
class Student {
String name;
// Default constructor
Student() {
name = "Unknown";
}
void display() {
System.out.println("Name: " + name);
}
}
2. Parameterized Constructor
A parameterized constructor accepts arguments to initialize the object with specific values.
Example:
java
Copy code
class Student {
String name;
int age;
// Parameterized constructor
Student(String studentName, int studentAge) {
name = studentName;
age = studentAge;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student("Alice", 20); // Passing values to
constructor
student.display(); // Output: Name: Alice, Age: 20
}
}
3. Copy Constructor
Java does not directly support a copy constructor like C++, but it can be implemented by creating
a constructor that accepts an object of the same class.
Example:
java
Copy code
class Student {
String name;
int age;
// Parameterized constructor
Student(String studentName, int studentAge) {
name = studentName;
age = studentAge;
}
// Copy constructor
Student(Student otherStudent) {
name = otherStudent.name;
age = otherStudent.age;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
Constructor Overloading
Like methods, constructors can also be overloaded. Constructor overloading allows multiple
constructors with different parameter lists in the same class.
Example:
java
Copy code
class Box {
int width, height, depth;
// Default constructor
Box() {
width = height = depth = 0;
}
// Parameterized constructor
Box(int w, int h, int d) {
width = w;
height = h;
depth = d;
}
void displayDimensions() {
System.out.println("Dimensions: " + width + "x" + height + "x" +
depth);
}
}
1. Can use this keyword: To refer to the current class instance. Example:
java
Copy code
class Employee {
String name;
int id;
java
Copy code
class Person {
String name;
int age;
// Default constructor
Person() {
this("Unknown", 0); // Calls parameterized constructor
}
// Parameterized constructor
Person(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
The scope of a variable in Java refers to the part of the program where the variable is accessible
or visible. In simpler terms, it determines the lifetime and visibility of the variable.
Definition: Variables declared as static within a class are said to have class scope.
These variables are shared among all objects of the class and belong to the class itself
rather than any specific object.
Lifetime: Exists for the entire duration of the program.
Access: Can be accessed using the class name or an object of the class.
Example:
java
Copy code
class Counter {
static int count = 0; // Static variable (class scope)
Counter() {
count++; // Increment count whenever an object is created
}
void displayCount() {
System.out.println("Count: " + count);
}
}
Definition: Variables declared inside a class but outside any method or block are instance
variables. Each object of the class has its own copy of these variables.
Lifetime: Exists as long as the object exists.
Access: Accessible by creating an object of the class.
Example:
java
Copy code
class Student {
String name; // Instance variable
int age;
void displayDetails() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
Definition: Variables declared inside a method are local variables. They can only be
accessed within that method.
Lifetime: Exists only during the execution of the method.
Access: Not accessible outside the method.
Example:
java
Copy code
class Calculator {
void add() {
int a = 10; // Local variable
int b = 20;
System.out.println("Sum: " + (a + b));
}
}
4. Block Scope
Definition: Variables declared inside a block (e.g., if, for, or while) are limited to that
block.
Lifetime: Exists only during the execution of the block.
Access: Not accessible outside the block.
Example:
java
Copy code
public class Main {
public static void main(String[] args) {
int x = 10;
if (x > 5) {
int y = 20; // Block-scoped variable
System.out.println("y: " + y); // Output: y: 20
}
Scope vs Lifetime
Aspect Scope Lifetime
Definition Where the variable can be accessed. How long the variable exists in memory.
A local variable's scope is within the A static variable's lifetime is the entire
Example
method. program.
Variable Shadowing
Definition: When a local variable with the same name as a class or instance variable
hides the outer variable.
Example:
java
Copy code
class Test {
int x = 5; // Instance variable
void show() {
int x = 10; // Local variable (shadows instance variable)
System.out.println("Local x: " + x); // Output: Local x: 10
System.out.println("Instance x: " + this.x); // Output: Instance x: 5
}
}
Access modifiers (private, public, protected, default) also influence the visibility of
variables but are independent of the scope.
Summary of Scopes
By understanding variable scope, you can write cleaner, more efficient, and bug-free Java code.
Access modifiers in Java define the visibility or accessibility of classes, methods, variables, and
constructors. They control how different parts of a program interact with one another and ensure
encapsulation by restricting access to sensitive parts of the code.
1. Public
2. Private
3. Protected
4. Default (Package-Private)
1. Public Modifier
Example:
java
Copy code
public class PublicExample {
public void display() {
System.out.println("Public method is accessible everywhere.");
}
}
Definition: Members marked as private are accessible only within the class in which
they are declared.
Usage: Often used for data hiding or encapsulation to restrict access to sensitive fields.
Example:
java
Copy code
class PrivateExample {
private int data = 10; // Private variable
3. Protected Modifier
Example:
java
Copy code
class Parent {
protected String name = "Parent Class"; // Protected variable
Definition: If no access modifier is specified, the member is accessible only within the
same package.
Usage: Useful for restricting access within a package without explicitly marking
it private.
Example:
java
Copy code
class DefaultExample {
void show() { // Default access
System.out.println("Default access: Accessible within the same
package.");
}
}
Key Points
1. Public: Provides the broadest accessibility, useful for methods and classes intended to be
universally accessible.
2. Private: Most restrictive; only accessible within the class. Ensures encapsulation.
3. Protected: Balances visibility; accessible to subclasses and within the same package.
4. Default: Package-private access; only accessible within the same package.
Example:
java
Copy code
// Default class
class DefaultClass {
void show() {
System.out.println("Default class: Only accessible in the same
package.");
}
}
// Public class
public class PublicClass {
public void display() {
System.out.println("Public class: Accessible everywhere.");
}
}
Practical Example
java
Copy code
package animals;
// In a different package
package zoo;
import animals.Dog;
By strategically using access modifiers, you can build robust and secure applications.
Inheritance in Java
Inheritance is a core concept in Object-Oriented Programming (OOP) that allows a class (child
class) to acquire the properties and methods of another class (parent class). It promotes code
reusability and establishes a hierarchical relationship between classes.
Key Terminology
1. Parent Class (Super Class):
o The class whose properties and methods are inherited.
2. Child Class (Sub Class):
o The class that inherits from the parent class.
3. extends Keyword:
o Used to establish an inheritance relationship between a child class and a parent
class.
Syntax of Inheritance
java
Copy code
class Parent {
// Parent class members
}
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
1. Single Inheritance
Example:
java
Copy code
class Parent {
void showMessage() {
System.out.println("This is a message from the Parent class.");
}
}
2. Multilevel Inheritance
In multilevel inheritance, a class inherits from a class that is already a child of another class.
Example:
java
Copy code
class GrandParent {
void displayGrandParent() {
System.out.println("GrandParent class method.");
}
}
3. Hierarchical Inheritance
In hierarchical inheritance, multiple child classes inherit from the same parent class.
Example:
java
Copy code
class Parent {
void displayParent() {
System.out.println("Parent class method.");
}
}
1. Code Reusability:
o Reduces duplication of code by allowing child classes to use methods and fields
from parent classes.
2. Method Overriding:
o A child class can provide a specific implementation for a method defined in the
parent class.
Example of Overriding:
java
Copy code
class Parent {
void showMessage() {
System.out.println("Message from Parent class.");
}
}
class Child extends Parent {
@Override
void showMessage() {
System.out.println("Message from Child class.");
}
}
3. Hierarchical Structure:
o Establishes a clear hierarchy between classes.
The super keyword is used to access members of the parent class, including:
java
Copy code
class Parent {
void display() {
System.out.println("Parent class method.");
}
}
java
Copy code
class Parent {
Parent() {
System.out.println("Parent class constructor.");
}
}
Advantages of Inheritance
1. Code Reusability:
o Allows the reuse of existing code in new classes.
2. Method Overriding:
o Provides flexibility to modify parent class behavior in child classes.
3. Polymorphism:
o Enables dynamic method invocation and late binding.
4. Modularity:
o Encourages clean and modular code by organizing common functionalities in
parent classes.
Limitations of Inheritance
1. Tight Coupling:
o The child class becomes dependent on the implementation of the parent class.
2. Single Inheritance in Java:
o Java does not support multiple inheritance to avoid ambiguity (like the Diamond
Problem).
3. Increased Complexity:
o Improper use of inheritance can make code more complex and harder to debug.
Inheritance vs Composition
Summary
Inheritance is a powerful feature in Java that promotes code reuse, flexibility, and hierarchical
relationships between classes. However, it should be used judiciously to avoid issues like tight
coupling or complexity.
Packages
Definition:
A package in Java is a namespace that organizes classes and interfaces. It helps to prevent name
conflicts and provides controlled access to classes, methods, and fields.
Types of Packages
Creating a Package
1. Syntax:
java
Copy code
package packageName;
Example:
java
Copy code
package myPackage; // Declaring a package
Using a Package
1. Importing a Package:
o Use the import keyword to access a package.
Example:
java
Copy code
import myPackage.MyClass;
java
Copy code
import myPackage.*;
Access Modifier Same Class Same Package Subclass (Different Package) Other Packages
public Yes Yes Yes Yes
protected Yes Yes Yes No
Access Modifier Same Class Same Package Subclass (Different Package) Other Packages
default Yes Yes No No
private Yes No No No
Interfaces
Definition:
Defining an Interface
1. Syntax:
java
Copy code
interface InterfaceName {
// Abstract methods
void method1();
void method2();
}
Example:
java
Copy code
interface Animal {
void eat(); // Abstract method
void sleep(); // Abstract method
}
Implementing an Interface
1. Syntax:
java
Copy code
class ClassName implements InterfaceName {
// Provide implementation for all methods
}
Example:
java
Copy code
interface Animal {
void eat();
void sleep();
}
1. Abstract Methods:
o Methods in an interface are implicitly public and abstract.
2. Static and Final Variables:
o Variables declared in an interface are public, static, and final by default.
3. Multiple Inheritance:
o A class can implement multiple interfaces.
Example:
java
Copy code
interface A {
void methodA();
}
interface B {
void methodB();
}
class C implements A, B {
public void methodA() {
System.out.println("Method A from Interface A");
}
1. Default Methods:
o Introduced in Java 8 to allow interfaces to have methods with a default
implementation.
Example:
java
Copy code
interface Animal {
void eat();
2. Static Methods:
o Interfaces can have static methods, which can only be called using the interface
name.
Example:
java
Copy code
interface Utility {
static void printMessage() {
System.out.println("Static method in interface.");
}
}
You can define interfaces in packages and access them just like classes.
Example:
java
Copy code
// File: myPackage/MyInterface.java
package myPackage;
// File: Main.java
import myPackage.MyInterface;
class MyClass implements MyInterface {
public void greet() {
System.out.println("Hello from the interface!");
}
}
Summary
Packages:
o Organize code, prevent name conflicts, and provide access control.
o Use package and import keywords.
Interfaces:
o Provide a blueprint for classes with abstract methods.
o Allow multiple inheritance and ensure a contract for implementing classes.
o Introduced default and static methods in Java 8.
Both packages and interfaces enhance modularity, code organization, and maintainability in Java
Unit-II
1/0 basics: Stream and Byte classes, Character Streams, Reading Console input and output,
Print
Writer
Class, String Handling,
• Exceptions
Multithreaded Programming.
Link : https://www.programiz.com/java-programming/io-streams
1. Streams in Java
Definition:
A stream in Java is a sequence of data that represents an input source or output destination.
Streams abstract the process of reading and writing data, making it easier to handle various types
of I/O operations such as file, network, or memory access.
Types of Streams
Java divides streams into two main categories based on the type of data:
1. Byte Streams: Used for handling binary data (e.g., images, videos, or raw files).
o Classes: InputStream and OutputStream.
2. Character Streams: Used for handling text data (e.g., reading/writing files with text).
o Classes: Reader and Writer.
Stream Structure
Example:
java
Copy code
InputStream inputStream; // Reads data
OutputStream outputStream; // Writes data
2. Byte Streams
Definition:
Byte streams process data in 8-bit chunks and are best suited for binary data. They are the
foundation for low-level I/O operations in Java.
java
Copy code
import java.io.FileInputStream;
import java.io.IOException;
java
Copy code
import java.io.FileOutputStream;
import java.io.IOException;
java
ZCopy code
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
java
Copy code
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
1. Byte streams operate on 8-bit data, while character streams operate on 16-bit data (for
text).
2. Always close streams after use (or use try-with-resources).
3. Use buffered streams for better performance.
By mastering byte streams and their associated classes, developers can efficiently handle file and
network I/O operations in Java.
Definition:
Character streams in Java are designed to handle textual data (characters) rather than binary
data. They process data in 16-bit Unicode format, making them ideal for working with text
files, strings, or other character-based inputs and outputs.
1. Reader Class
2. Writer Class
1. FileReader:
o Reads characters from a file.
java
Copy code
import java.io.FileReader;
import java.io.IOException;
public class FileReaderExample {
public static void main(String[] args) {
try (FileReader fr = new FileReader("example.txt")) {
int character;
while ((character = fr.read()) != -1) {
System.out.print((char) character); // Convert int to char
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. FileWriter:
o Writes characters to a file.
java
Copy code
import java.io.FileWriter;
import java.io.IOException;
1. BufferedReader:
o Reads text from a character stream and buffers the input for efficient reading.
o Often used to read lines of text.
java
Copy code
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
2. BufferedWriter:
o Writes text to a character stream and buffers the output for efficient writing.
java
Copy code
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
1. InputStreamReader:
o Converts byte streams to character streams (bridge
between InputStream and Reader).
java
Copy code
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.IOException;
2. OutputStreamWriter:
o Converts character streams to byte streams (bridge
between Writer and OutputStream).
java
Copy code
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.IOException;
1. CharArrayReader:
o Reads data from a character array as a stream.
Example:
java
Copy code
import java.io.CharArrayReader;
import java.io.IOException;
2. CharArrayWriter:
o Writes data to a character array as a stream.
Example:
java
Copy code
import java.io.CharArrayWriter;
import java.io.IOException;
Use character streams for reading and writing text files or strings.
Use byte streams when dealing with binary data (e.g., images or videos).
Summary
Character streams simplify text processing in Java by providing tools optimized for Unicode
characters and string operations. With the variety of classes available, developers can handle
text-based I/O tasks efficiently and effectively
Java provides built-in mechanisms to interact with the console (standard input and output). These
are commonly used for basic programs, debugging, or simple user interaction.
1. Console Input
Java offers multiple ways to read input from the console. The most common are:
The Scanner class, located in the java.util package, is the most straightforward way to read
input.
java
Copy code
import java.util.Scanner;
System.out.println("Hello, " + name + "! You are " + age + " years
old.");
scanner.close(); // Close the scanner to free resources
}
}
BufferedReader is part of the java.io package. It is more efficient for reading large amounts
of text input.
java
Copy code
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
System.out.println("Hello, " + name + "! You are " + age + " years
old.");
}
}
The Console class, part of the java.io package, is ideal for console-based applications. It offers
methods for reading text and secure password input.
java
Copy code
import java.io.Console;
System.out.println("Hello, " + name + "! You are " + age + " years
old.");
} else {
System.out.println("Console is not available.");
}
}
}
2. Console Output
Example:
java
Copy code
System.out.print("Hello, ");
System.out.print("World!");
// Output: Hello, World!
Example:
java
Copy code
System.out.println("Hello, World!");
// Output:
// Hello, World!
Example:
java
Copy code
System.out.printf("Hello, %s! You are %d years old.%n", "Alice", 25);
// Output: Hello, Alice! You are 25 years old.
// Input
System.out.print("Enter your name: ");
String name = scanner.nextLine();
// Output
System.out.println("Hello, " + name + "! Your favorite number is " +
number + ".");
System.out.printf("Did you know %d squared is %d?%n", number, number *
number);
scanner.close();
}
}
Output (Example):
csharp
Copy code
Enter your name: Alice
Enter your favorite number: 7
Hello, Alice! Your favorite number is 7.
Did you know 7 squared is 49?
Summary
The PrintWriter class in Java is part of the java.io package and is used to write formatted
text output to a file or console. It provides convenient methods to print data in a human-readable
form and supports automatic flushing.
Constructor:
The PrintWriter class has several constructors, which allow you to specify the output
destination.
java
Copy code
PrintWriter writer = new PrintWriter(OutputStream out);
PrintWriter writer = new PrintWriter(File file);
PrintWriter writer = new PrintWriter(String fileName);
PrintWriter writer = new PrintWriter(Writer writer);
1. print():
o Prints data (like System.out.print()), but without a newline at the end.
Example:
java
Copy code
PrintWriter writer = new PrintWriter(System.out);
writer.print("Hello ");
writer.print("World!");
writer.flush(); // Makes sure the output is printed immediately
2. println():
o Prints data followed by a newline.
Example:
java
Copy code
writer.println("This is a new line.");
writer.flush();
3. printf():
o Formats and prints text in a manner similar to System.out.printf().
Example:
java
Copy code
writer.printf("Name: %s, Age: %d%n", "Alice", 25);
writer.flush();
4. flush():
o Forces any buffered data to be written to the output destination.
Example:
java
Copy code
writer.flush(); // Ensures all data is written out
5. close():
o Closes the PrintWriter and releases any resources.
Example:
java
Copy code
writer.close();
6. checkError():
o Returns true if an error occurred while writing, otherwise false.
writer.print("Hello, ");
writer.println("World!");
writer.printf("The number is: %d%n", 100);
Output:
csharp
Copy code
Hello, World!
The number is: 100
writer.println("Hello, file!");
writer.printf("This is an integer: %d%n", 42);
vbnet
Copy code
Hello, file!
This is an integer: 42
1. Convenience: Provides methods like print(), println(), and printf() that simplify
writing formatted text.
2. Automatic Flushing: With the appropriate configuration, it automatically flushes the
stream whenever a newline character is written or when the buffer is full.
3. Flexible Output: Can write to various output streams, including files, system output, and
more.
4. Error Handling: You can check for errors using the checkError() method.
PrintWriter is ideal for writing formatted text and can write to files, console, or any
other output stream.
Always close the PrintWriter when done to release resources.
You can use flush() to immediately write buffered data to the output.
The PrintWriter class is a versatile tool for handling output in Java applications, especially
when you need to write human-readable text with formatting capabilities to various destinations
like the console or files.
In Java, strings are a sequence of characters used to represent text. Java provides powerful
classes and methods for working with strings, primarily through the String class and other
utility classes like StringBuilder and StringBuffer.
The String class in Java is part of the java.lang package and represents immutable sequences
of characters. Once a String object is created, it cannot be modified.
Immutable: Once created, the value of a String cannot be changed. Any operation that
modifies a string returns a new string.
Built-in Methods: The String class provides numerous methods for manipulating and
querying strings.
java
Copy code
String str = "Hello, World!";
int length = str.length(); // length = 13
charAt(int index): Returns the character at the specified index (index starts from 0).
Example:
java
Copy code
String str = "Hello";
char ch = str.charAt(1); // ch = 'e'
concat(String str): Concatenates the specified string to the end of the current string.
Example:
java
Copy code
String str1 = "Hello";
String str2 = " World!";
String result = str1.concat(str2); // result = "Hello World!"
Example:
java
Copy code
String str1 = "Hello";
String str2 = " World!";
String result = str1 + str2; // result = "Hello World!"
substring(int start): Returns a substring from the specified start index to the end of
the string.
substring(int start, int end): Returns a substring from the start index to the end
index (exclusive).
Example:
java
Copy code
String str = "Hello, World!";
String subStr = str.substring(7); // subStr = "World!"
String subStr2 = str.substring(0, 5); // subStr2 = "Hello"
Example:
java
Copy code
String str = "Hello, World!";
String upper = str.toUpperCase(); // "HELLO, WORLD!"
String lower = str.toLowerCase(); // "hello, world!"
Example:
java
Copy code
String str1 = "Hello";
String str2 = "hello";
boolean isEqual = str1.equals(str2); // false
boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2); // true
Example:
java
Copy code
String str = "Hello, World!";
boolean containsWorld = str.contains("World"); // true
java
Copy code
String str = " Hello, World! ";
String trimmed = str.trim(); // "Hello, World!"
Example:
java
Copy code
String str = "Hello, World!";
String replaced = str.replace("World", "Java"); // "Hello, Java!"
split(String regex): Splits the string into an array of substrings based on the given
regular expression.
Example:
java
Copy code
String str = "apple,banana,grape";
String[] fruits = str.split(","); // ["apple", "banana", "grape"]
StringBuilder:
StringBuffer:
Similar to StringBuilder but is synchronized, meaning it is thread-safe but slower
compared to StringBuilder.
append(String str): Adds the specified string to the end of the current string.
insert(int offset, String str): Inserts the specified string at the specified
position.
delete(int start, int end): Deletes characters from the string between the start and
end indices.
reverse(): Reverses the content of the string.
Java maintains a string pool (or string literal pool) to optimize memory usage. When a string is
created using a string literal, Java checks the string pool to see if that string already exists. If it
does, Java reuses the reference; if not, it creates a new string in the pool.
Interning:
You can manually add a string to the pool using the intern() method, which returns a
reference to the string from the pool.
Example:
java
Copy code
String str1 = "Hello";
String str2 = new String("Hello");
System.out.println(str1 == str2); // false (different references)
String str3 = str2.intern();
System.out.println(str1 == str3); // true (both refer to the same pool entry)
Java supports regular expressions (regex) for complex pattern matching in strings using
the Pattern and Matcher classes. Common methods include:
Conclusion
String handling in Java provides a variety of tools for working with text efficiently.
The String class is immutable and offers numerous methods for querying and modifying text.
When performance is a concern, especially with frequent string modifications, classes
like StringBuilder and StringBuffer provide mutable alternatives. Java also provides support
for string manipulation with regular expressions, making it highly flexible for various text-
processing tasks.
Exception Handling is a mechanism in Java to handle runtime errors, ensuring the normal flow
of the application. An exception is an event that disrupts the normal execution of a program.
Java provides a robust and flexible way to deal with such events through its exception handling
framework.
1. Exceptions:
o These are problems that occur during the execution of a program, such as file not
found, network failure, or invalid input.
2. Types of Exceptions:
o Checked Exceptions: Exceptions checked at compile-time. For
example, IOException, SQLException.
o Unchecked Exceptions: Exceptions that occur at runtime. For
example, NullPointerException, ArithmeticException.
o Errors: Problems that are beyond the control of the application, such
as OutOfMemoryError.
1. Try Block:
o Contains code that may throw an exception.
o If an exception occurs, it is passed to the catch block.
Example:
java
Copy code
try {
int result = 10 / 0; // May cause ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
2. Catch Block:
o Catches and handles exceptions thrown in the try block.
Example:
java
Copy code
catch (ExceptionType e) {
System.out.println("Exception occurred: " + e);
}
3. Finally Block:
o Always executes after try and catch, even if no exception occurred.
o Commonly used for cleanup actions like closing files or releasing resources.
Example:
java
Copy code
finally {
System.out.println("This block always executes.");
}
4. Throw Keyword:
o Used to explicitly throw an exception.
Example:
java
Copy code
throw new ArithmeticException("Arithmetic Exception thrown explicitly");
5. Throws Keyword:
o Used to declare exceptions that a method might throw.
Example:
java
Copy code
public void readFile() throws IOException {
// Code that might throw IOException
}
Examples
java
Copy code
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Exception: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}
}
Output:
vbnet
Copy code
Exception: / by zero
Finally block executed.
java
Copy code
public class MultipleExceptions {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out Of Bounds: " +
e.getMessage());
} catch (Exception e) {
System.out.println("General Exception: " + e.getMessage());
}
}
}
Output:
mathematica
Copy code
Array Index Out Of Bounds: Index 5 out of bounds for length 3
java
Copy code
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
Output:
php
Copy code
Caught Exception: Age must be at least 18.
java
Copy code
catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
Conclusion
Exception handling is a vital feature in Java for building robust and error-resilient applications.
By properly using try, catch, finally, and other related keywords, you can manage exceptions
effectively and ensure smooth execution of your program.
Thread:
A thread in Java is the smallest unit of a program that can execute independently. A program in
Java starts with a single thread called the main thread.
Multithreading:
Multithreading is a feature in Java that allows the concurrent execution of two or more threads
within a program. It enables multiple tasks to run simultaneously, making applications more
efficient and responsive.
1. Thread Class:
Java provides the Thread class in the java.lang package to create and manage threads.
2. Runnable Interface:
The Runnable interface is a functional interface that represents a task that can be
executed by a thread.
3. Thread States: Threads can be in one of the following states:
o New: A thread that has been created but not started.
o Runnable: A thread that is ready to run but waiting for CPU time.
o Running: A thread that is currently executing.
o Blocked/Waiting: A thread waiting for a resource or another thread.
o Terminated: A thread that has completed execution.
Steps:
Example:
java
Copy code
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running: " +
Thread.currentThread().getName());
}
}
Steps:
Example:
java
Copy code
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running: " +
Thread.currentThread().getName());
}
}
Thread Methods
Method Description
start() Starts the thread and invokes the run() method.
run() Contains the code to be executed by the thread.
sleep(long millis) Makes the thread pause execution for a specified time.
join() Waits for a thread to complete before proceeding.
isAlive() Checks if the thread is alive.
getName() / setName() Gets or sets the thread name.
setPriority(int value) Sets the priority of a thread (1 to 10).
yield() Pauses the current thread to allow other threads to execute.
Multithreading Example
java
Copy code
class MyRunnable implements Runnable {
private String name;
t1.start();
t2.start();
t3.start();
}
}
Output:
arduino
Copy code
Thread 1 is running: 1
Thread 2 is running: 1
Thread 3 is running: 1
Thread 1 is running: 2
...
Thread Synchronization
In multithreaded programming, when multiple threads access shared resources (e.g., variables or
files), it can lead to race conditions. Synchronization ensures that only one thread can access a
shared resource at a time.
Example:
java
Copy code
class Counter {
private int count = 0;
t1.start();
t2.start();
t1.join();
t2.join();
Output:
yaml
Copy code
Final count: 2000
Inter-thread Communication
Java provides methods like wait(), notify(), and notifyAll() to facilitate communication
between threads.
Example:
java
Copy code
class SharedResource {
private int value = 0;
private boolean available = false;
producer.start();
consumer.start();
}
}
Output:
makefile
Copy code
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
...
Advantages of Multithreading
1. Better CPU Utilization: Threads allow multiple tasks to run concurrently, using CPU
cycles efficiently.
2. Faster Execution: Multiple threads can execute tasks in parallel, reducing execution
time.
3. Improved User Experience: Background threads prevent blocking the main thread,
improving responsiveness.
Disadvantages of Multithreading
The thread lifecycle describes the various states a thread can go through during its execution. A
thread transitions through these states based on the actions performed by the thread and the
thread scheduler.
Thread States
1. New State
o A thread is in the New state when it is created but not started.
o At this stage, the thread object is initialized, but it is not executing yet.
Code Example:
java
Copy code
Thread t = new Thread(); // Thread is in the New state
Key Method:
Code Example:
java
Copy code
t.start(); // Thread is now Runnable
Note:
The thread does not immediately start executing; it depends on the thread scheduler to
allocate CPU time.
3. Running State
o When the thread is assigned CPU time, it moves to the Running state and
executes its run() method.
Code Example:
java
Copy code
public void run() {
System.out.println("Thread is running");
}
Transition to Running:
o A thread in the Runnable state becomes Running when the thread scheduler
selects it for execution.
Code Example:
java
Copy code
try {
Thread.sleep(1000); // Thread is in Timed Waiting state
} catch (InterruptedException e) {
e.printStackTrace();
}
Code Example:
java
Copy code
public void run() {
System.out.println("Thread has finished execution.");
}
Key Point:
The following example demonstrates the transitions of a thread through various states:
java
Copy code
class MyThread extends Thread {
public void run() {
System.out.println("Thread is Running");
try {
Thread.sleep(1000); // Thread goes into Timed Waiting state
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
System.out.println("Thread is now Terminated");
}
}
try {
Thread.sleep(500);
System.out.println("Thread State after sleep(): " +
t1.getState());
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
t1.join(); // Wait for thread to finish
} catch (InterruptedException e) {
e.printStackTrace();
}
Output:
mathematica
Copy code
Thread State: NEW
Thread State after start(): RUNNABLE
Thread is Running
Thread State after sleep(): TIMED_WAITING
Thread is now Terminated
Thread State after termination: TERMINATED
Conclusion
The thread lifecycle in Java provides a systematic way to understand the various states a thread
can go through. By managing thread states effectively, developers can write robust and efficient
multithreaded programs.
Unit-III
Exploring Java Language, Collection Overview, Collections Interfaces, Collection Classes,
Iterators, Random Access Interface, Maps, Comparators, Arrays, Legacy classes and
Interfaces, String Tokenizer, Bit Set, Date, Calendar observable, Timer.
1.
oJava achieves high performance through Just-In-Time (JIT) compilers that
optimize bytecode at runtime.
2. Distributed:
o Java supports networked applications using its built-in APIs like Remote Method
Invocation (RMI) and CORBA.
The Java Development Kit (JDK) is a collection of tools required for Java programming. It
includes:
The Java Runtime Environment (JRE) provides the environment to run Java applications. It
includes:
The JVM is the core of Java’s "write once, run anywhere" principle. It:
java
Copy code
// Java program to print "Hello, World!"
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Explanation:
Java is a statically typed language, meaning every variable must have a declared data type.
1. Decision-Making:
o if, if-else, switch
java
Copy code
if (age > 18) {
System.out.println("Eligible to vote.");
} else {
System.out.println("Not eligible.");
}
2. Looping:
o for, while, do-while
java
Copy code
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
3. Branching:
o break, continue
java
Copy code
for (int i = 1; i <= 5; i++) {
if (i == 3) continue; // Skip iteration when i is 3
System.out.println(i);
}
Object-Oriented Concepts
Java is a pure object-oriented language, meaning everything revolves around objects and
classes.
Key Concepts:
java
Copy code
class Car {
String brand;
int year;
}
java
Copy code
Car car = new Car();
3. Inheritance: Allows one class to inherit fields and methods from another class.
java
Copy code
class Vehicle {
void run() {
System.out.println("Vehicle is running");
}
}
Java Packages
Java provides a large library of packages to reuse pre-written code, such as:
1. java.util: Utility classes like ArrayList, HashMap.
2. java.io: Input and Output classes.
3. java.net: Networking classes.
4. java.sql: Classes for database interaction.
Creating a Package:
java
Copy code
package mypackage;
Java APIs
The Java API is a collection of classes and interfaces for tasks like:
Advantages of Java
Java Applications
1. Desktop Applications:
o Swing, JavaFX for GUI-based applications.
2. Web Applications:
o Servlets, JSP, and frameworks like Spring, Hibernate.
3. Mobile Applications:
o Android development is primarily done using Java.
4. Enterprise Applications:
o Java is widely used for large-scale enterprise systems.
5. Scientific Applications:
o Java is preferred for its precision and reliability.
1. Unified Architecture:
o All collections (e.g., List, Set, Map) share a common set of methods and
properties.
2. Performance:
o Optimized implementations of common data structures and algorithms.
3. Flexibility:
o Provides a wide range of implementations and allows customization.
4. Thread Safety:
o Supports thread-safe versions of collections
(e.g., Collections.synchronizedList()).
5. Generics Support:
o Enables type safety and reduces runtime errors.
Collection Interfaces
Interface Description
Collection The root interface for most collection types (e.g., List, Set, Queue).
List Ordered collection that allows duplicate elements (e.g., ArrayList, LinkedList).
Set
Unordered collection that does not allow duplicate elements
(e.g., HashSet, TreeSet).
Map Collection of key-value pairs (e.g., HashMap, TreeMap).
Interface Description
Queue Ordered collection for holding elements prior to processing (e.g., PriorityQueue).
Deque
Double-ended queue that allows insertion and removal from both ends
(e.g., ArrayDeque).
List
1. ArrayList:
o Resizable array implementation.
o Fast random access but slower for insertion/deletion.
Example:
java
Copy code
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.forEach(System.out::println);
2. LinkedList:
o Doubly linked list implementation.
o Faster insertion/deletion, slower random access.
Example:
java
Copy code
List<Integer> linkedList = new LinkedList<>();
linkedList.add(10);
linkedList.add(20);
Set
1. HashSet:
o Uses a hash table for storage.
o No order is guaranteed, and duplicates are not allowed.
Example:
java
Copy code
Set<String> set = new HashSet<>();
set.add("A");
set.add("B");
2. TreeSet:
o Implements Set using a tree structure.
o Maintains elements in sorted order.
Example:
java
Copy code
Set<Integer> treeSet = new TreeSet<>();
treeSet.add(5);
treeSet.add(1);
Map
1. HashMap:
o Stores key-value pairs.
o Allows one null key and multiple null values.
Example:
java
Copy code
Map<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
2. TreeMap:
o Sorted map implementation.
o Keys are maintained in ascending order.
Example:
java
Copy code
Map<String, Integer> treeMap = new TreeMap<>();
treeMap.put("A", 1);
treeMap.put("B", 2);
Queue
1. PriorityQueue:
o A queue where elements are ordered based on priority.
Example:
java
Copy code
Queue<Integer> pq = new PriorityQueue<>();
pq.add(10);
pq.add(5);
2. ArrayDeque:
o Implementation of a double-ended queue.
Example:
java
Copy code
Deque<String> deque = new ArrayDeque<>();
deque.addFirst("First");
deque.addLast("Last");
Generics in Collections
Generics provide type safety to collections by defining the type of elements they can hold.
java
Copy code
List list = new ArrayList();
list.add("Hello");
list.add(123); // Allowed but can cause runtime errors
java
Copy code
List<String> list = new ArrayList<>();
list.add("Hello");
// list.add(123); // Compile-time error
The Collections class provides utility methods for working with collections.
1. Sorting:
java
Copy code
List<Integer> numbers = Arrays.asList(5, 2, 8, 1);
Collections.sort(numbers);
2. Searching:
java
Copy code
int index = Collections.binarySearch(numbers, 2);
3. Thread-Safe Collections:
java
Copy code
List<String> synchronizedList = Collections.synchronizedList(new
ArrayList<>());
Conclusion
The Java Collections Framework is a powerful set of tools that simplifies data management in
Java programs. It provides flexible, efficient, and reusable data structures that suit various
application needs, from simple tasks to complex operations. Mastering collections is essential for
writing robust and maintainable Java applications.
1. Collection Interface
Definition:
The Collection interface is the root interface of the Java Collections Framework. It
represents a group of objects, known as elements, and defines the basic methods that all
collections must implement.
Key Methods:
Method Description
add(E e) Adds an element to the collection.
remove(Object o) Removes a specified element from the collection.
size() Returns the number of elements in the collection.
isEmpty() Checks if the collection is empty.
contains(Object o) Checks if the collection contains a specific element.
clear() Removes all elements from the collection.
Example:
java
Copy code
Collection<String> collection = new ArrayList<>();
collection.add("Java");
collection.add("Python");
System.out.println(collection.size()); // Output: 2
2. List Interface
Definition:
The List interface extends Collection and represents an ordered collection of elements.
It allows duplicate elements and provides methods for positional access and
manipulation.
Implementations:
o ArrayList
o LinkedList
o Vector
Key Methods:
Method Description
get(int index) Returns the element at the specified position.
add(int index, E e) Inserts an element at the specified position.
remove(int index) Removes the element at the specified position.
indexOf(Object o) Returns the index of the first occurrence of the element.
subList(int from, int to) Returns a view of a portion of the list.
Example:
java
Copy code
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add(1, "Grapes");
System.out.println(list); // Output: [Apple, Grapes, Banana]
3. Set Interface
Definition:
The Set interface extends Collection and represents a collection that does not allow
duplicate elements. It is based on mathematical set theory.
Implementations:
o HashSet
o LinkedHashSet
o TreeSet
Key Features:
o No duplicate elements are allowed.
o HashSet does not maintain any order.
o LinkedHashSet maintains insertion order.
o TreeSet maintains elements in sorted order.
Example:
java
Copy code
Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.add(2); // Duplicate, will not be added
System.out.println(set); // Output: [1, 2]
4. Queue Interface
Definition:
The Queue interface extends Collection and represents a collection designed for
holding elements before processing. It follows the FIFO (First In, First Out) principle.
Implementations:
o PriorityQueue
o ArrayDeque
Key Methods:
Method Description
add(E e) Inserts the specified element into the queue.
offer(E e) Inserts an element, returning false if capacity is full.
poll() Retrieves and removes the head of the queue.
peek() Retrieves, but does not remove, the head of the queue.
Example:
java
Copy code
Queue<String> queue = new LinkedList<>();
queue.add("Task1");
queue.add("Task2");
System.out.println(queue.poll()); // Output: Task1
5. Deque Interface
Definition:
The Deque interface extends Queue and represents a double-ended queue, allowing
elements to be added or removed from both ends.
Implementations:
o ArrayDeque
o LinkedList
Key Methods:
Method Description
addFirst(E e) Inserts an element at the front.
addLast(E e) Inserts an element at the end.
removeFirst() Removes the first element.
removeLast() Removes the last element.
Example:
java
Copy code
Deque<String> deque = new ArrayDeque<>();
deque.addFirst("Start");
deque.addLast("End");
System.out.println(deque); // Output: [Start, End]
6. Map Interface
Definition:
The Map interface represents a collection of key-value pairs. Each key maps to exactly
one value, and duplicate keys are not allowed.
Implementations:
o HashMap
o LinkedHashMap
o TreeMap
o Hashtable
Key Methods:
Method Description
put(K key, V value) Associates the specified value with the key.
get(Object key) Returns the value associated with the key.
remove(Object key) Removes the mapping for the specified key.
containsKey(Object key) Checks if the map contains the specified key.
Example:
java
Copy code
Map<String, Integer> map = new HashMap<>();
map.put("One", 1);
map.put("Two", 2);
System.out.println(map.get("One")); // Output: 1
Extended Interfaces
1. SortedSet Interface
Extends Set.
Maintains elements in a natural or custom order.
Implementation: TreeSet.
2. SortedMap Interface
Extends Map.
Maintains keys in a sorted order.
Implementation: TreeMap.
3. NavigableSet Interface
4. NavigableMap Interface
Conclusion
The Java Collections Framework provides a robust and flexible set of interfaces to handle
different types of data structures efficiently. Each interface is designed for specific use cases,
ensuring optimal performance and ease of development. Understanding these interfaces is
essential for mastering Java programming.
java
Copy code
import java.util.*;
java
Copy code
ArrayList<String> list = new ArrayList<>();
3. Add Elements
Use methods like add() or put() to populate the collection.
java
Copy code
list.add("Java");
list.add("Python");
4. Perform Operations
Use provided methods for accessing, modifying, or iterating over elements.
java
Copy code
list.get(0); // Retrieve the first element
list.remove(1); // Remove the second element
java
Copy code
for (String item : list) {
System.out.println(item);
}
Detailed Explanation of Collection Classes and Examples
1. ArrayList Class
Definition: A resizable array implementation of the List interface that allows duplicate
elements and maintains insertion order.
Steps:
1. Import the ArrayList class from java.util.
2. Create an ArrayList object.
3. Add elements using the add() method.
4. Perform operations like get(), remove(), and size().
Example:
java
Copy code
import java.util.ArrayList;
2. LinkedList Class
Definition: A doubly linked list implementation of the List and Deque interfaces,
efficient for frequent insertions and deletions.
Steps:
1. Import the LinkedList class.
2. Create a LinkedList object.
3. Add elements using add(), addFirst(), or addLast().
4. Perform operations like removeFirst(), getFirst(), and iteration.
Example:
java
Copy code
import java.util.LinkedList;
3. HashSet Class
Definition: A hash table-based implementation of the Set interface, used for storing
unique elements.
Steps:
1. Import the HashSet class.
2. Create a HashSet object.
3. Add elements using add() method.
4. Perform operations like remove() and contains().
Example:
java
Copy code
import java.util.HashSet;
4. HashMap Class
Definition: A hash table-based implementation of the Map interface for storing key-value
pairs.
Steps:
1. Import the HashMap class.
2. Create a HashMap object.
3. Add key-value pairs using the put() method.
4. Perform operations like get(), remove(), and containsKey().
Example:
java
Copy code
import java.util.HashMap;
5. PriorityQueue Class
Definition: A queue implementation that orders its elements based on natural ordering or
a custom comparator.
Steps:
1. Import the PriorityQueue class.
2. Create a PriorityQueue object.
3. Add elements using add() or offer() methods.
4. Retrieve elements using peek() or poll().
Example:
java
Copy code
import java.util.PriorityQueue;
public class PriorityQueueExample {
public static void main(String[] args) {
// Step 2: Create a PriorityQueue
PriorityQueue<Integer> queue = new PriorityQueue<>();
Summary
These collection classes provide efficient and flexible data management in Java programs
Iterators in Java
Definition: An Iterator is an object in Java that provides a way to traverse through a collection
sequentially without exposing its internal structure. It is part of the java.util package and
supports operations like reading and removing elements during iteration.
java
Copy code
import java.util.*;
2. Create a Collection
Initialize a collection object (e.g., ArrayList, HashSet, LinkedList).
3. Get an Iterator
Call the iterator() method on the collection to get an Iterator object.
4. Traverse Using the Iterator
Use a while loop with hasNext() to check for elements and next() to retrieve them.
5. Optional: Remove Elements
Use the remove() method to safely remove elements during traversal.
java
Copy code
import java.util.ArrayList;
import java.util.Iterator;
Output:
mathematica
Copy code
Using Iterator:
Java
Python
C++
java
Copy code
import java.util.ArrayList;
import java.util.Iterator;
while (iterator.hasNext()) {
String language = iterator.next();
if (language.equals("Python")) {
iterator.remove(); // Safely remove element during iteration
}
}
Output:
mathematica
Copy code
Updated List: [Java, C++]
java
Copy code
import java.util.HashSet;
import java.util.Iterator;
System.out.println("HashSet Elements:");
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
Output:
yaml
Copy code
HashSet Elements:
1
2
3
Limitations of Iterator
ListIterator
Definition: A specialized iterator available for List collections (e.g., ArrayList, LinkedList)
that supports bidirectional traversal and element modification.
Method Description
boolean hasPrevious() Returns true if there are elements when traversing backward.
E previous() Returns the previous element in the list.
void add(E e) Inserts the specified element into the list.
void set(E e) Replaces the last element returned by next() or previous().
Example of ListIterator
java
Copy code
import java.util.ArrayList;
import java.util.ListIterator;
System.out.println("Forward Traversal:");
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}
System.out.println("Backward Traversal:");
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
}
}
Output:
mathematica
Copy code
Forward Traversal:
Java
Python
C++
Backward Traversal:
C++
Python
Java
Summary
Iterators are essential for working with Java collections in a consistent and safe manner. They
simplify operations like traversal and modification while ensuring encapsulation of the
collection's internal structure.
Random Access in Java:
In Java, random access refers to the ability to access data at any position in a file without having
to process it sequentially from the beginning. This is especially useful when working with large
files or datasets where only specific portions of data need to be read or modified. Java provides
this functionality using the RandomAccessFile class in the java.io package.
What is RandomAccessFile?
RandomAccessFile is a specialized Java class that allows you to read and write data to a file in a
non-sequential (random) manner. Unlike standard file handling classes
like FileReader and FileWriter, which work sequentially, RandomAccessFile allows jumping
directly to any part of the file using file pointers.
A file pointer is an internal marker that tracks the current read/write position within the file. You
can manually move this pointer to any position, enabling efficient file operations.
Features of RandomAccessFile
Constructor of RandomAccessFile
java
Copy code
RandomAccessFile(String fileName, String mode) throws IOException
Below is an example demonstrating how to use RandomAccessFile for random file access.
java
Copy code
import java.io.*;
makefile
Copy code
Message: Hello, World!
Number: 42
Pi: 3.14
Additionally, the file content will be modified to replace the integer 42 with 100.
Advantages of RandomAccessFile
Disadvantages of RandomAccessFile
1. Complexity: Managing file pointers and data types can be tricky.
2. Limited to File Systems: Cannot be used with non-file data streams.
3. Platform Dependency: File operations may behave differently on different platforms.
Applications of RandomAccessFile
Maps in Java
In Java, a Map is an interface in the java.util package that represents a collection of key-value
pairs. It is part of the Java Collections Framework. Unlike other collection interfaces
like List or Set, a Map does not extend the Collectioninterface. Maps are used when you need
to associate keys with values and ensure fast lookups based on keys.
1. Key-Value Pairs:
o Each entry in a Map consists of a key and a corresponding value (key => value).
o Keys are unique, but values can be duplicated.
2. Efficient Lookup:
o Maps provide efficient access to values using their keys.
3. No Fixed Order:
o The order of elements in a Map depends on the specific implementation
(e.g., HashMap is unordered, while LinkedHashMap maintains insertion order).
4. Null Keys and Values:
o Some implementations (e.g., HashMap) allow one null key and
multiple null values.
1. HashMap:
o Allows one null key and multiple null values.
o Does not maintain any order.
o Fast for most operations due to hashing.
2. LinkedHashMap:
o Maintains insertion order.
o Slightly slower than HashMap because of the additional ordering overhead.
3. TreeMap:
o Stores keys in sorted (natural or custom) order.
o Does not allow null keys but allows multiple null values.
4. Hashtable:
o Legacy implementation.
o Synchronized and thread-safe, but slower than modern alternatives
like ConcurrentHashMap.
5. ConcurrentHashMap:
o Thread-safe and designed for concurrent access in multithreaded environments.
1. Basic Operations
2. Bulk Operations
putAll(Map<? extends K, ? extends V> m): Copies all entries from another map.
clear(): Removes all entries from the map.
3. Views
// Remove an entry
map.remove("Banana");
System.out.println("After removing 'Banana': " + map);
Advantages of Maps
Disadvantages of Maps
1. Memory Overhead:
o Uses more memory due to the need to store keys and values.
2. Iteration Complexity:
o Iterating over a map can be less efficient than a list or set.
Comparators in Java
A Comparator in Java is an interface in the java.util package that provides a way to define
custom comparison logic for objects. It is commonly used for sorting collections or arrays of
objects when the natural ordering (defined by the Comparable interface) is not sufficient or not
desired.
Purpose of Comparator
1. Custom Sorting:
o It allows defining multiple sorting orders for a single class (e.g., sort by name,
age, or salary for an Employeeobject).
2. Flexibility:
o Unlike the Comparable interface, which requires modifying the class
itself, Comparator provides sorting logic separately.
1. Custom Logic: You can define custom comparison logic independent of the class.
2. Functional Interface: As of Java 8, Comparator is a functional interface, so you can use
lambda expressions or method references to implement it.
3. Multiple Comparisons: You can chain multiple comparison criteria using methods
like thenComparing().
Comparator Interface
java
Copy code
int compare(T o1, T o2);
Comparator vs Comparable
java
Copy code
import java.util.*;
class Employee {
String name;
int age;
double salary;
@Override
public String toString() {
return name + " (Age: " + age + ", Salary: " + salary + ")";
}
}
System.out.println("Sorted by age:");
for (Employee e : employees) {
System.out.println(e);
}
Output
less
Copy code
Sorted by age:
Bob (Age: 25, Salary: 50000.0)
Alice (Age: 30, Salary: 70000.0)
Charlie (Age: 35, Salary: 80000.0)
1. Using thenComparing()
Allows sorting by multiple criteria. For example, sort by age, then by name:
java
Copy code
employees.sort(Comparator.comparingInt(Employee::getAge)
.thenComparing(Employee::getName));
Instead of a lambda, you can use method references for concise code:
java
Copy code
employees.sort(Comparator.comparing(Employee::getName));
3. Reverse Order
java
Copy code
employees.sort(Comparator.comparingDouble(Employee::getSalary).reversed());
When to Use Comparator?
Arrays in Java
Arrays are among the most fundamental and widely used data structures in Java programming.
Here's an expanded and more detailed explanation, including examples, diagrams, and
applications.
1. What is an Array?
An array is a container object in Java that can hold a fixed number of values of the same data
type. It provides an easy way to store and manage large collections of data in a structured format.
Key Characteristics:
Declaration:
java
Copy code
dataType[] arrayName; // Recommended syntax
dataType arrayName[]; // Also valid but less common
Initialization:
java
Copy code
int[] primes = {2, 3, 5, 7, 11}; // Automatically creates an array of
size 5
Access:
java
Copy code
int firstPrime = primes[0]; // Access the first element
primes[2] = 17; // Update the third element
3. Types of Arrays
Example:
java
Copy code
int[] arr = {10, 20, 30, 40, 50};
Visualization:
Index 0 1 2 3 4
Value 10 20 30 40 50
Example:
java
Copy code
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Visualization:
Index 0 1 2
0 1, 2, 3
1 4, 5, 6
2 7, 8, 9
A special type of multi-dimensional array where rows can have different lengths.
Example:
java
Copy code
int[][] jaggedArray = {
{1, 2},
{3, 4, 5},
{6}
};
Visualization:
Row 0: {1, 2}
Row 1: {3, 4, 5}
Row 2: {6}
4. Array Operations
1. for loop:
java
Copy code
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
2. Enhanced for loop:
java
Copy code
for (int num : arr) {
System.out.println(num);
}
1. Manual Copying:
java
Copy code
int[] copy = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
copy[i] = arr[i];
}
2. Using System.arraycopy():
java
Copy code
System.arraycopy(source, 0, destination, 0, source.length);
3. Using Arrays.copyOf():
java
Copy code
int[] copy = Arrays.copyOf(arr, arr.length);
java
Copy code
int[] arr = {5, 2, 8, 1};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); // Output: [1, 2, 5, 8]
java
Copy code
int index = Arrays.binarySearch(arr, 5);
if (index >= 0) {
System.out.println("Found at index: " + index);
} else {
System.out.println("Not found.");
}
java
Copy code
int[] arr = {5, 8, 12, 3};
int max = arr[0];
for (int num : arr) {
if (num > max) {
max = num;
}
}
System.out.println("Maximum: " + max);
java
Copy code
int[] arr = {1, 2, 3, 4};
for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
System.out.println(Arrays.toString(arr)); // Output: [4, 3, 2, 1]
6. Advantages of Arrays
7. Limitations of Arrays
1. Fixed Size:
o Cannot resize once initialized. Use ArrayList or LinkedList for dynamic
resizing.
2. Insertion/Deletion Overhead:
o Shifting elements is required for these operations.
3. Single Data Type:
o Cannot store mixed data types.
8. Applications of Arrays
1. Data Representation:
o Storing scores, records, or sensor data.
2. Matrix Operations:
o Representing mathematical matrices for scientific calculations.
3. Sorting and Searching Algorithms:
o Bubble Sort, Quick Sort, Binary Search, etc.
4. Game Development:
o Grids for board games like Tic-Tac-Toe.
5. Dynamic Programming:
o Arrays are widely used in optimization problems.
Output:
yaml
Copy code
Matrix:
1 2 3
4 5 6
7 8 9
Sum of all elements: 45
Legacy classes and interfaces in Java refer to the components introduced in earlier versions of
Java (primarily before Java 2 Collections Framework). These were part of
the java.util package and were later replaced or enhanced by the modern Java Collections
Framework (JCF) introduced in Java 2 (JDK 1.2). However, they are still retained for backward
compatibility.
1. Hashtable
Description: A synchronized, key-value data structure used for storing and accessing
data.
Replacement: Mostly replaced by HashMap and ConcurrentHashMap in the modern
Collections Framework.
Key Points:
o Keys and values cannot be null.
o Thread-safe but less efficient than HashMap.
Example:
java
Copy code
import java.util.Hashtable;
2. Vector
Example:
java
Copy code
import java.util.Vector;
3. Stack
Example:
java
Copy code
import java.util.Stack;
4. Enumeration
Example:
java
Copy code
import java.util.Enumeration;
import java.util.Vector;
1. Dictionary
2. Properties
Example:
java
Copy code
import java.util.Properties;
StringTokenizer in Java
The StringTokenizer class in Java is part of the java.util package. It is used to break a string
into tokens (substrings) based on specified delimiters. Introduced in the early versions of Java, it
has been largely replaced by more modern approaches like the split() method in
the String class or using the Scanner class. However, StringTokenizer is still useful in
specific scenarios.
Constructors of StringTokenizer
1. Default Constructor:
java
Copy code
StringTokenizer(String str)
oSplits the string using default delimiters: spaces, tabs, newline (" \t\n\r\f").
2. Custom Delimiter:
java
Copy code
StringTokenizer(String str, String delimiter)
java
Copy code
StringTokenizer(String str, String delimiter, boolean returnDelims)
o If returnDelims is true, the delimiters are treated as tokens.
Methods in StringTokenizer
Method Description
boolean hasMoreTokens() Checks if there are more tokens available.
String nextToken() Returns the next token in the string.
String nextToken(String
delim) Returns the next token using a new delimiter.
int countTokens()
Returns the total number of tokens in the string. (Only for
unprocessed tokens.)
Basic Example
java
Copy code
import java.util.StringTokenizer;
System.out.println("Tokens:");
while (tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken());
}
}
}
Output:
makefile
Copy code
Tokens:
Java
Python
C++
JavaScript
System.out.println("Tokens:");
while (tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken());
}
}
}
Output:
makefile
Copy code
Tokens:
Java
Python
C++
JavaScript
Output:
mathematica
Copy code
Tokens (including delimiters):
Java
,
Python
|
C++
System.out.println("Tokens:");
for (String token : tokens) {
System.out.println(token);
}
}
}
Output:
makefile
Copy code
Tokens:
Java
Python
C++
JavaScript
Advantages of StringTokenizer
1. Simple and Fast: Ideal for simple tokenization without requiring regex.
2. Backward Compatibility: Useful for working with legacy code.
3. Handles Multiple Delimiters: Efficiently manages tokenization with various delimiters.
Disadvantages of StringTokenizer
1. Less Flexible: Does not support complex delimiter patterns like regex.
2. Deprecated in Practice: Modern methods (String.split(), Scanner) are more widely
used.
3. Immutable String Requirement: Cannot modify the original string.
BitSet in Java
The BitSet class is part of the java.util package and represents a bit array or bit vector. It
allows you to store a collection of bits (binary values: true or false) efficiently. Each bit can be
either 0 or 1, and you can perform bitwise operations on them.
Constructor
java
Copy code
BitSet bitSet = new BitSet();
Method Description
set(int bitIndex) Sets the bit at the specified index to true.
set(int bitIndex, boolean Sets the bit at the specified index to the given boolean value
value) (true or false).
get(int bitIndex)
Returns the value of the bit at the specified index
(true or false).
clear(int bitIndex) Clears the bit at the specified index (sets it to false).
clear(int fromIndex, int Clears the bits from fromIndex (inclusive)
toIndex) to toIndex (exclusive).
flip(int bitIndex)
Flips the bit at the specified index (true becomes false and
vice versa).
flip(int fromIndex, int Flips all the bits in the specified range
toIndex) from fromIndex to toIndex.
and(BitSet set)
Performs a bitwise AND operation between the
current BitSet and the specified BitSet.
or(BitSet set)
Performs a bitwise OR operation between the
current BitSet and the specified BitSet.
xor(BitSet set)
Performs a bitwise XOR operation between the
current BitSet and the specified BitSet.
not() Inverts all bits in the BitSet.
length()
Returns the length of the BitSet, which is the index of the
highest bit set to true + 1.
size() Returns the number of bits in the BitSet (its capacity).
cardinality() Returns the number of bits set to true in the BitSet.
isEmpty()
Returns true if the BitSet is empty (no bits are set to true),
otherwise false.
java
Copy code
import java.util.BitSet;
Output:
yaml
Copy code
BitSet: {0, 2, 4}
Bit at index 2: true
Bit at index 1: false
2. Flipping Bits
java
Copy code
public class FlipBitsExample {
public static void main(String[] args) {
BitSet bitSet = new BitSet(10);
Output:
css
Copy code
Original BitSet: {1, 3, 5}
After flipping bit at index 3: {1, 5}
After flipping bits from index 1 to 5: {3, 4}
3. Bitwise Operations
java
Copy code
public class BitwiseOperationsExample {
public static void main(String[] args) {
BitSet bitSet1 = new BitSet(8);
BitSet bitSet2 = new BitSet(8);
bitSet2.set(2);
bitSet2.set(3);
bitSet2.set(6);
// AND operation
bitSet1.and(bitSet2);
System.out.println("AND result: " + bitSet1);
// OR operation
bitSet1.or(bitSet2);
System.out.println("OR result: " + bitSet1);
// XOR operation
bitSet1.xor(bitSet2);
System.out.println("XOR result: " + bitSet1);
}
}
Output:
css
Copy code
BitSet1: {1, 3, 5}
BitSet2: {2, 3, 6}
AND result: {3}
OR result: {1, 2, 3, 5, 6}
XOR result: {1, 2, 5, 6}
Method Descriptions
1. Compact Memory Representation: It efficiently uses memory for storing binary data.
2. Bitwise Operations: Supports fast and efficient bitwise operations like AND, OR, XOR,
and NOT.
3. Dynamic Sizing: It grows dynamically as you set more bits.
4. Efficient for Flag Management: Ideal for managing flags or binary states in an
application.
Limitations of BitSet
1. No Direct Support for Non-Binary Data: Only supports boolean true/false values.
2. Not Thread-Safe: BitSet is not synchronized, so you need to handle synchronization
manually in multithreaded environments.
3. Performance: While BitSet is more memory-efficient than arrays, operations on very
large sets might still be slow.
Conclusion
BitSet is a useful data structure when you need to work with a collection of bits, perform
bitwise operations, or manage binary flags efficiently. While it is not as widely used as other
collection types like ArrayList, it still has specific use cases where its bit-level operations make
it an ideal choice.
Constructors of Date
1. Date(): Constructs a Date object that represents the current date and time.
java
Copy code
Date date = new Date();
2. Date(long date): Constructs a Date object representing the date and time represented
by the specified millisecond value (since January 1, 1970, 00:00:00 GMT).
java
Copy code
Date date = new Date(1623648000000L); // Specific time in milliseconds
3. Date(int year, int month, int day): Deprecated constructor that creates
a Date object using a specified year, month, and day.
java
Copy code
Date date = new Date(2024, 5, 15); // Deprecated, use Calendar or
LocalDate instead
Method Description
getTime() Returns the time (in milliseconds) represented by the Date object.
setTime(long time) Sets the time of the Date object using the given milliseconds.
getYear() Deprecated. Returns the year (relative to 1900).
getMonth() Deprecated. Returns the month (0-11, where 0 is January).
getDate() Returns the day of the month (1-31).
getHours() Returns the hours of the day (0-23).
getMinutes() Returns the minutes (0-59).
getSeconds() Returns the seconds (0-59).
before(Date when) Returns true if the current Date is before the specified Date.
Method Description
after(Date when) Returns true if the current Date is after the specified Date.
equals(Object obj) Returns true if the current Date is equal to the specified Date.
compareTo(Date Compares two Date objects. Returns negative if before, positive if
anotherDate) after, and 0 if equal.
toString() Returns a string representation of the Date object.
java
Copy code
import java.util.Date;
Output:
sql
Copy code
Current Date and Time: Mon Dec 03 13:45:12 IST 2024
java
Copy code
import java.util.Date;
Output:
sql
Copy code
Current Time in Milliseconds: 1607455607000
Updated Date: Tue Jun 15 05:30:00 IST 2021
java
Copy code
import java.util.Date;
Output:
vbnet
Copy code
Is date1 after date2? true
Is date1 before date2? false
Are date1 and date2 equal? false
Although the following methods are deprecated, they are still functional in legacy code:
java
Copy code
import java.util.Date;
sql
Copy code
Year: 2024
Month: 6
Day of the month: 15
5. toString() Method
java
Copy code
import java.util.Date;
Output:
javascript
Copy code
Date String Representation: Mon Dec 03 13:45:12 IST 2024
1. Mutability: The Date class is mutable, meaning the date can be changed after the object
is created. This can lead to potential issues when dates are shared between different parts
of a program.
2. Deprecated Methods: Many of its methods (getYear(), getMonth(), getDate()) are
deprecated in favor of newer classes like Calendar, LocalDate, LocalDateTime,
and Instant.
3. Lack of Time Zone Management: The Date class does not handle time zones well. For
better time zone handling, use ZonedDateTime in Java 8 or newer.
In Java, Calendar and Observable are two separate concepts, but they are both part of
the java.util package. Let me explain each in detail and then how they might interact in a real-
world scenario.
1. Calendar Class
The Calendar class is an abstract class that provides methods for manipulating and working with
dates and times. It is part of the java.util package and was introduced as a replacement for the
outdated Date class to handle date and time calculations.
The Calendar class provides methods to manipulate dates, like adding or subtracting days,
months, and years, as well as getting specific components of a date (such as year, month, day,
hour, minute, etc.).
Method Description
get(int field)
Gets the value of the given field
(like Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH).
set(int field, int
value) Sets the value for the given field (like set(Calendar.YEAR, 2024)).
add(int field, int Adds or subtracts a given amount to the specified field
amount) (e.g., add(Calendar.DAY_OF_MONTH, 5)).
roll(int field, int Similar to add(), but it doesn't affect higher fields (e.g., adding 1 to
amount) the month).
getTime() Returns a Date object representing the current calendar time.
getTimeInMillis()
Returns the time as a long value (milliseconds since January 1, 1970,
00:00:00 GMT).
setTime(Date date) Sets the calendar’s time to the specified Date object.
getActualMaximum(int Returns the maximum value for the specified field (e.g., the maximum
field) day in a month).
java
Copy code
import java.util.Calendar;
Output:
yaml
Copy code
Current Date: Mon Dec 03 14:45:12 IST 2024
After adding 5 days: Sat Dec 08 14:45:12 IST 2024
Year: 2024, Month: 12, Day: 8
2. Observable Class
The Observable class is a part of the java.util package and is used to implement the observer
design pattern. It allows objects (called "observers") to be notified automatically when there is a
change in the state of another object (the "observable").
In Java, the Observable class has methods for registering observers and notifying them when
there is a change. The Observer interface, which must be implemented by any class that wants
to be notified, defines the update() method that gets called when the observable object changes.
Method Description
addObserver(Observer o) Adds an observer to the list of observers for this object.
deleteObserver(Observer o) Removes an observer from the list.
deleteObservers() Removes all observers from the list.
setChanged() Marks the object as changed, so observers will be notified.
clearChanged() Clears the "changed" status, so observers won't be notified.
hasChanged() Returns whether the object has been marked as changed.
notifyObservers()
Notifies all registered observers if the object has been marked
as changed.
notifyObservers(Object
arg) Notifies all observers with a specified argument.
java
Copy code
import java.util.Observable;
import java.util.Observer;
Output:
css
Copy code
State changed to: Hello, World!
If you want to use both the Calendar and Observable classes together, it can be done in a
scenario where you want to observe changes in a Calendar instance. For instance, if you have a
calendar object and you want observers to be notified whenever the date is changed, you can
mark the Calendar object as an observable.
java
Copy code
import java.util.Calendar;
import java.util.Observable;
observableCalendar.printCurrentDate();
observableCalendar.addDays(5); // Adding 5 days and notifying
observers
}
}
Output:
sql
Copy code
Current Date: Mon Dec 03 14:45:12 IST 2024
Date updated to: Sat Dec 08 14:45:12 IST 2024
Conclusion
Calendar: It is a versatile class to work with date and time, offering methods for date
manipulation, adding or subtracting time, and formatting.
Observable: A class used to implement the observer design pattern, allowing objects to
notify other objects when their state changes.
When combined, you can create a system where a Calendar object is observable, and observers
are notified whenever the date changes, which is useful in scenarios like a calendar application or
scheduling system
executed according to the system's clock and the scheduled time. For fixed-rate tasks, the
execution time is spaced exactly according to the period, while for fixed-delay tasks, there is a
delay between the completion of the previous task and the start of the next.
Cancelling the Timer: After calling the cancel() method on a Timer, it can no longer be
used to schedule any further tasks. It's generally a good idea to cancel a timer when it is no
longer needed.
Unit-IV
Introducing AWT working With Graphics: AWT Classes, Working with Graphics.
Event Handling: Two Event Handling Mechanisms, The Delegation Event Model, Event
Classes, Source of Events, Event Listener Interfaces.
AWT Controls: Control Fundamentals, Labels, Using Buttons, Applying Check Boxes,
CheckboxGroup, Choice Controls, Using Lists, Managing Scroll Bars, Using TextField,
Using TextArea, Understanding Layout Managers, Menu bars and Menus, Dialog Boxes,
FileDialog, Handling events by Extending AWT Components, Exploring the controls, Menus and Layout Managers.
AWT (Abstract Window Toolkit) is a set of application programming interfaces (APIs) provided
by Java for building graphical user interfaces (GUIs). It is part of the java.awt package and was
one of the earliest Java libraries for building GUI applications.
AWT provides a collection of classes for creating windows, dialogs, buttons, text fields, and
other user interface components, as well as classes for handling events and drawing graphics. It
is based on the native system’s graphical user interface, which means that the components are
mapped to the operating system’s GUI components.
AWT Architecture
AWT uses a component-based architecture, where each user interface element is considered a
component, and components can be added to containers. AWT relies on the underlying operating
system's GUI components (native peers), which means that AWT GUIs look different on
different platforms because they are rendered using the native OS components.
AWT Components:
1. Component Class:
o The Component class is the base class for all AWT components.
o It defines common methods for all GUI components such
as setSize(), setLocation(), setVisible(), setBackground(),
and setForeground().
2. Container Class:
o Container is a subclass of Component and is used to hold other components.
Examples include Frame, Panel, and Window.
3. Frame Class:
o The Frame class represents a window in AWT. It has a title bar and can hold other
components like buttons, labels, and text fields.
o A Frame can be made visible by calling the setVisible(true) method.
4. Panel Class:
o The Panel class is a container for organizing components within a Frame. It
doesn’t have a title bar, but you can use it to group components in a window.
5. Button, Label, TextField, TextArea:
o Button: Represents a clickable button.
o Label: Displays non-editable text.
o TextField: A single-line text input field.
o TextArea: A multi-line text input field.
1. Creating a Frame:
o In AWT, the most common top-level container is a Frame. A Frame contains
components like buttons, text fields, etc.
2. Adding Components:
o Components like buttons, text fields, and labels are added to containers
(like Frame) using methods like add().
3. Handling Events:
o AWT handles user actions such as clicks, typing, etc., using event listeners
like ActionListener, MouseListener, etc.
4. Graphics:
o AWT allows for drawing on components using the Graphics class, and for
advanced graphics, the Graphics2D class can be used.
java
Copy code
Frame f = new Frame("My Frame");
f.setSize(400, 300);
f.setVisible(true);
2. Button Class (Button):
o Represents a clickable button.
o Example:
java
Copy code
Button b = new Button("Click Me");
f.add(b);
java
Copy code
TextField tf = new TextField("Enter text");
f.add(tf);
java
Copy code
Label l = new Label("Name:");
f.add(l);
java
Copy code
Checkbox c = new Checkbox("Accept terms and conditions");
f.add(c);
AWT uses the event-driven programming model. In this model, user actions such as button
clicks, mouse movement, or keystrokes generate events that the program listens for and reacts to.
1. Event Listeners:
o Java provides event listeners that respond to specific actions (like button clicks or
mouse movements).
2. Common Event Listeners:
o ActionListener: Listens for actions (e.g., button clicks).
o MouseListener: Listens for mouse events (e.g., mouse clicks).
o KeyListener: Listens for keyboard events.
AWT Graphics
AWT provides basic drawing capabilities with the Graphics class. You can override
the paint() method of a component to draw graphics on it. The paint() method is
automatically called when the component needs to be redrawn (e.g., when the window is resized
or restored).
@Override
public void paint(Graphics g) {
// Draw a line
g.drawLine(50, 50, 200, 50);
// Draw a rectangle
g.drawRect(50, 100, 100, 60);
// Fill a rectangle
g.setColor(Color.BLUE);
g.fillRect(200, 100, 100, 60);
// Draw an oval
g.setColor(Color.RED);
g.drawOval(50, 200, 100, 60);
// Fill an oval
g.setColor(Color.GREEN);
g.fillOval(200, 200, 100, 60);
}
AWT Layouts
AWT provides several layout managers that help organize components in a container. Some of
the commonly used layout managers include:
Example:
java
Copy code
Graphics g = getGraphics();
g.setColor(Color.RED);
g.drawRect(50, 50, 100, 50);
AWT (Abstract Window Toolkit) is Java's original GUI library and is part of
the java.awt package. It provides a set of classes to create graphical user interfaces (GUIs),
handle events, and perform drawing operations. AWT is built around a component-based
architecture where different classes serve specific roles for building and managing GUI
components, handling layout, and providing graphical capabilities.
1. Component Class
2. Container Class
3. Frame Class
Frame represents a top-level window with a title bar and a border. It is used to create the
main window of an application.
Key Methods:
o setTitle(String title) — Sets the title of the window.
o setSize(int width, int height) — Sets the size of the window.
o setVisible(boolean visible) — Makes the frame visible or invisible.
o addWindowListener(WindowListener l) — Adds a listener to handle window
events like closing.
Example:
java
Copy code
Frame frame = new Frame("My Frame");
frame.setSize(400, 300);
frame.setVisible(true);
4. Button Class
Example:
java
Copy code
Button button = new Button("Click Me");
button.setBounds(100, 100, 100, 50); // Set position and size
5. Label Class
Example:
java
Copy code
Label label = new Label("Hello, World!");
label.setFont(new Font("Arial", Font.PLAIN, 20));
6. TextField Class
TextField is a single-line text input field where users can enter text.
Key Methods:
o setText(String text) — Sets the text inside the text field.
o getText() — Gets the current text from the text field.
o setColumns(int columns) — Sets the width of the text field in terms of
columns.
o addActionListener(ActionListener l) — Adds an action listener to capture
the "Enter" key press.
Example:
java
Copy code
TextField textField = new TextField("Enter text");
textField.setBounds(50, 150, 200, 30);
7. TextArea Class
Example:
java
Copy code
TextArea textArea = new TextArea("Enter multiline text here...");
textArea.setBounds(50, 200, 300, 100);
8. Checkbox Class
java
Copy code
Checkbox checkbox = new Checkbox("Accept terms and conditions");
checkbox.setBounds(50, 250, 200, 30);
9. Panel Class
Panel is a container used to group components together, often used inside Frame or other
containers.
Key Methods:
o setLayout(LayoutManager mgr) — Sets the layout manager for the panel.
o add(Component comp) — Adds a component to the panel.
Example:
java
Copy code
Panel panel = new Panel();
panel.setLayout(new FlowLayout());
Listis used to display a list of items and allow users to select one or more items.
Key Methods:
o add(String item) — Adds an item to the list.
o getSelectedItem() — Gets the currently selected item.
o addItemListener(ItemListener l) — Adds an item listener to handle item
selection.
Example:
java
Copy code
List list = new List();
list.add("Item 1");
list.add("Item 2");
Example:
java
Copy code
Menu fileMenu = new Menu("File");
MenuItem newItem = new MenuItem("New");
fileMenu.add(newItem);
Graphicsis used for drawing shapes, text, and images on the screen.
Key Methods:
o drawLine(int x1, int y1, int x2, int y2) — Draws a line between two
points.
o drawRect(int x, int y, int width, int height) — Draws a rectangle.
o fillRect(int x, int y, int width, int height) — Fills a rectangle with
the current color.
o setColor(Color color) — Sets the drawing color.
Example:
java
Copy code
Graphics g = getGraphics();
g.setColor(Color.RED);
g.drawRect(50, 50, 100, 50);
Conclusion
AWT provides the basic building blocks for creating graphical user interfaces in Java, including
components like buttons, labels, text fields, checkboxes, panels, and windows. These
components can be arranged within containers (like Frameand Panel) and can interact with users
through event handling. For more complex and modern GUI development, developers often
use Swing (which extends AWT) or JavaFX. However, understanding AWT is still crucial for
learning Java GUIs, as Swing and JavaFX build upon its foundational concepts.
Graphics in Java allows you to draw shapes, images, and text on various components such as
windows, panels, and canvases. This is achieved using the Graphics and Graphics2D classes in
the java.awt package. Graphics is used in Java applications for creating custom drawings and
visual representations.
1. Graphics Class:
The Graphics class is the base class for all graphics-related operations in Java. It
provides methods to draw shapes, images, and text.
o The Graphics class cannot be instantiated directly. It is passed to components
through methods like paint(Graphics g), where you can draw on the
component’s surface.
o Graphics2D extends Graphics and provides more advanced drawing capabilities
such as transformations, anti-aliasing, and more complex shapes.
2. Graphics2D Class:
Graphics2D is a subclass of Graphics and provides more features for complex graphics
operations. It supports the drawing of lines, shapes, text, and images. It also allows you to
apply transformations, strokes, and other advanced graphical effects.
1. Override the paint() Method: In any AWT component (like Frame, Panel, Canvas),
you override the paint()method to handle the drawing operations. The paint() method
is called automatically when the component needs to be redrawn (e.g., when the window
is resized or restored).
2. Use the Graphics Object: The paint() method provides a Graphics object that can be
used to perform drawing operations on the component. For more advanced features, you
can cast it to Graphics2D.
3. Drawing Operations: You can use the Graphics or Graphics2D object to perform
various drawing tasks like drawing lines, rectangles, circles, ovals, and text.
Here are some common methods in the Graphics and Graphics2D classes for drawing
operations:
1. Drawing Lines
drawLine(int x1, int y1, int x2, int y2)
This method draws a straight line from point (x1, y1) to (x2, y2).
Example:
java
Copy code
g.drawLine(50, 50, 150, 150);
Example:
java
Copy code
g.drawRect(50, 50, 100, 60); // Draw rectangle
g.fillOval(200, 100, 80, 60); // Draw filled oval
3. Drawing Arcs
Example:
java
Copy code
g.drawArc(50, 50, 100, 100, 0, 180); // Draw half-circle
4. Drawing Polygons
Example:
java
Copy code
int[] xPoints = {50, 100, 150};
int[] yPoints = {50, 100, 50};
g.drawPolygon(xPoints, yPoints, 3);
5. Drawing Text
Example:
java
Copy code
g.drawString("Hello, Graphics!", 50, 50);
setColor(Color c)
o This method sets the drawing color for subsequent drawing operations.
setFont(Font f)
o This method sets the font for drawing text.
Example:
java
Copy code
g.setColor(Color.RED); // Set color to red
g.setFont(new Font("Arial", Font.BOLD, 20)); // Set font
g.drawString("Hello", 50, 50);
7. Filling Shapes
Example:
java
Copy code
g.setColor(Color.BLUE);
g.fillRect(200, 200, 100, 50); // Fill rectangle with blue
Here’s a simple Java program that demonstrates how to use the Graphics class to draw various
shapes and text:
java
Copy code
import java.awt.*;
import java.awt.event.*;
public GraphicsExample() {
setTitle("AWT Graphics Example");
setSize(400, 400);
setVisible(true);
}
@Override
public void paint(Graphics g) {
// Set color to blue and draw a rectangle
g.setColor(Color.BLUE);
g.drawRect(50, 50, 100, 60);
Graphics2D is an extension of the Graphics class and provides more advanced capabilities like:
java
Copy code
import java.awt.*;
import javax.swing.*;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Conclusion
Graphics Class: Used for basic drawing tasks like lines, rectangles, ovals, and text.
Graphics2D Class: Extends Graphics and provides more advanced features like strokes,
transformations, and anti-aliasing.
Paint Method: Override the paint() method in a component (like Frame or Canvas) to
perform drawing operations.
Graphics in Java provides a lot of flexibility for creating custom visual elements, making it
suitable for a wide range of applications, from simple UI elements to complex graphical designs.
Event handling is an essential concept in GUI programming, especially in frameworks like AWT
(Abstract Window Toolkit) and Swing. It refers to the process of responding to user actions such
as mouse clicks, keyboard input, or other interactions with GUI components. In Java, event
handling follows a listener-based model, where an event is generated by a user action and then
passed to the event handler.
In the Delegation Event Model, Event Listeners are used to separate the event-handling code
from the components, whereas the Inheritance Event Model relies on subclassing components
to handle events.
The Delegation Event Model is the most commonly used event handling mechanism in Java.
This model uses event listeners to handle events and decouples the event source (component)
from the event handler (listener). In this model, a component (e.g., a button or a text field)
generates an event when an action occurs, and an Event Listener is responsible for handling the
event.
Event Source: The component that generates the event (e.g., a button, text field, or
window).
Event Object: An object that encapsulates information about the event, such as its type
and source.
Event Listener: An interface that defines methods to handle specific types of events.
Event Handler: A class that implements the event listener interface and provides the
code to handle the event.
1. Define the Event Listener Interface: This defines methods to handle events
(e.g., ActionListener for action events, MouseListener for mouse events).
2. Implement the Event Listener Interface: Create a class that implements the listener
interface and provides the event handling logic.
3. Register the Listener with the Event Source: Register the listener with the component
(e.g., a button) to receive events.
java
Copy code
import java.awt.*;
import java.awt.event.*;
add(button);
setSize(300, 300);
setLayout(null);
setVisible(true);
}
In the Inheritance Event Model, you subclass the component itself to handle events. Instead of
implementing a listener interface, the event handling method is inherited by extending the
component class.
This model is not commonly used in modern Java programming, as it is less flexible and breaks
the principle of separation of concerns (mixing the event handling logic with the component
behavior).
1. Subclass the Component Class: You subclass the GUI component, like Button, and
override its event-handling methods.
2. Override Event-Handling Methods: You override methods in the subclass to handle
specific events.
java
Copy code
import java.awt.*;
import java.awt.event.*;
In this example, the ButtonClickExampleInheritance class inherits from Button. When the
button is clicked, the actionPerformed() method is invoked. However, this approach is not
typically preferred as it mixes the component with the event-handling logic.
The Delegation Event Model is the most commonly used event handling mechanism in Java,
particularly in GUI-based applications like those created using AWT (Abstract Window Toolkit)
or Swing. In this model, event sources generate events, and event listeners handle those events
by delegating the responsibility to specific methods in the listener class. This separation of
concerns between the source of an event (component) and the handling of the event makes it
easier to manage, maintain, and scale event-driven applications.
Key Components of the Delegation Event Model
1. Event Source:
The event source is the component or object that generates an event. Examples include
buttons, checkboxes, text fields, windows, etc. The event source listens for user actions
like clicks, key presses, or mouse movements.
2. Event Object:
An event object encapsulates information about the event, such as the event type (mouse
click, key press, etc.), the component that generated the event, and additional data (e.g.,
the key code for a key event).
3. Event Listener:
An event listener is an interface that defines methods for handling specific types of
events. The listener acts as a callback mechanism, which is invoked when an event
occurs. Java provides several listener interfaces, each designed to handle a specific type
of event.
4. Event Handler:
An event handler is a class or method that implements the event listener interface. The
handler contains the logic for responding to events (e.g., button clicks, key presses). The
handler is typically a separate class or an anonymous class that responds to the event by
implementing the listener's methods.
5. Event Dispatching:
Once an event occurs (e.g., a user clicks a button), the event is passed to the appropriate
listener method (such as actionPerformed() for action events), which is responsible for
handling the event. This delegation mechanism ensures that the event source (the
component) does not need to know what specific action to take when an event occurs.
1. Event Generation:
The event source generates an event when a user interacts with a component. For
example, when a user clicks a button, an ActionEvent is generated.
2. Event Object Creation:
The event object is created to store the details of the event (e.g., type of event, source,
time).
3. Event Listener Registration:
The event source (component) registers a listener to handle the event. The listener is
responsible for implementing the necessary interface and providing the behavior for the
event.
4. Event Handling:
Once the event is generated and passed to the listener, the listener invokes the appropriate
method (e.g., actionPerformed(), mouseClicked(), etc.) to handle the event.
5. Event Processing:
The event listener processes the event and executes the necessary action, such as updating
the UI or performing an operation.
Steps for Implementing the Delegation Event Model
ActionListener: For handling action events such as button clicks, menu item selections,
etc.
MouseListener: For handling mouse events such as clicks, mouse entering, and mouse
exiting.
KeyListener: For handling keyboard events such as key presses, key releases, etc.
WindowListener: For handling window events such as opening, closing, iconifying, etc.
ItemListener: For handling events related to items like checkboxes or choice menus.
java
Copy code
import java.awt.*;
import java.awt.event.*;
1. Separation of Concerns: The event source and event handler are separate. The source is
responsible for generating events, while the listener handles the logic. This makes the
code easier to maintain.
2. Scalability: Multiple listeners can be registered for a single event source. This allows the
same event to be handled in different ways by different parts of the program.
3. Flexibility: The event handler (listener) can be implemented in a separate class, allowing
for reusability. The event handler can be changed or modified without affecting the event
source.
4. Loose Coupling: The event source does not need to know anything about the event
handler. This results in a decoupled system where the components are independent.
Conclusion
The Delegation Event Model is the most widely used and flexible event handling mechanism in
Java. By decoupling the event source and event listener, this model provides a clean,
maintainable, and scalable way to handle user interactions in GUI-based applications. It allows
multiple listeners to be attached to the same event source, and the event-handling logic can be
kept separate from the components that generate the events. This model is fundamental to AWT
and Swing in Java, and its flexibility is crucial for building dynamic and interactive user
interfaces.
In Java, event handling in GUI components is accomplished through listener interfaces. These
interfaces contain methods that are triggered when specific events occur. Below is a table listing
some commonly used event listener interfaces and a brief description of each:
1. ActionListener:
o Purpose: Handles general action events such as button clicks or menu selections.
o Method: void actionPerformed(ActionEvent e) – Triggered when an action
occurs.
2. MouseListener:
o Purpose: Detects events related to the mouse, such as clicks, pressing, and
releasing buttons, as well as mouse entry and exit on a component.
o Methods:
void mouseClicked(MouseEvent e)
void mousePressed(MouseEvent e)
void mouseReleased(MouseEvent e)
void mouseEntered(MouseEvent e)
void mouseExited(MouseEvent e)
3. KeyListener:
o Purpose: Handles keyboard events like key presses, key releases, and typing.
o Methods:
void keyPressed(KeyEvent e)
void keyReleased(KeyEvent e)
void keyTyped(KeyEvent e)
4. WindowListener:
o Purpose: Listens for events related to window activities, such as opening, closing,
or minimizing.
o Methods:
void windowOpened(WindowEvent e)
void windowClosing(WindowEvent e)
void windowClosed(WindowEvent e)
void windowIconified(WindowEvent e)
void windowDeiconified(WindowEvent e)
void windowActivated(WindowEvent e)
void windowDeactivated(WindowEvent e)
5. ItemListener:
o Purpose: Handles events triggered by item selections, such as selecting a
checkbox or radio button.
o Method: void itemStateChanged(ItemEvent e)
6. FocusListener:
o Purpose: Responds to events when a component gains or loses focus.
o Methods:
void focusGained(FocusEvent e)
void focusLost(FocusEvent e)
7. TextListener:
o Purpose: Listens for changes to text, typically in text input components like text
fields or text areas.
o Method: void textValueChanged(TextEvent e)
8. MouseMotionListener:
o Purpose: Listens for events related to mouse movement and dragging.
o Methods:
void mouseMoved(MouseEvent e)
void mouseDragged(MouseEvent e)
9. ContainerListener:
o Purpose: Detects changes in the components of a container, such as adding or
removing components.
o Methods:
void componentAdded(ContainerEvent e)
void componentRemoved(ContainerEvent e)
10. AdjustmentListener:
o Purpose: Listens for adjustments in components like scroll bars or sliders.
o Method: void adjustmentValueChanged(AdjustmentEvent e)
11. ComponentListener:
o Purpose: Responds to changes in the size, position, or visibility of a component.
o Methods:
void componentResized(ComponentEvent e)
void componentMoved(ComponentEvent e)
void componentShown(ComponentEvent e)
void componentHidden(ComponentEvent e)
java
Copy code
import java.awt.*;
import java.awt.event.*;
public ActionListenerExample() {
button = new Button("Click Me");
button.setBounds(100, 100, 100, 50);
add(button);
setSize(300, 300);
setLayout(null);
setVisible(true);
}
java
Copy code
import java.awt.*;
import java.awt.event.*;
public MouseListenerExample() {
label = new Label("MouseListener Example");
label.setBounds(100, 100, 150, 50);
add(label);
label.addMouseListener(this); // Registering the MouseListener
setSize(300, 300);
setLayout(null);
setVisible(true);
}
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse Clicked!");
}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
In Java, event handling is a key aspect of creating interactive applications, especially for GUI-
based programs. The event-driven programming model in Java uses Event Classes, Event
Sources, and Event Listener Interfaces to enable components to generate events and trigger
specific actions when events occur.
1. Event Classes
An Event Class encapsulates information about a particular event that occurs in a program.
These event classes typically inherit from java.util.EventObject (the root class for all event
objects) and contain details about the event, such as its type and source.
java
Copy code
import java.awt.event.*;
2. Source of Events
The source of an event is the object or component that generates the event. The event source is
responsible for notifying listeners about the event when it occurs.
When an event occurs (such as a button click or a mouse click), the event source (button or
mouse) generates an event object and passes it to the registered event listener.
In the case of a button, the source is the Button object. When clicked, it generates
an ActionEvent.
java
Copy code
import java.awt.*;
import java.awt.event.*;
public ButtonClickExample() {
button = new Button("Click Me");
button.setBounds(100, 100, 100, 50);
button.addActionListener(this); // Registering the event source with
the listener
add(button);
setSize(300, 300);
setLayout(null);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button was clicked!");
}
Event Listener Interfaces are used to define the behavior that should occur when a specific
event happens. These interfaces have methods that must be implemented by the class that
handles the event. The event source registers the event listener, and when the event occurs, the
listener method is invoked.
Event
Listener Interface Methods Common Use
Type
Action
events like
void
button
ActionListener actionPerformed(ActionEvent Buttons, menu items, etc.
clicks, e)
menu
selections
Mouse
events like void mouseClicked(MouseEvent Mouse interactions with
MouseListener e), etc.
clicks, components
entry, exit
Keyboard
events (key
void keyPressed(KeyEvent e), Text fields, key press
KeyListener press,
etc. interactions
release,
typing)
WindowListener Window void Handling window state
Event
Listener Interface Methods Common Use
Type
events like
open, windowClosing(WindowEvent e),
changes
close, etc.
resizing
Item
events like void Checkboxes, radio
ItemListener itemStateChanged(ItemEvent e)
checkbox buttons, etc.
selection
Focus
change
events void focusGained(FocusEvent Components like text
FocusListener (componen e), etc.
fields, buttons, etc.
t gaining
or losing
focus)
Text Text components
void
TextListener change textValueChanged(TextEvent e) like TextField, TextAr
events ea
Mouse
motion
void mouseMoved(MouseEvent
MouseMotionListene events Mouse movements and
e), void
r (movement mouseDragged(MouseEvent e) drag events
or
dragging)
Componen
t change void
Resizing or moving
ComponentListener events like componentResized(ComponentEve
components
resizing, nt e), etc.
moving
java
Copy code
import java.awt.*;
import java.awt.event.*;
public ActionListenerExample() {
button = new Button("Click Me");
button.setBounds(100, 100, 100, 50);
// Registering the event source (button) with the event listener
button.addActionListener(this);
add(button);
setSize(300, 300);
setLayout(null);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// This method gets triggered when the button is clicked
System.out.println("Button clicked!");
}
1. Event Source: A component like a button or a mouse event generates an event when the
user interacts with it.
2. Event Object: The event source creates an event object (like ActionEvent, MouseEvent,
etc.) to store event-related data.
3. Event Listener: A listener (like ActionListener or MouseListener) is registered to
handle the event.
4. Event Dispatching: When the event occurs, the listener's corresponding method
(e.g., actionPerformed() for ActionListener) is invoked.
5. Event Handling: The listener method processes the event (e.g., prints a message, updates
the UI, etc.).
Summary
Awt controls:
AWT provides several types of controls to build interactive interfaces. These controls are used to
get user input, display information, or enable interaction with the program. Some of the common
AWT controls include buttons, checkboxes, text fields, labels, and more.
1. Button (Button)
o A button control is used to trigger an action when clicked. It can be labeled with
text and linked to an event handler using listeners.
Usage: Used for user interactions like form submissions, triggering events.
java
Copy code
Button button = new Button("Click Me");
button.setBounds(100, 100, 100, 50);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button Clicked!");
}
});
2. Checkbox (Checkbox)
o A checkbox is used for selecting or deselecting options. It is a boolean control
that allows users to make a binary choice (checked or unchecked).
java
Copy code
Checkbox checkbox = new Checkbox("Agree to Terms");
checkbox.setBounds(100, 150, 200, 50);
checkbox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
System.out.println(checkbox.getState() ? "Checked" :
"Unchecked");
}
});
3. TextField (TextField)
o A text field allows users to input text. It is a single-line text area for short inputs,
such as names, email addresses, etc.
Usage: Used for entering short strings of text, such as names, search queries, or
passwords.
java
Copy code
TextField textField = new TextField();
textField.setBounds(100, 200, 200, 30);
textField.addTextListener(new TextListener() {
public void textValueChanged(TextEvent e) {
System.out.println("Text entered: " + textField.getText());
}
});
4. Label (Label)
o A label is used to display a text string or image in a GUI. It is a non-interactive
control, used only for presenting information.
java
Copy code
Label label = new Label("Enter your name:");
label.setBounds(100, 250, 200, 30);
5. List (List)
o A list provides the user with a selection of options from a list of items. It can
support single or multiple selections.
Usage: Used to display multiple items, and users can select one or more from the list.
java
Copy code
List list = new List();
list.add("Option 1");
list.add("Option 2");
list.add("Option 3");
list.setBounds(100, 300, 200, 100);
list.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
System.out.println("Selected Item: " + list.getSelectedItem());
}
});
6. TextArea (TextArea)
o A text area allows users to input multi-line text. It is useful for entering larger
blocks of text, such as comments or descriptions.
Usage: Used for displaying or entering multiple lines of text (e.g., comments, messages).
java
Copy code
TextArea textArea = new TextArea();
textArea.setBounds(100, 400, 200, 100);
7. Choice (Choice)
o A choice is a drop-down list that allows users to select an item from a list of
options.
Usage: Used when a compact selection mechanism is needed, like a drop-down menu.
java
Copy code
Choice choice = new Choice();
choice.add("Option 1");
choice.add("Option 2");
choice.add("Option 3");
choice.setBounds(100, 500, 200, 30);
choice.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
System.out.println("Selected: " + choice.getSelectedItem());
}
});
8. Scrollbar (Scrollbar)
o A scrollbar allows users to scroll through content. It can be horizontal or vertical
and is used when the content exceeds the visible area of a window.
java
Copy code
Scrollbar scrollbar = new Scrollbar();
scrollbar.setBounds(100, 600, 200, 30);
scrollbar.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("Scrollbar position: " +
scrollbar.getValue());
}
});
9. Panel (Panel)
o A Panel is a container used to group AWT controls together. It doesn't display
anything by itself but is used to hold other controls.
java
Copy code
Panel panel = new Panel();
panel.setBounds(100, 700, 200, 100);
Usage: Used for implementing menus in a GUI, such as File, Edit, View, etc.
java
Copy code
Menu menu = new Menu("File");
MenuItem item = new MenuItem("Open");
menu.add(item);
AWT controls are the basic building blocks of a GUI. Some of the fundamental concepts related
to AWT controls are:
1. Layout Managers:
o A layout manager is used to arrange AWT components (controls) within a
container. AWT provides various layout managers
like FlowLayout, BorderLayout, GridLayout, etc., to control how components
are arranged.
2. Event Handling:
o Each control in AWT generates events in response to user actions. For example, a
button generates an ActionEvent when clicked. Event listeners are used to handle
these events and trigger the necessary actions.
3. Component Hierarchy:
o Controls are placed in containers like Frame, Panel, or Dialog. These containers
manage the layout of controls and can contain other containers or controls.
4. Component Visibility:
o Controls can be made visible or hidden using the setVisible() method. By
default, components are visible once added to a container.
5. Control Customization:
o Controls can be customized by setting properties like text, size, color, font, etc.
For instance, a button's label can be set using button.setLabel("Click Me").
// Create a Button
Button button = new Button("Click Me");
button.setBounds(100, 100, 100, 50);
// Create a Checkbox
Checkbox checkbox = new Checkbox("Agree to Terms");
checkbox.setBounds(100, 200, 200, 50);
// Create a TextField
TextField textField = new TextField();
textField.setBounds(100, 300, 200, 30);
// Create a List
List list = new List();
list.setBounds(100, 350, 200, 100);
list.add("Option 1");
list.add("Option 2");
list.add("Option 3");
1. Creating a Frame:
o Frame frame = new Frame("AWT Controls Example");: We create an
instance of Frame, which serves as the window for displaying AWT components.
2. Creating Controls:
o Button: Button button = new Button("Click Me"); creates a button.
o Checkbox: Checkbox checkbox = new Checkbox("Agree to
Terms"); creates a checkbox.
o TextField: TextField textField = new TextField(); creates a single-line
text field.
o List: List list = new List(); creates a list control with options for selection.
3. Event Handling:
o ActionListener for Button: When the button is clicked,
the actionPerformed() method is triggered, printing "Button Clicked!" to the
console.
o ItemListener for Checkbox: The itemStateChanged() method is triggered
when the checkbox is checked or unchecked, printing "Checked" or "Unchecked"
based on the state.
o ItemListener for List: The itemStateChanged() method for the list is triggered
when a selection is made, printing the selected item.
4. Adding Components:
o frame.add(button);, frame.add(checkbox);, etc., add the controls to the
frame.
5. Window Listener:
o frame.addWindowListener(new WindowAdapter() { ... });: A window
listener is added to handle the frame's close event. System.exit(0); ensures that
the program exits when the window is closed.
6. Layout and Display:
o The frame uses setLayout(null); to allow manual positioning of controls
with setBounds(). This gives more control over the placement of the
components.
o frame.setSize(400, 500); sets the size of the frame.
o frame.setVisible(true); makes the frame visible on the screen.
AWT Label in Java: Detailed Explanation
In Java's Abstract Window Toolkit (AWT), a Label is a simple, non-interactive component used
to display text or images. Labels are often used to provide information or context to the user,
such as instructions, descriptions, titles, or even static content in a GUI.
A Label does not generate events (i.e., it doesn't interact with the user), and it cannot accept any
user input. However, it can be customized in terms of appearance (such as text color, font,
alignment, etc.).
Definition of Label
A Label in Java AWT is a simple non-editable text component that can be added to containers
such as Frame or Panel. You use it when you need to display information to the user without
expecting any interaction with the label.
1. Basic Constructor:
o Label(): Creates an empty label with no text.
java
Copy code
Label label = new Label();
java
Copy code
Label label = new Label("Hello, World!");
java
Copy code
Label label = new Label("Welcome", Label.CENTER);
1. setText(String text)
java
Copy code
label.setText("New Text");
2. getText()
java
Copy code
String text = label.getText();
System.out.println(text);
3. setAlignment(int alignment)
java
Copy code
label.setAlignment(Label.CENTER);
4. getAlignment()
java
Copy code
int alignment = label.getAlignment();
System.out.println("Current alignment: " + alignment);
5. setFont(Font font)
java
Copy code
Font font = new Font("Arial", Font.BOLD, 14);
label.setFont(font);
6. setForeground(Color color)
java
Copy code
label.setForeground(Color.RED);
7. setBackground(Color color)
java
Copy code
label.setBackground(Color.YELLOW);
Description: Sets the position and size of the label within its parent container.
Parameters:
o x and y: The position of the label on the screen (top-left corner).
o width and height: The size of the label.
Usage: This method is used for absolute positioning when the layout manager is set
to null.
java
Copy code
label.setBounds(50, 50, 150, 30);
9. setVisible(boolean visibility)
java
Copy code
label.setVisible(true); // Makes the label visible
label.setVisible(false); // Hides the label
10. getPreferredSize()
Description: Returns the preferred size of the label based on its content (text or image).
Usage: It gives the preferred width and height for the label to display its content properly.
java
Copy code
Dimension preferredSize = label.getPreferredSize();
System.out.println("Preferred size: " + preferredSize);
Here’s an example of how to use various methods of the Label class in a simple Java AWT
application:
java
Copy code
import java.awt.*;
import java.awt.event.*;
1. Creating a Label:
o Label label = new Label("Hello, World!"); creates a label with the initial
text "Hello, World!".
2. Setting Alignment:
o label.setAlignment(Label.CENTER); centers the text in the label.
3. Setting Font:
o label.setFont(new Font("Arial", Font.BOLD, 16)); sets the font to Arial,
bold, and size 16.
4. Setting Text Color:
o label.setForeground(Color.BLUE); sets the text color to blue.
5. Setting Background Color:
o label.setBackground(Color.LIGHT_GRAY); sets the background color to light
gray.
6. Positioning and Sizing:
o label.setBounds(50, 100, 300, 50); sets the label's position and size.
7. Adding Label to the Frame:
o frame.add(label); adds the label to the frame.
8. Frame Setup:
o The frame is sized, set to be visible, and made capable of closing correctly when
the window is closed.
In Java's Abstract Window Toolkit (AWT), a Button is a control that is used to trigger actions
when clicked by the user. Buttons are commonly used to submit forms, execute commands, or
control the flow of an application. A Button is a clickable component that can be associated with
an event, and when the button is clicked, an action is performed.
Definition of Button
A Button in Java AWT is a component that allows the user to click on it, which triggers an
event. When clicked, a Buttongenerates an ActionEvent that can be captured by
an ActionListener.
java
Copy code
Button button = new Button();
java
Copy code
Button button = new Button("Click Me!");
The Button class provides several methods to set properties and handle events related to buttons.
1. setLabel(String label)
java
Copy code
button.setLabel("Submit");
2. getLabel()
java
Copy code
String label = button.getLabel();
System.out.println(label);
3. addActionListener(ActionListener listener)
Description: Adds an ActionListener to the button that listens for ActionEvent when
the button is clicked.
Parameters: An ActionListener object that will handle the event when the button is
clicked.
Usage: This method is crucial for capturing the button click action and performing tasks
in response.
java
Copy code
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});
4. setEnabled(boolean enabled)
Description: Enables or disables the button. When disabled, the button is grayed out and
cannot be clicked.
Parameters: A boolean value (true for enabled, false for disabled).
Usage: This method is used to disable the button when you want to prevent user
interaction.
java
Copy code
button.setEnabled(false); // Disable the button
button.setEnabled(true); // Enable the button
5. setFont(Font font)
java
Copy code
button.setFont(new Font("Arial", Font.BOLD, 16));
6. setBackground(Color color)
java
Copy code
button.setBackground(Color.BLUE);
7. setForeground(Color color)
java
Copy code
button.setForeground(Color.WHITE);
Button Event Handling with ActionListener
A Button in AWT generates an ActionEvent when clicked. To handle this event, we use
an ActionListener that is added to the button using the addActionListener() method.
ActionListener Interface
Here’s an example that demonstrates how to use AWT buttons, handle button clicks, and
customize the button’s appearance.
java
Copy code
import java.awt.*;
import java.awt.event.*;
java
Copy code
import java.awt.*;
import java.awt.event.*;
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
System.out.println("Newsletter subscription: " +
(checkbox2.getState() ? "Checked" : "Unchecked"));
}
});
Definition of CheckboxGroup
A CheckboxGroup is used to create a set of checkboxes where only one checkbox can be selected
at a time, which is the opposite of the default behavior of checkboxes (where multiple
checkboxes can be selected independently).
1. CheckboxGroup():
o Creates a new CheckboxGroup object.
java
Copy code
CheckboxGroup group = new CheckboxGroup();
The CheckboxGroup class provides some key methods to work with groups of checkboxes:
1. getSelectedCheckbox()
Description: Returns the checkbox that is currently selected in the group. If no checkbox
is selected, it returns null.
Usage: This method is used to determine which checkbox is selected in the group.
java
Copy code
Checkbox selectedCheckbox = group.getSelectedCheckbox();
if (selectedCheckbox != null) {
System.out.println("Selected Checkbox: " + selectedCheckbox.getLabel());
} else {
System.out.println("No checkbox selected");
}
2. setSelectedCheckbox(Checkbox checkbox)
Description: Sets the specified checkbox as the selected checkbox in the group.
Parameters: A Checkbox object that should be selected.
Usage: This method allows you to programmatically set a checkbox as selected.
java
Copy code
group.setSelectedCheckbox(checkbox1); // Select checkbox1 programmatically
When you create a CheckboxGroup, it automatically forces the checkboxes added to it to behave
like a set of radio buttons. That is, if one checkbox is selected, all other checkboxes in the same
group will be automatically deselected.
java
Copy code
import java.awt.*;
import java.awt.event.*;
// Create a CheckboxGroup
CheckboxGroup group = new CheckboxGroup();
1. Create a CheckboxGroup:
o CheckboxGroup group = new CheckboxGroup(); creates a
new CheckboxGroup object.
2. Create Checkboxes with the Group:
o Checkbox checkbox1 = new Checkbox("Option 1", group,
false); creates a checkbox for "Option 1" and adds it to the CheckboxGroup.
The third parameter (false) sets the checkbox to be initially unchecked.
o Similarly, checkbox2 and checkbox3 are created and added to the same group.
3. Setting Positions:
o checkbox1.setBounds(50, 100, 100, 30); positions each checkbox at
different locations within the frame.
4. Adding Event Listeners:
o checkbox1.addItemListener(new ItemListener() {...}); adds
an ItemListener to each checkbox to handle the state change when the checkbox
is clicked.
5. Adding the Checkboxes to the Frame:
o frame.add(checkbox1); adds the checkboxes to the frame so they can be
displayed.
6. Frame Setup:
o The layout is set to null to manually position the components.
o The frame is sized and made visible, and a WindowAdapter is added to handle
window closure.
The CheckboxGroup class is specifically used when you want to group checkboxes in a
way that only one checkbox can be selected at a time, just like radio buttons.
When a Checkbox is added to a CheckboxGroup, its state is controlled by the group, so
selecting one checkbox will automatically deselect the others in the group.
You can programmatically select a checkbox within
a CheckboxGroup using setSelectedCheckbox(), and you can retrieve the currently
selected checkbox with getSelectedCheckbox().
In Java AWT, the Choice class is a type of control that allows users to select an item from a list
of options. It presents a dropdown menu (also known as a combo box in other UI frameworks)
where the user can choose a single item from a list. It is useful in forms or settings when there
are multiple predefined options to choose from, but space on the screen is limited.
Definition of Choice
The Choice class is a part of the AWT library and provides a list of items presented in a pop-up
menu. The user can select one of the items from the list. Once an item is selected, it is displayed
in the menu bar, and the user can either keep the selected option or change it by selecting another
item.
1. Choice():
o Creates an empty Choice object, which can then have items added to it.
java
Copy code
Choice choice = new Choice();
2. Choice(String items[]):
o Creates a Choice object and populates it with a list of items. This constructor
allows you to initialize the dropdown menu with multiple options from an array of
strings.
java
Copy code
String[] options = {"Option 1", "Option 2", "Option 3"};
Choice choice = new Choice();
for (String option : options) {
choice.add(option);
}
The Choice class provides several methods to manage and interact with the list of items.
1. add(String item)
java
Copy code
choice.add("Option 4");
java
Copy code
choice.insert("Option 0", 0); // Insert at the start
3. remove(String item)
java
Copy code
choice.remove("Option 2");
4. remove(int index)
java
Copy code
choice.remove(1); // Removes the item at index 1
5. getSelectedItem()
java
Copy code
String selectedItem = choice.getSelectedItem();
System.out.println("Selected Item: " + selectedItem);
6. getSelectedIndex()
java
Copy code
int selectedIndex = choice.getSelectedIndex();
System.out.println("Selected Index: " + selectedIndex);
7. select(int index)
java
Copy code
choice.select(2); // Selects the third item in the list (index 2)
8. addItemListener(ItemListener listener)
Description: Adds an ItemListener to the Choice control to listen for item selection
changes.
Parameters: An ItemListener object that will handle the event when an item is
selected.
Usage: This method allows you to detect when the user selects a new item from the
dropdown list.
java
Copy code
choice.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
System.out.println("Item Selected: " + choice.getSelectedItem());
}
});
9. getItemCount()
java
Copy code
int itemCount = choice.getItemCount();
System.out.println("Total items: " + itemCount);
Here’s an example that demonstrates how to use a Choice control to allow a user to select a fruit
from a dropdown list.
java
Copy code
import java.awt.*;
import java.awt.event.*;
The Choice class provides a dropdown menu for selecting a single item from a list.
Methods like add(), remove(), insert(), and getSelectedItem() allow you to
manipulate the list and retrieve selected items.
Use the ItemListener interface to handle events when the user selects an item from the
dropdown menu.
The Choice control is an excellent choice when you need a compact control for
presenting multiple options to the user in limited space.
Using Lists in Java AWT
In Java AWT, the List class is a component that allows users to select one or more items from a
list of options. It displays a list of items in a scrollable list box, and the user can select either a
single item or multiple items, depending on how the list is configured.
Definition of List
The List class is used to display a list of items in a scrollable area. It can be used for scenarios
where multiple choices are available, and the user needs to select one or more items. The list can
also be configured to allow the user to select multiple items simultaneously or just one item at a
time.
1. List():
o Creates an empty list.
java
Copy code
List list = new List();
2. List(int rows):
o Creates a list with a specified number of visible rows.
java
Copy code
List list = new List(4); // Displays 4 rows at a time
java
Copy code
List list = new List(4, true); // Allows multiple selection
The List class provides several methods to manage and interact with the list of items.
1. add(String item)
java
Copy code
list.add("Option 1");
java
Copy code
list.insert("Option 0", 0); // Insert at index 0
3. remove(String item)
java
Copy code
list.remove("Option 2");
4. remove(int index)
java
Copy code
list.remove(1); // Removes the item at index 1
5. getItem(int index)
java
Copy code
String item = list.getItem(0); // Get the item at index 0
System.out.println(item);
6. getSelectedItem()
Description: Returns the currently selected item from the list (if single selection is
enabled).
Usage: This method retrieves the text of the currently selected item.
java
Copy code
String selectedItem = list.getSelectedItem();
System.out.println("Selected Item: " + selectedItem);
7. getSelectedIndexes()
Description: Returns an array of the indexes of the selected items (if multiple selection is
enabled).
Usage: This method is used when multiple selections are allowed. It returns the indexes
of the selected items.
java
Copy code
int[] selectedIndexes = list.getSelectedIndexes();
for (int index : selectedIndexes) {
System.out.println("Selected Index: " + index);
}
8. select(int index)
java
Copy code
list.select(2); // Selects the item at index 2
9. clear()
java
Copy code
list.clear(); // Clears the list
Here’s an example that demonstrates how to use a List control to allow the user to select
multiple fruits from a list.
java
Copy code
import java.awt.*;
import java.awt.event.*;
The List class provides a list control to display multiple options, where the user can
select one or more items.
Methods like add(), remove(), getSelectedItem(),
and getSelectedIndexes() allow you to manipulate the list and retrieve selected items.
Use the ItemListener interface to handle events when the user selects or deselects an
item.
The List control is useful when you need to present a series of options that may not fit in
the limited space of a combo box.
Scroll bars are managed using the Scrollbar class in AWT, but other components
like TextArea, List, and Panel also have built-in support for scroll bars.
1. Scrollbar Class
The Scrollbar class is used to create a scrollbar, which can either be horizontal or vertical. A
scrollbar is typically used when the size of the content exceeds the visible area of the container.
The Scrollbar class provides multiple constructors for creating both horizontal and vertical
scrollbars.
1. Scrollbar()
o Creates a vertical scrollbar with default values for the range and visibility.
java
Copy code
Scrollbar scrollbar = new Scrollbar();
2. Scrollbar(int orientation)
o Creates a scrollbar of the specified orientation
(Scrollbar.HORIZONTAL or Scrollbar.VERTICAL).
java
Copy code
Scrollbar verticalScrollbar = new Scrollbar(Scrollbar.VERTICAL);
Scrollbar horizontalScrollbar = new Scrollbar(Scrollbar.HORIZONTAL);
java
Copy code
Scrollbar scrollbar = new Scrollbar(Scrollbar.HORIZONTAL, 50, 10, 0,
100);
Methods of the Scrollbar Class
Here are some important methods provided by the Scrollbar class for managing scrollbars:
1. getValue()
java
Copy code
int position = scrollbar.getValue();
2. setValue(int value)
java
Copy code
scrollbar.setValue(30); // Set the scrollbar's position to 30
3. setMinimum(int minimum)
java
Copy code
scrollbar.setMinimum(0); // Set the minimum position to 0
4. setMaximum(int maximum)
java
Copy code
scrollbar.setMaximum(100); // Set the maximum position to 100
5. setBlockIncrement(int increment)
Description: Sets the block increment, which is the amount the scrollbar moves when the
user clicks in the area next to the thumb.
Parameters: An integer increment specifying the value to increase or decrease the
scrollbar’s thumb position.
java
Copy code
scrollbar.setBlockIncrement(10); // Set the block increment to 10
6. setUnitIncrement(int increment)
Description: Sets the unit increment, which is the amount the scrollbar moves when the
user clicks the arrow buttons on the scrollbar.
Parameters: An integer increment specifying the value for moving the thumb in small
steps.
java
Copy code
scrollbar.setUnitIncrement(1); // Set the unit increment to 1
7. addAdjustmentListener(AdjustmentListener listener)
java
Copy code
scrollbar.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("Scrollbar Value: " + scrollbar.getValue());
}
});
Here’s an example demonstrating the use of a vertical scrollbar to scroll through a content area in
a frame.
java
Copy code
import java.awt.*;
import java.awt.event.*;
java
Copy code
TextArea textArea = new TextArea("Content here...");
textArea.setBounds(50, 50, 200, 100);
Scrollbar vScrollbar = new Scrollbar(Scrollbar.VERTICAL);
vScrollbar.setBounds(260, 50, 20, 100);
frame.add(textArea);
frame.add(vScrollbar);
java
Copy code
List list = new List();
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
Scrollbar vScrollbar = new Scrollbar(Scrollbar.VERTICAL);
list.add(vScrollbar);
ou said:
Textfield:
The TextField class in AWT (Abstract Window Toolkit) is used to create a single-line text
field that allows the user to input or edit text. It is part of the java.awt package and is often used
in graphical user interfaces (GUIs) for user input.
Constructors of TextField
// Create components
Label label = new Label("Enter Text:");
TextField textField1 = new TextField(20); // TextField with 20 columns
TextField textField2 = new TextField(20); // Another TextField
Explanation
Output
Text area
The TextArea class in Java's AWT (Abstract Window Toolkit) is used to create a multi-line
area where users can input or display text. It is commonly used when dealing with larger text
inputs or outputs, such as comments, descriptions, or logs.
Features of TextArea
1. Multi-Line Text Input: Allows for multiple lines of text to be entered or displayed.
2. Scrollable: When the text exceeds the visible area, it automatically scrolls.
3. Editable/Non-editable: Can be set as editable or read-only.
4. Customizable Rows and Columns: You can define the number of visible rows and
columns.
5. Text Events: Can handle user interactions, such as text changes.
Constructors of TextArea
1. TextArea()
Creates an empty text area.
2. TextArea(String text)
Creates a text area initialized with the given text.
3. TextArea(String text, int rows, int columns)
Creates a text area with specified rows and columns, initialized with the given text.
4. TextArea(String text, int rows, int columns, int scrollbars)
Creates a text area with rows, columns, initial text, and scrollbar options.
The scrollbars parameter can take values like:
o TextArea.SCROLLBARS_BOTH (default)
o TextArea.SCROLLBARS_VERTICAL_ONLY
o TextArea.SCROLLBARS_HORIZONTAL_ONLY
o TextArea.SCROLLBARS_NONE
java
Copy code
import java.awt.*;
import java.awt.event.*;
// Create a Label
Label label = new Label("Enter Your Comments:");
// Create a TextArea
TextArea textArea = new TextArea("Type here...", 10, 30,
TextArea.SCROLLBARS_BOTH);
// Create a Button
Button button = new Button("Show Text");
Explanation
1. TextArea:
o Created with 10 rows, 30 columns, and both horizontal and vertical scrollbars
(TextArea.SCROLLBARS_BOTH).
o Initialized with default text "Type here...".
2. Button:
o Captures the text entered in the TextArea and prints it to the console
using getText().
3. Event Handling:
o ActionListener is added to the button to handle user interaction.
o WindowListener ensures the program closes when the window is closed.
Output
Layout manager
In Java AWT, layout managers are used to arrange components (like buttons, labels, text
fields) in a container (such as a frame or panel). They provide a way to control the size, position,
and alignment of components within the container.
Automatic Resizing: Layout managers automatically adjust the size and position of
components when the container is resized.
Platform Independence: They ensure consistent appearance across different operating
systems.
Ease of Use: No need to manually calculate coordinates or dimensions for components.
Java provides several built-in layout managers, each with a specific arrangement style. Below are
the most commonly used ones:
1. FlowLayout
Description: Arranges components in a row, one after another (left to right). If a row is
full, components are moved to the next row.
Default Layout: Used by Panel.
Alignment Options: LEFT, CENTER (default), RIGHT.
Constructor:
java
Copy code
FlowLayout()
FlowLayout(int alignment)
FlowLayout(int alignment, int hgap, int vgap)
Example:
java
Copy code
Frame frame = new Frame("FlowLayout Example");
frame.setLayout(new FlowLayout());
frame.add(new Button("Button 1"));
frame.add(new Button("Button 2"));
frame.add(new Button("Button 3"));
frame.setSize(300, 200);
frame.setVisible(true);
2. BorderLayout
Description: Divides the container into five regions: NORTH, SOUTH, EAST, WEST,
and CENTER. Components are placed in these regions.
Default Layout: Used by Frame and Dialog.
Constructor:
java
Copy code
BorderLayout()
BorderLayout(int hgap, int vgap)
Example:
java
Copy code
Frame frame = new Frame("BorderLayout Example");
frame.setLayout(new BorderLayout());
frame.add(new Button("North"), BorderLayout.NORTH);
frame.add(new Button("South"), BorderLayout.SOUTH);
frame.add(new Button("East"), BorderLayout.EAST);
frame.add(new Button("West"), BorderLayout.WEST);
frame.add(new Button("Center"), BorderLayout.CENTER);
frame.setSize(300, 200);
frame.setVisible(true);
3. GridLayout
Description: Arranges components in a grid of rows and columns. All cells are of equal
size.
Usage: Suitable for creating forms or calculators.
Constructor:
java
Copy code
GridLayout(int rows, int cols)
GridLayout(int rows, int cols, int hgap, int vgap)
Example:
java
Copy code
Frame frame = new Frame("GridLayout Example");
frame.setLayout(new GridLayout(2, 2)); // 2 rows, 2 columns
frame.add(new Button("Button 1"));
frame.add(new Button("Button 2"));
frame.add(new Button("Button 3"));
frame.add(new Button("Button 4"));
frame.setSize(300, 200);
frame.setVisible(true);
4. CardLayout
Description: Manages multiple components in a stack (like cards). Only one component
is visible at a time.
Usage: Ideal for wizards, tab-based interfaces, or paginated forms.
Constructor:
java
Copy code
CardLayout()
CardLayout(int hgap, int vgap)
Example:
java
Copy code
Frame frame = new Frame("CardLayout Example");
CardLayout cardLayout = new CardLayout();
Panel panel = new Panel(cardLayout);
frame.add(panel);
cardLayout.show(panel, "1"); // Show the first card
frame.setSize(300, 200);
frame.setVisible(true);
5. GridBagLayout
Description: A flexible and powerful layout manager that aligns components both
horizontally and vertically in a grid. Each component can span multiple rows or columns.
Usage: Used for complex and custom UI designs.
Example:
java
Copy code
Frame frame = new Frame("GridBagLayout Example");
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
frame.setSize(300, 200);
frame.setVisible(true);
Example:
java
Copy code
Frame frame = new Frame("Null Layout Example");
frame.setLayout(null);
frame.setSize(300, 200);
frame.setVisible(true);
Java AWT, menu bars and menus are used to create drop-down menus in a graphical user
interface. These are typically seen in desktop applications and provide an organized way for
users to interact with an application.
1. MenuBar: Represents the menu bar of a window. It can hold multiple menus.
2. Menu: Represents a single menu in the menu bar. A menu can hold menu items and
submenus.
3. MenuItem: Represents an individual menu item that a user can select.
4. CheckboxMenuItem: A special type of menu item that acts as a toggle (checked or
unchecked).
Classes and Hierarchy
MenuBar
└── Menu
├── MenuItem
└── CheckboxMenuItem
MenuBar
Constructor:
java
Copy code
MenuBar() // Creates an empty menu bar
Menu
Constructor:
java
Copy code
Menu(String label) // Creates a menu with the specified label
Menu(String label, boolean tearOff) // Tear-off menus are no longer widely
supported
MenuItem
Constructor:
java
Copy code
MenuItem(String label) // Creates a menu item with the specified label
MenuItem(String label, MenuShortcut shortcut) // Adds a keyboard shortcut
CheckboxMenuItem
Represents a toggleable menu item.
Constructor:
java
Copy code
CheckboxMenuItem(String label) // Creates a checkbox menu item with the
specified label
CheckboxMenuItem(String label, boolean state) // Sets the initial state
(checked/unchecked)
java
Copy code
import java.awt.*;
import java.awt.event.*;
// Create a MenuBar
MenuBar menuBar = new MenuBar();
// Create Menus
Menu fileMenu = new Menu("File");
Menu editMenu = new Menu("Edit");
Menu viewMenu = new Menu("View");
// Frame settings
frame.setSize(400, 300);
frame.setVisible(true);
1. MenuBar:
o A MenuBar object (menuBar) is created and added to the Frame.
2. Menus:
o Three menus (File, Edit, and View) are added to the menu bar.
3. MenuItems:
o Menu items like "New", "Open", "Save", etc., are added to the File menu.
o Menu items like "Cut", "Copy", and "Paste" are added to the Edit menu.
4. CheckboxMenuItem:
o The View menu contains a checkbox item ("Show Status Bar") that can toggle its
state.
5. Event Handling:
o The "Exit" menu item has an ActionListener attached to close the application
when clicked.
Output
1. A frame is displayed with a menu bar containing three menus: File, Edit, and View.
2. The File menu includes options like "New", "Open", "Save", and "Exit".
3. The Edit menu includes options like "Cut", "Copy", and "Paste".
4. The View menu contains a checkbox item labeled "Show Status Bar".
5. Clicking "Exit" closes the application.
Advanced Features
1. Keyboard Shortcuts: Use the MenuShortcut class to assign shortcuts to menu items.
java
Copy code
MenuItem saveItem = new MenuItem("Save", new
MenuShortcut(KeyEvent.VK_S)); // Ctrl+S
java
Copy code
Menu subMenu = new Menu("Export");
subMenu.add(new MenuItem("PDF"));
subMenu.add(new MenuItem("Word"));
fileMenu.add(subMenu); // Adding sub-menu to File menu
3. Dynamic Menus: You can dynamically add or remove items from menus based on user
actions.
1. Menu Structure: Understand the hierarchy (MenuBar -> Menu -> MenuItem).
2. Event Handling: Use listeners to handle user actions on menu items.
3. Flexibility: Menus can have submenus, separators, and toggle options.
4. CheckboxMenuItem: Useful for options like toggling features on or off.
Dialog boxes :
Dialog boxes in Java AWT are small windows that appear on top of the main application
window. They are typically used to display information, get user input, or present a message that
requires immediate attention.
1. Modal Dialog: Prevents the user from interacting with the main application until the
dialog is closed.
2. Modeless Dialog: Allows interaction with the main application even when the dialog is
open.
Dialog Class
Constructors of Dialog
1. Dialog(Frame parent)
Creates a non-modal dialog with the specified parent frame.
2. Dialog(Frame parent, String title)
Creates a non-modal dialog with a title.
3. Dialog(Frame parent, String title, boolean modal)
Creates a dialog with the specified modality (true for modal).
Methods in Dialog
java
Copy code
import java.awt.*;
import java.awt.event.*;
// Create a dialog
Dialog dialog = new Dialog(frame, "My Dialog", true); // Modal dialog
dialog.setSize(200, 150);
dialog.setLayout(new FlowLayout());
dialog.add(label);
dialog.add(closeButton);
1. Dialog Creation:
o A modal dialog (Dialog(frame, "My Dialog", true)) is created.
2. Dialog Components:
o A Label is used to display a message.
o A Button is added to close the dialog.
3. Event Handling:
o Clicking the "Close" button hides the dialog using setVisible(false).
o Clicking the "Show Dialog" button makes the dialog visible.
FileDialog Class
The FileDialog class is a built-in dialog for selecting files to open or save.
Constructors of FileDialog
1. FileDialog(Frame parent)
Creates a file dialog for opening files.
2. FileDialog(Frame parent, String title)
Creates a file dialog with a title.
3. FileDialog(Frame parent, String title, int mode)
Creates a file dialog with the specified mode:
o FileDialog.LOAD: For opening files.
o FileDialog.SAVE: For saving files.
FileDialog Example
java
Copy code
import java.awt.*;
import java.awt.event.*;
if (fileName != null) {
System.out.println("File Selected: " + directory + fileName);
} else {
System.out.println("No file selected.");
}
});
Explanation
1. FileDialog:
o A file dialog is created in "LOAD" mode to select a file.
2. Getting Selected File:
o getFile() returns the selected file name.
o getDirectory() returns the directory of the selected file.
By using AWT dialog boxes effectively, you can enhance the user experience in Java desktop
applications.
File dialog:
The FileDialog class in Java AWT is a built-in dialog specifically designed for file operations,
such as opening or saving files. It provides a graphical interface for users to select files or
directories, making it a convenient way to handle file input/output in desktop applications.
1. Modes:
o FileDialog.LOAD: Used for selecting files to open.
o FileDialog.SAVE: Used for selecting a file to save.
2. Platform-Dependent UI: The look and feel of the file dialog may vary depending on the
operating system.
3. User Interaction: Allows users to navigate directories, select files, or specify file names.
Constructors
1. FileDialog(Frame parent)
Creates a file dialog with a default title in the LOAD mode.
2. FileDialog(Frame parent, String title)
Creates a file dialog with the specified title in the LOAD mode.
3. FileDialog(Frame parent, String title, int mode)
Creates a file dialog with the specified title and mode (LOAD or SAVE).
Methods
1. setVisible(boolean visible)
Displays or hides the file dialog.
2. getFile()
Returns the name of the selected file as a String. If no file is selected, it returns null.
3. getDirectory()
Returns the directory of the selected file as a String. If no file is selected, it
returns null.
4. setFile(String file)
Sets a default file name to display in the dialog.
5. setDirectory(String dir)
Sets the default directory to open when the dialog is displayed.
6. getMode()
Returns the mode of the file dialog (LOAD or SAVE).
java
Copy code
import java.awt.*;
import java.awt.event.*;
if (fileName != null) {
System.out.println("File Selected: " + directory + fileName);
} else {
System.out.println("No file selected.");
}
});
// Set main frame properties
frame.setSize(400, 300);
frame.setLayout(null);
frame.setVisible(true);
}
}
java
Copy code
import java.awt.*;
import java.awt.event.*;
if (fileName != null) {
System.out.println("File to Save: " + directory + fileName);
} else {
System.out.println("No file selected.");
}
});
Explanation
Key Points
1. Modes:
o Use FileDialog.LOAD for opening files.
o Use FileDialog.SAVE for saving files.
2. Null Checks:
o Always check if getFile() returns null to handle cases where the user cancels
the operation.
3. Default Directory/File:
o Use setDirectory() and setFile() to set default values for the file dialog.
Advantages
Disadvantages
By using FileDialog, you can easily integrate file selection and saving capabilities into your
Java AWT applications
Extending classes
In Java AWT, you can handle events by extending components like Button, Frame, Canvas,
etc., and overriding their event-handling methods. This approach allows you to customize the
behavior of AWT components and integrate event-handling logic directly within the extended
class.
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Custom Button clicked: " + getLabel());
}
}
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setVisible(true);
}
}
Explanation
public CustomFrame() {
super("Custom Frame Example");
addMouseListener(this); // Add mouse listener to the frame
setSize(400, 300);
setVisible(true);
}
@Override
public void paint(Graphics g) {
g.drawString(message, 50, 100); // Display the message
}
// Implement MouseListener methods
@Override
public void mouseClicked(MouseEvent e) {
message = "Mouse Clicked at (" + e.getX() + ", " + e.getY() + ")";
repaint();
}
@Override
public void mousePressed(MouseEvent e) {
message = "Mouse Pressed at (" + e.getX() + ", " + e.getY() + ")";
repaint();
}
@Override
public void mouseReleased(MouseEvent e) {
message = "Mouse Released";
repaint();
}
@Override
public void mouseEntered(MouseEvent e) {
message = "Mouse Entered the Frame";
repaint();
}
@Override
public void mouseExited(MouseEvent e) {
message = "Mouse Exited the Frame";
repaint();
}
}
Explanation
public CustomCanvas() {
setSize(400, 300);
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
});
}
@Override
public void paint(Graphics g) {
if (x >= 0 && y >= 0) {
g.setColor(Color.RED);
g.fillOval(x - 10, y - 10, 20, 20); // Draw a circle at the
clicked position
}
}
}
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setVisible(true);
}
}
Explanation
1. Custom Canvas:
o Extends Canvas to create a drawable area.
o Handles mouseClicked to determine where to draw shapes.
2. Dynamic Drawing:
o Repaints the canvas to draw a circle at the clicked position.
1. Encapsulation:
o Combines custom functionality and event handling in one class.
2. Reusability:
o Custom components can be reused across multiple applications.
3. Simplified Logic:
o Keeps event handling and component logic tightly integrated.
Disadvantages
1. Less Modular:
o Extending components may reduce flexibility if used for simple tasks.
2. Complexity:
o Overloading event methods can make code harder to read for larger projects.
3. Inheritance Limitation:
o Java supports single inheritance, so extending a component restricts further
inheritance.
When to Use?
Use extending AWT components for custom behaviors or advanced features that are
not easily achievable through existing components.
For simple event handling, prefer using listeners attached to components instead of
extending them.
Controls Awt
In Java AWT (Abstract Window Toolkit), controls are the basic building blocks for creating
graphical user interfaces (GUIs). They are components like buttons, text fields, labels,
checkboxes, etc., that allow users to interact with the application.
Here’s a quick overview of the commonly used AWT controls and their purposes:
Control Description
Label Displays a single line of read-only text.
Button A clickable button that triggers an action.
TextField A single-line text input field.
TextArea A multi-line text input field.
Checkbox A box that can be checked or unchecked to toggle a setting.
CheckboxGroup Groups checkboxes so only one can be selected at a time (radio button group).
List Displays a list of items from which the user can select one or more.
Choice A dropdown menu for selecting one item.
Scrollbar A vertical or horizontal scroll bar for scrolling content.
Canvas A blank area for drawing or custom graphics.
Menu A menu item that can contain submenus or actions.
Examples of Controls
1. Label
java
Copy code
import java.awt.*;
frame.add(label);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
}
}
2. Button
java
Copy code
import java.awt.*;
import java.awt.event.*;
frame.add(button);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
3. TextField
java
Copy code
import java.awt.*;
import java.awt.event.*;
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
4. Checkbox
java
Copy code
import java.awt.*;
import java.awt.event.*;
button.addActionListener(e -> {
System.out.println("Option 1: " + checkbox1.getState());
System.out.println("Option 2: " + checkbox2.getState());
});
frame.add(checkbox1);
frame.add(checkbox2);
frame.add(button);
frame.setSize(300, 300);
frame.setLayout(null);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
java
Copy code
import java.awt.*;
frame.add(choice);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
AWT uses an event delegation model to handle user interactions with controls.
1. Event Source: The control triggering the event (e.g., Button).
2. Event Object: The event details encapsulated in an object (e.g., ActionEvent).
3. Event Listener: The interface implemented to handle the event (e.g., ActionListener).
Example:
java
Copy code
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Handle button click event
}
});
Limitations
1. Outdated: AWT lacks advanced features available in modern libraries like Swing or
JavaFX.
2. Limited Customization: Styling and advanced component behavior are harder to
achieve.
3. Native Dependency: Depends on the native OS for rendering, leading to inconsistent
behavior across platforms.
By mastering AWT controls, you can create simple GUI applications and gain a foundation for
more advanced Java GUI frameworks like Swing and JavaFX.
In Java AWT, Menus and Layout Managers are essential components that help structure and
organize the user interface (UI) of desktop applications.
Menus in AWT
Menus provide a way to offer a list of choices or commands in a graphical interface. Java AWT
provides several classes for creating menus and menu items. The key classes are:
Creating Menus
MenuBar: A menu bar is created and attached to the frame using frame.setMenuBar().
Menu: A "File" menu is created and populated with menu items (Open, Save, and Exit).
MenuItem: Each item in the menu triggers a specific action when clicked.
Separator: addSeparator() creates a visual line between menu items.
Event Handling: Each MenuItem has an event listener to handle user actions (e.g.,
opening or saving a file).
1. FlowLayout:
o Components are arranged in a left-to-right flow, one after the other.
o Components wrap to the next line when the container is full.
o By default, it centers components.
java
Copy code
frame.setLayout(new FlowLayout());
2. BorderLayout:
o Divides the container into five regions: North, South, East, West, and Center.
o Components are placed in one of these regions.
java
Copy code
frame.setLayout(new BorderLayout());
frame.add(button, BorderLayout.NORTH); // Place button in the North
3. GridLayout:
o Components are arranged in a grid with a specified number of rows and columns.
o All components are the same size.
java
Copy code
frame.setLayout(new GridLayout(2, 3)); // 2 rows, 3 columns
4. CardLayout:
o Allows multiple components (cards) to occupy the same space.
o Only one card is visible at a time.
o Useful for tabbed interfaces or wizards.
java
Copy code
frame.setLayout(new CardLayout());
5. GridBagLayout:
o A flexible and powerful layout manager that allows precise control over
component placement.
o Components are placed in a grid but can span multiple rows or columns.
java
Copy code
frame.setLayout(new GridBagLayout());
6. FlowLayout:
o The default layout manager for Panel and Frame.
o Organizes components sequentially, wrapping them as necessary.
java
Copy code
import java.awt.*;
public class FlowLayoutExample {
public static void main(String[] args) {
Frame frame = new Frame("FlowLayout Example");
frame.setSize(300, 200);
frame.setVisible(true);
java
Copy code
import java.awt.*;
frame.setSize(400, 300);
frame.setVisible(true);