Java Notes
Java Notes
JAVA PROGRAMMING
UNIT II: Inheritance: Basic concepts - Types of inheritance - Member access rules - Usage of this and
Super key word - Method Overloading - Method overriding - Abstract classes - Dynamic method dispatch
- Usage of final keyword. Packages:Definition-AccessProtection -ImportingPackages.
Interfaces:Definition–Implementation–Extending Interfaces. Exception Handling: try – catch- throw -
throws – finally – Built-inexceptions - Creating own Exception classes.
UNIT IV: AWT Controls: The AWT class hierarchy - user interface components- Labels - Button - Text
Components - Check Box - Check Box Group - Choice - List Box - Panels – Scroll Pane - Menu - Scroll
Bar. Working with Frame class - Colour - Fonts and layout managers. Event Handling: Events - Event
sources - Event Listeners - Event Delegation Model (EDM) - Handling Mouse and Keyboard Events -
Adapter classes - Inner classes
UNIT V: Swing: Introduction to Swing - Hierarchy of swing components. Containers - Top level
containers - JFrame - JWindow - JDialog - JPanel - JButton - JToggleButton - JCheckBox - JRadioButton
- JLabel,JTextField - JTextArea - JList - JComboBox - JScrollPane.
UNIT-I
Object-Oriented Programming (OOP) is a programming paradigm that revolves around the concept of
"objects." An object is an instance of a class, which encapsulates data (attributes) and behavior (methods).
This approach promotes modularity, reusability, and maintainability in software development.
History of Java
Java, created by Sun Microsystems (now owned by Oracle), was introduced in 1995. It was designed to be
platform-independent, "write once, run anywhere" language, making it highly portable. Java's popularity
soared due to its robustness, security, and versatility, leading to its widespread use in various domains,
including web development, enterprise applications, and mobile app development.
Java Buzzwords
Platform Independent: Java code can run on any platform with a Java Virtual Machine (JVM).
Object-Oriented: Java is a pure object-oriented language.
Robust: Java's strong type checking and exception handling mechanisms help prevent runtime
errors.
Secure: Java's security features, such as bytecode verification, protect against malicious code.
High Performance: Java's Just-In-Time (JIT) compilation and optimized bytecode execution
provide efficient performance.
Multi-threaded: Java supports concurrent programming, allowing multiple tasks to run
simultaneously.
Distributed: Java provides networking capabilities for distributed applications.
JVM Architecture
The Java Virtual Machine (JVM) is a virtual machine that executes Java bytecode. It consists of the
following components:
These are built-in data types that represent basic data values. They are directly stored in memory.
These are data types that refer to objects, which are instances of classes. They are stored in the heap
memory.
Example:
Key Points:
Primitive data types are stored directly in memory, while reference data types store references to
objects in the heap.
The size of primitive data types is fixed, while the size of reference data types can vary.
Primitive data types are passed by value, while reference data types are passed by reference.
By understanding these data types, you can effectively represent and manipulate data in your Java
programs.
Variables:
variable in Java is a named storage location that holds a value. It's like a container that can store
different types of data.
To use a variable, you must first declare it. This involves specifying the data type and the variable
name. You can also initialize a variable by assigning it a value at the time of declaration.
data_type variable_name;
data_type variable_name = value;
Example:
Scope refers to the region of a program where a variable is accessible. Lifetime refers to the period during
which a variable exists in memory.
1. Local Variables:
o Scope: Declared within a method or block. Accessible only within that block.
o Lifetime: Exists only while the method or block is executing. Once the block ends, the
variable is destroyed.
2. Instance Variables:
o Scope: Declared within a class but outside any method. Accessible to all methods within
the class.
o Lifetime: Exists as long as the object of the class exists. When the object is destroyed, the
instance variables are also destroyed.
3. Static Variables:
o Scope: Declared with the static keyword. Accessible to all instances of the class, as well as
from outside the class.
o Lifetime: Exists as long as the class is loaded. They are created when the class is loaded
and destroyed when the class is unloaded.
Example:
In this example:
Arrays:
An array is a collection of elements of the same data type. It provides a way to store multiple
values under a single variable name.
Types of Arrays:
1. One-Dimensional Arrays:
o A simple array that stores elements in a linear sequence.
o Declared using data_type[] array_name;
o Example:
2. Multi-Dimensional Arrays:
o Arrays of arrays, used to represent matrices or tables.
o Declared using data_type[][] array_name;
o Example:
Array Operations:
}
Sorting an array:
Arrays.sort(numbers);
Operators
Operators in Java
Operators are symbols that perform specific operations on variables and values. They are the
building blocks of expressions in Java, allowing you to perform calculations, comparisons, and more.
1. Arithmetic Operators:
2. Assignment Operators:
3. Relational Operators:
4. Logical Operators:
5. Unary Operators:
6. Bitwise Operators:
7. Ternary Operator:
?: A conditional operator that evaluates an expression and returns one of two values based on the
result.
Control Statements
Control statements are essential in programming to alter the normal flow of execution based on certain
conditions or to repeat a block of code multiple times. Java provides a variety of control statements to
achieve these objectives:
if Statement:
o Executes a block of code if a specified condition is true.
if (condition) {
// code to be executed if condition is true
}
if-else Statement:
o Executes one block of code if a condition is true, and another block if it's false.
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
if-else-if Ladder:
o Allows for multiple conditions to be checked sequentially.
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else if (condition3) {
// code to be executed if condition3 is true
} else {
// code to be executed if all conditions are false
switch Statement:
o Efficiently handles multiple choices based on the value of an expression.
switch (expression) {
case value1:
// code to be executed if expression equals value1
break;
case value2:
// code to be executed if expression equals value2
break;
default:
// code to be executed
if no case matches
}
2. Looping Statements:
for Loop:
o Repeats a block of code a specific number of times.
while Loop:
o Repeats a block of code as long as a specified condition is true.
while (condition) {
// code to be repeated
}
do-while Loop:
o Executes a block of code at least once, and then repeats as long as a specified condition is
true.
do {
// code to be repeated
} while (condition);
By effectively using these control statements, you can create dynamic and flexible Java programs
that can make decisions, repeat actions, and control the flow of execution based on specific conditions.
Java automatically performs implicit type conversion when assigning a smaller data type to a
larger one. This is known as widening conversion. Here's an example:
byte b = 10;
int i = b; // Implicit conversion from byte to int
When converting a larger data type to a smaller one, explicit type conversion is required. This is
known as narrowing conversion. It's important to note that narrowing conversion can lead to loss of
precision or data. Here's an example:
double d = 3.14;
int i = (int) d; // Explicit conversion from double to int
In this case, the double value 3.14 is explicitly converted to an int value. However, the decimal part is
truncated, resulting in the value 3.
Casting
Casting is the process of converting one data type to another explicitly using the cast operator (). It's often
used in narrowing conversions to avoid potential errors.
Example:
double d = 3.14;
int i = (int) d; // Casting double to int
Loss of Precision: Be aware of potential loss of precision when converting larger data types to
smaller ones.
Data Overflow: Ensure that the target data type can accommodate the value being converted.
Use Casting Judiciously: Cast only when necessary and be mindful of the potential consequences.
Check for Potential Errors: Always verify the correctness of the conversion, especially when
dealing with complex expressions.
Constructors
A constructor is a special method in Java that is automatically called when an object of a class is
created. It's primarily used to initialize the object's state.
1. Name: The constructor's name must be the same as the class name.
2. Return Type: Constructors do not have a return type, not even void.
3. Invocation: Constructors are invoked automatically when you create an object using the new
keyword.
Types of Constructors:
1. Default Constructor:
o A default constructor is a no-argument constructor that is automatically provided by the
compiler if you don't explicitly define any constructors.
o It initializes the object's instance variables to their default values.
2. Parameterized Constructor:
o A parameterized constructor accepts arguments to initialize the object's instance variables.
o You can define multiple parameterized constructors with different argument lists to provide
flexibility in object creation.
Example:
class Car {
String color;
int year;
// Default constructor
public Car() {
color = "White";
year = 2023;
}
// Parameterized constructor
public Car(String color, int year) {
this.color = color;
this.year = year;
}
}
Methods
Methods are the building blocks of Java programs. They encapsulate a specific task or behavior and can
be reused throughout your code.
Example:
greet("Alice");
}
}
Key Points:
Method Overloading: You can define multiple methods with the same name but different
parameter lists.
Method Overriding: You can redefine a method in a subclass to provide a specific
implementation.
Recursion: A method can call itself directly or indirectly.
Method Signatures: The method signature consists of the method name and the parameter list. It's
used to uniquely identify a method.
Static Block
A static block is a block of code that is executed only once, when the class is first loaded into memory. It's
often used to initialize static variables or perform other one-time setup tasks.
Syntax:
static {
// Code to be executed once
}
Example:
}
}
Output:
Static Data
In Java, static data members are associated with the class itself, rather than with individual objects of the
class. This means that they are shared by all instances of the class.
Key Points:
Declaration:
o Static data members are declared using the static keyword.
o They can be variables or methods.
Memory Allocation:
o Static data members are allocated memory only once, when the class is loaded into
memory.
Access:
o They can be accessed directly using the class name, without creating an object.
Persistence:
o Static data members retain their values across different object instances.
Example:
public class MyClass {
static int count = 0; // Static variable
public void incrementCount() {
count++;
}
obj1.incrementCount();
obj2.incrementCount();
Static Method
A static method is a method that belongs to a class rather than an instance of a class. This means that you
can call a static method without creating an object of the class.
Key Points:
Declaration:
o Declared using the static keyword.
Access:
o Can be accessed directly using the class name.
No this Keyword:
o Cannot access instance variables or methods directly.
Common Use Cases:
o Utility methods: Methods that perform common tasks like mathematical calculations, string
manipulation, etc.
o Factory methods: Methods that create and return objects.
o Main method: The entry point of every Java application.
Example:
Explanation:
The add and calculateArea methods are static methods of the MathUtils class.
They can be called directly using the class name, without creating an object of the MathUtils class.
This is because static methods belong to the class itself, not to individual objects.
Key Considerations:
String Class
Key Methods:
StringBuffer Class
Key Methods:
append(str): Appends the specified string to the end of this character sequence.
insert(offset, str): Inserts the specified string into this character sequence.
deleteCharAt(index): Deletes the character at the specified index.
delete(startIndex, endIndex): Deletes the characters in a specified range.
replace(startIndex, endIndex, str): Replaces the characters in a specified range with a new
string.
reverse(): Reverses the character sequence.
Example:
public class StringAndStringBufferExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
// String concatenation
String str3 = str1 + " " + str2;
System.out.println(str3);
// StringBuffer
StringBuffer sb = new StringBuffer("Java");
sb.append(" Programming");
sb.insert(5, " is ");
System.out.println(sb);
}
}
String: Use for fixed character sequences that don't require modification.
StringBuffer: Use for frequent modifications to character sequences.
1 MARK:
a) Inheritance
b) Polymorphism
c) Encapsulation
d) Compilation
2. What is the process of binding data members and member functions together into a single
unit?
a) Inheritance
b) Encapsulation
c) Polymorphism
d) Abstraction
3. Who is the creator of Java?
a) Dennis Ritchie
b) James Gosling
c) Bjarne Stroustrup
d) Linus Torvalds
4. What does WORA stand for in the context of Java?
a) ClassLoader
c) Execution Engine
6. Which data type is used to represent decimal numbers with a fractional part?
a) int
b) float
c) char
d) boolean
a) Class-level
b) Method-level
c) Block-level
d) Global-level
a) 0
b) 1
c) -1
d) Array size
a) ||
b) &&
c) |
d) &
10. Which loop is best suited for iterating a fixed number of times?
a) while loop
b) do-while loop
c) for loop
d) switch-case
11. What is the process of converting a larger data type to a smaller data type called?
a) Widening conversion
b) Narrowing conversion
c) Implicit conversion
d) Explicit conversion
a) main method
b) static method
c) constructor
d) destructor
b) No
UNIT-II:
Inheritance is a powerful mechanism in object-oriented programming (OOP) that allows one class to
inherit the properties and behaviors of another class. This promotes code reusability and creates a
hierarchical relationship between classes.
Key Concepts
Parent Class (Superclass): The class whose properties and methods are inherited.
Child Class (Subclass): The class that inherits from the parent class.
Types of Inheritance
class Animal {
// ...
}
class Vehicle {
// ...
}
class Vehicle {
// ...
}
this keyword:
o Refers to the current object.
o Used to distinguish between instance variables and parameters with the same name.
o Used to call other constructors of the same class.
super keyword:
o Refers to the parent class object.
o Used to call parent class constructors.
o Used to access parent class members when there's a name conflict with child class
members.
Example:
class Animal {
void makeSound() {
System.out.println("Generic animal sound");
}
}
}
}
In this example, the Dog class inherits from the Animal class. It overrides the makeSound() method to
provide a specific implementation for dogs.
Code Reusability: Avoids redundant code by inheriting common properties and behaviors.
Polymorphism: Enables objects to take on many forms, promoting flexibility and extensibility.
Modularity: Encourages breaking down complex systems into smaller, more manageable units.
In Java, member access rules determine the visibility of class members (fields and methods) to
other classes. This is crucial for understanding how inheritance works and controlling the exposure of
your class's internals.
Here are the four primary access modifiers and their visibility rules:
1. Public:
o Accessible from anywhere: within the same class, package, or other classes.
o Declared using the public keyword.
2. Protected:
o Accessible within the same package and subclasses.
o Declared using the protected keyword.
3. Default (Package-Private):
o Accessible within the same package.
o Declared without any access modifier.
4. Private:
o Accessible only within the same class.
o Declared using the private keyword.
Example:
class Animal {
public String name; // Accessible anywhere
protected int age; // Accessible within the package and subclasses
private String color; // Accessible only within the Animal class
}
In Java, the this and super keywords are essential for understanding object-oriented programming
concepts. They provide a way to refer to specific objects and their members.
The this keyword refers to the current object. It's used in various scenarios:
1. Distinguishing Between Instance Variables and Parameters: When an instance variable and a
parameter have the same name, the this keyword can be used to differentiate between them.
class Person {
String name;
2. Calling Other Constructors: You can use this() to call another constructor of the same class.
class Person {
String name;
int age;
3. Returning the Current Object: You can use this to return the current object itself, often used in
method chaining.
Java
class StringBuilder {
// ...
public StringBuilder append(String str) {
// ...
return this; // Returns the current StringBuilder object
}
}
The super keyword refers to the parent class object. It's primarily used in the following scenarios:
1. Calling Parent Class Constructors: You can use super() to call the parent class's constructor.
2. Accessing Parent Class Members: You can use super to access members of the parent class when
there's a name conflict with a member in the child class.
class Animal {
void makeSound() {
System.out.println("Generic animal sound");
}
}
Method Overloading
Method overloading is a technique in Java that allows you to define multiple methods with the same
name but different parameter lists within the same class. The compiler differentiates between these
methods based on the number, type, and order of their parameters.
Key Points:
Same Method Name: All overloaded methods must have the same name.
Different Parameter Lists: The parameter lists must differ in terms of the number, type, or order
of parameters.
Return Type: The return type can be the same or different.
Example:
class Calculator {
public int add(int a, int b) {
return a + b;
}
}
}
In this example, we have three add methods with different parameter lists:
The compiler determines which overloaded method to call based on the arguments passed at the call site.
It matches the number, type, and order of the arguments with the parameter lists of the available methods.
Example Usage:
Overloaded methods must have different parameter lists, not just different return types.
Overloading does not involve inheritance. It's a technique within a single class.
Overloading can make code more flexible and readable by providing different ways to perform the
same operation.
Method Overriding
Key Points:
Same Method Signature: The overriding method in the subclass must have the same name, return
type, and parameter list as the original method in the parent class.
Access Modifiers: The overriding method's access modifier can be the same or more permissive
than the original method's access modifier. For example, a protected method can be overridden
with a public method.
Dynamic Binding: The appropriate method to be called is determined at runtime based on the
actual object type, not the declared type. This is known as polymorphism.
Example:
class Animal {
public void makeSound() {
System.out.println("Generic animal sound");
}
}
}
}
In this example:
1. The Animal class has a makeSound() method that prints a generic sound.
2. The Dog class inherits from Animal and overrides the makeSound() method to print a specific
sound for dogs.
When we create a Dog object and call the makeSound() method on it, the overridden version from the Dog
class will be executed.
Abstract Classes
An abstract class is a class that cannot be instantiated directly. It serves as a blueprint for other classes,
defining common attributes and behaviors. Abstract classes often contain one or more abstract methods,
which are methods declared without a body. Subclasses must provide implementations for these abstract
methods.
Example:
Dynamic method dispatch, also known as late binding or runtime polymorphism, is the process of
determining the appropriate method to call at runtime based on the actual object type, not the declared
type. This allows for flexible and extensible code.
Based on object type: The method to be called is determined by the object's actual type, not the
reference variable's declared type.
Occurs at runtime: The decision is made at runtime, not at compile time.
Requires inheritance: Dynamic method dispatch relies on inheritance to create a hierarchy of
classes.
Example:
1. Final Variables:
o Declares a constant variable whose value cannot be changed after initialization.
o Can be used with primitive data types and reference types.
2. Final Methods:
o Prevents a method from being overridden by subclasses.
o Ensures that the method's behavior remains consistent across the inheritance hierarchy.
3. Final Classes:
o Prevents a class from being subclassed.
o Ensures that the class's behavior cannot be modified by inheritance.
Example:
public ImmutableClass(int x) {
this.x = x;
}
public int getX() {
return x;
}
}
Combining Concepts
Abstract classes, dynamic method dispatch, and the final keyword work together to create
powerful and flexible object-oriented designs. By using abstract classes to define common interfaces and
dynamic method dispatch to select the appropriate implementation at runtime, you can create code that is
both adaptable and efficient. The final keyword can be used to control the mutability of variables, the
overridability of methods, and the subclassability of classes.
PACKAGE:
In Java, a package is a mechanism to group related classes, interfaces, and sub-packages. It's like a
container that organizes your code into a hierarchical structure, making it more manageable and reusable.
1. Namespace Management:
o Prevents naming conflicts between classes with the same name but different functionalities.
o Each class belongs to a specific package, creating a unique identifier.
2. Code Organization:
o Groups related classes and interfaces together, improving code readability and
maintainability.
o Makes it easier to find and understand specific classes within a project.
3. Access Control:
o Provides control over the visibility of classes and interfaces.
o Packages can define access levels (public, protected, default, private) to restrict access to
certain parts of your code.
4. Reusability:
o Encapsulates reusable code components into packages that can be shared across different
projects.
Example:
package com.example.myproject;
In this example, com.example.myproject is the package name. All classes defined within this file belong
to this package.
In Java, access protection refers to the control over the visibility of classes, interfaces, and their members
(methods and variables) across different packages. This is achieved through the use of access modifiers.
1. Public:
o Accessible from anywhere, including other packages.
o Declared using the public keyword.
2. Protected:
o Accessible within the same package and subclasses in other packages.
o Declared using the protected keyword.
3. Default (Package-Private):
o Accessible within the same package only.
o No keyword is used to declare it.
4. Private:
o Accessible only within the same class.
o Declared using the private keyword.
Example:
package com.example.package1;
package
com.example.package2;
publicMethod(); // Accessible
protectedMethod(); // Accessible
// defaultMethod(); // Not accessible
// privateMethod(); // Not accessible
}
}
IMPORTING PACKAGES:
n Java, you can import classes and interfaces from other packages to use them in your code. This is
done using the import statement.
Syntax:
import package_name.class_name;
Example:
import java.util.Scanner;
In this example, we import the Scanner class from the java.util package. This allows us to create a
Scanner object to read input from the user.
import java.util.*;
However, it's generally recommended to import only the specific classes you need. Importing all
classes can make your code less readable and can potentially introduce naming conflicts.
Package Hierarchy:
Java packages can be organized in a hierarchical structure. To import a class from a subpackage,
you can use the following syntax:
import package_name.subpackage_name.class_name;
Example:
import java.util.ArrayList;
import java.util.List;
// ...
}
}
Important Considerations:
Default Package: If a class is not explicitly declared in a package, it belongs to the default
package. Classes in the default package can only be accessed from other classes in the same
package.
Fully Qualified Names: If you don't import a class, you can still use it by specifying its fully
qualified name:
INTERFACES:
Definition:
An interface in Java is a blueprint of a class. It defines a set of abstract methods that a class must
implement. Interfaces are used to achieve abstraction and polymorphism.
Key Points:
Implementation:
A class implements an interface using the implements keyword. It must provide implementations for all
the abstract methods defined in the interface.
Example:
interface Drawable {
void draw();
}
}
}
Extending Interfaces:
Interfaces can extend other interfaces. This allows for creating hierarchical relationships between
interfaces.
Example:
interface Shape {
void draw();
}
interface Colorable {
void setColor(String color);
}
@Override
public void setColor(String color) {
System.out.println("Setting color to " + color);
}
}
Advantages of Using Interfaces:
Abstraction: Interfaces provide a clear abstraction of what a class should be able to do, without
specifying how it's done.
Polymorphism: Different classes can implement the same interface, allowing for polymorphic
behavior.
Loose Coupling: Interfaces promote loose coupling between classes, making code more modular
and easier to maintain.
Multiple Inheritance: A class can implement multiple interfaces, unlike class inheritance, which
is single.
Design Patterns: Interfaces are essential in many design patterns, such as the Strategy, Observer,
and Factory patterns.
Exception handling is a mechanism to handle errors and unexpected events that may occur during program
execution. It helps in preventing program crashes and provides a graceful way to handle errors.
Key Concepts:
1. Try-Catch Block:
o The try block encloses the code that might throw an exception.
o The catch block handles the exception if it occurs.
try {
// Code that might throw an exception
} catch (ExceptionType exceptionObject) {
// Handle the exception
}
2. Throw Keyword:
o The throw keyword is used to explicitly throw an exception.
3. Throws Keyword:
o The throws keyword is used to declare that a method might throw an exception.
4. Finally Block:
o The finally block is executed regardless of whether an exception is thrown or caught. It's
often used for cleanup tasks like closing files or database connections.
try {
// Code that might throw an exception
} catch (Exception e) {
// Handle the exception
} finally {
// Code to be executed always
}
Built-in Exceptions:
Java provides a rich set of built-in exceptions, categorized into different hierarchies. Some common
exceptions include:
You can create your own custom exception classes by extending the Exception class or one of its
subclasses.
By following these guidelines and using exception handling effectively, you can write robust and reliable
Java applications.
1 Mark:
Inheritance:
a) Single inheritance
b) Multiple inheritance
c) Hierarchical inheritance
d) Hybrid inheritance
2. Which access modifier can be used to make a member accessible within the same package
and subclasses?
a) public
b) private
c) protected
d) default
a) Method overloading involves different return types, while method overriding involves different
parameter lists.
b) Method overloading involves different parameter lists, while method overriding involves
the same method signature but different implementations.
c) Method overloading involves the same method signature but different implementations, while
method overriding involves different parameter lists.
a) public
b) private
c) protected
d) default
a) Yes
b) No
a) Yes
b) No
a) To handle exceptions.
b) To throw exceptions.
a) extends
b) implements
c) inherits
d) derives
12. What is the process of creating new classes from existing ones called?
a) Polymorphism
b) Encapsulation
c) Inheritance
d) Abstraction
13. What is the access specifier that allows a class to be accessed from any package?
a) public
b) private
c) protected
d) default
a) self
b) this
c) current
d) instance
14. What is the process of having two or more methods with the same name but different
parameters called?
a) Method overriding
b) Method overloading
c) Method hiding
d) Method binding
15. Which type of inheritance involves a class inheriting from multiple parent classes?
a) Single inheritance
b) Multiple inheritance
c) Hierarchical inheritance
d) Multilevel inheritance
Answer: b) Multiple inheritance (Note: Java doesn't directly support multiple inheritance, but
it can be achieved using interfaces.)
a) catch
b) throw
c) throws
d) finally
19. Which block of code is always executed, regardless of whether an exception occurs?
a) try
b) catch
c) finally
d) throw
UNIT-III
Multithreaded Programming:
Key Concepts:
1. Thread:
o A basic unit of execution within a process.
o Each thread has its own program counter, stack, and local variables.
o Multiple threads can share the same heap memory.
2. Thread Creation:
o Extending the Thread class: Create a new class that extends the Thread class and override
the run() method.
o Implementing the Runnable interface: Create a new class that implements the Runnable
interface and implement the run() method.
3. Thread Lifecycle:
o New: Thread is created but not yet started.
o Runnable: Thread is ready to run but waiting for CPU time.
o Running: Thread is currently executing.
o Blocked: Thread is waiting for a resource or event.
o Terminated: Thread has finished execution.
4. Thread Synchronization:
o Ensures that multiple threads access shared resources in a controlled manner.
o Techniques:
Synchronized methods: Only one thread can execute a synchronized method on a
particular object at a time.
Synchronized blocks: A specific block of code is synchronized, allowing multiple
threads to access other parts of the object concurrently.
Volatile keyword: Ensures that changes to a variable are visible to all threads.
5. Inter-Thread Communication:
o wait() and notify(): Used to pause and resume threads.
o join(): Waits for a thread to finish execution.
6. Deadlock:
o Occurs when two or more threads are blocked, waiting for each other to release a resource.
o To avoid deadlock:
Acquire locks in a specific order.
Use timeouts for acquiring locks.
Avoid nested locks.
Example:
Benefits of Multithreading:
Challenges of Multithreading:
By understanding these concepts and best practices, you can effectively leverage multithreading to create
efficient and responsive applications.
The Thread class in Java represents an individual thread of execution. It provides a way to create and
manage multiple threads within a single process.
Creating a Thread:
Starting a Thread:
To start a thread, call the start() method on the Thread object. This method creates a new thread and
invokes the run() method.
Thread Lifecycle:
Thread Synchronization:
To ensure thread safety when multiple threads access shared resources, you can use synchronization
mechanisms like:
Synchronized methods:
o Only one thread can execute a synchronized method on a particular object at a time.
Synchronized blocks:
o A specific block of code is synchronized, allowing multiple threads to access other parts of
the object concurrently.
Volatile keyword:
o Ensures that changes to a variable are visible to all threads.
Inter-Thread Communication:
In Java, the Runnable interface is a fundamental building block for creating and managing threads. It
defines a single method, run(), which contains the code to be executed by the thread.
To create a thread using the Runnable interface, you follow these steps:
1. Create a class:
o Define a class that implements the Runnable interface.
Example:
}
}
Multiple inheritance: A class can implement multiple interfaces, including Runnable, whereas
Java doesn't support multiple inheritance for classes.
Flexibility: You can create multiple Thread objects with the same Runnable object, sharing the
same run() method.
Synchronization in Java
Synchronization is a crucial concept in multithreaded programming to ensure that multiple threads access
shared resources in a controlled manner. It prevents race conditions and data corruption.Methods of
Synchronization:
1. Synchronized Methods:
o Declared with the synchronized keyword.
o Only one thread can execute a synchronized method on a particular object at a time.
2. Synchronized Blocks:
o More granular control over synchronization.
o A specific block of code is synchronized, allowing multiple threads to access other parts of
the object concurrently.
3. Volatile Keyword:
o Ensures that changes to a variable are visible to all threads.
o It's useful for simple shared variables that don't require complex synchronization.
Inter-Thread Communication:
Deadlocks:
Occur when two or more threads are blocked, waiting for each other to release a resource.
To avoid deadlocks:
o Acquire locks in a specific order.
o Use timeouts for acquiring locks.
o Avoid nested locks.
Example:
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Final
count: " + counter.getCount());
}
}
Synchronized methods are a powerful tool in Java for ensuring thread safety when multiple threads
access shared resources. By declaring a method as synchronized, you guarantee that only one thread can
execute that method on a specific object at a time.
How it works:
1. Implicit Locking: When a thread enters a synchronized method, it acquires a lock on the object
associated with that method.
2. Exclusive Access: While one thread holds the lock, other threads attempting to enter the same
synchronized method on the same object are blocked.
3. Releasing the Lock: Once the thread finishes executing the synchronized method, it releases the
lock, allowing other waiting threads to acquire it.
Example:
class Counter {
private int count = 0;
}
}
In this example, the increment() method is synchronized, ensuring that only one thread can modify
the count variable at a time. This prevents race conditions and ensures that the count value is accurate.
Protecting shared mutable state: When multiple threads access and modify the same shared
object.
Simple synchronization scenarios: For straightforward synchronization needs, synchronized
methods can be a convenient solution.
Granularity: Use synchronized methods judiciously. Overusing them can lead to performance
bottlenecks.
Deadlocks: Be careful to avoid deadlocks, especially when using multiple locks.
Performance Impact: Synchronized methods can impact performance, so use them only when
necessary.
Alternative Approaches: Consider using higher-level concurrency utilities like
java.util.concurrent for more complex synchronization scenarios.
Remember:
Synchronized methods can be applied to both instance methods and static methods.
For static methods, the lock is associated with the class object.
While synchronized methods are a useful tool, it's essential to balance synchronization with
performance considerations.
Syntax:
synchronized (object) {
// Critical section of code
}
How it works:
1. Acquiring the Lock: When a thread enters a synchronized block, it acquires a lock on the
specified object.
2. Exclusive Access: Only one thread can hold the lock at a time. Other threads trying to enter the
same synchronized block will be blocked until the lock is released.
3. Releasing the Lock: Once the thread finishes executing the critical section, it releases the lock
Example:
class Counter {
private int count = 0;
In this example, the increment() method synchronizes only the critical section of code that
modifies the count variable. This allows other parts of the method to execute concurrently without
blocking.
Granular Control: You can synchronize specific parts of your code, reducing the impact on
performance.
Flexibility: You can use different objects as locks to synchronize different sections of code.
Considerations:
Best Practices:
Inter-Thread Communication
Inter-thread communication refers to the mechanisms by which threads can interact and synchronize with
each other. It's essential for coordinating the activities of multiple threads and ensuring proper data sharing
and synchronization.
Key Techniques:
2. join():
o Waits for a thread to finish execution before proceeding.
3. volatile Keyword:
o Ensures that changes to a variable are visible to all threads.
o Useful for simple shared variables that don't require complex synchronization.
Important Considerations:
Deadlock
A deadlock occurs when two or more threads are blocked indefinitely, each waiting for a resource held by
another thread. This creates a circular dependency, preventing any thread from making progress.
Causes of Deadlock:
Preventing Deadlocks:
Example:
class DeadlockExample {
public static void main(String[] args) {
Object lock1 = new Object();
Object lock2 = new Object();
Thread
t2 = new Thread(() -> {
synchronized (lock2) {
System.out.println("Thread 2: Acquired lock2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock1) {
System.out.println("Thread 2: Acquired lock1");
}
}
});
t1.start();
t2.start();
}
}
In this example, both threads try to acquire locks on lock1 and lock2 in different orders, leading to a
deadlock.
To avoid deadlocks in this scenario, you can acquire locks in a consistent order across all threads
or use more advanced synchronization mechanisms like semaphores or condition variables.
I/O Streams
In Java, I/O streams provide a mechanism for reading and writing data to various sources and destinations.
They are categorized into two main types:
1. Byte Streams:
Common Classes:
2. Character Streams:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
System.out.println("Hello, World!");
System.out.print("This is a line of text.");
File Handling:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
Concepts of Streams
In Java, streams are a sequence of data that flows from a source to a destination. They provide a
convenient way to read and write data.
Key Concepts:
1. Byte Streams:
o Deal with raw bytes.
o Used for binary data like images, audio, and executable files.
o Common classes: FileInputStream, FileOutputStream, BufferedInputStream,
BufferedOutputStream.
2. Character Streams:
o Deal with characters.
o Used for text-based data like plain text files, HTML, and XML.
o Common classes: FileReader, FileWriter, BufferedReader, BufferedWriter,
InputStreamReader, OutputStreamWriter.
3. Buffered Streams:
o Improve performance by reading or writing data in large chunks.
o Reduce the number of system calls.
4. Piped Streams:
o Allow communication between threads using pipes.
o One thread writes to the pipe, and another thread reads from it.
5. Filter Streams:
o Modify or filter the data being read or written.
o Examples: DataInputStream, DataOutputStream, PrintWriter, BufferedReader.
Common Operations:
Reading:
o Read a single byte or character.
o Read a specific number of bytes or characters.
o Read a line of text.
Writing:
o Write a single byte or character.
o Write a specific number of bytes or characters.
o Write a line of text.
import java.io.*;
}
bufferedReader.close();
reader.close();
}
}
In Java, streams are a sequence of data that flows from a source to a destination. They are used for
input and output operations. Java provides two types of streams:
Byte Streams
Key Classes:
Character Streams
Key Classes:
Common Operations:
Reading:
o read(): Reads a single character or byte.
o read(char[] buffer): Reads a block of characters or bytes into a buffer.
o readLine(): Reads a line of text.
Writing:
o write(int c): Writes a single character or byte.
o write(char[] cbuf): Writes an array of characters or bytes.
o write(String str): Writes a string.
import java.io.*;
}
bufferedReader.close();
reader.close();
}
}
In Java, I/O operations are primarily handled through streams. These streams are categorized into two
types: byte streams and character streams.
Byte Streams
Byte streams deal with raw bytes of data. They are suitable for handling binary data like images, audio,
and executable files.
Key classes:
Character streams deal with text data. They are suitable for handling text files, HTML, and other text-
based formats.
Key classes:
Key Differences:
import java.io.*;
}
bufferedReader.close();
reader.close();
}
}
Important Considerations:
Close Streams: Always close streams after use to release system resources.
Error Handling: Use try-catch blocks to handle potential exceptions like IOException.
Buffering: Use buffered streams to improve performance by reducing the number of system calls.
Encoding: Specify the character encoding when working with character streams.
By understanding the differences between byte and character streams and using the appropriate classes,
you can effectively handle various I/O operations in Java.
import java.util.Scanner;
Explanation:
1. Import Scanner: Import the Scanner class from the java.util package.
2. Create a Scanner object: Create a Scanner object to read input from the standard input stream
(System.in).
3. Read input: Use the nextLine() method to read a complete line of input from the console.
4. Process the input: Process the input as needed. In this example, we simply print a greeting
message.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class
ReadConsoleInput {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Hello,
" + name + "!");
}
}
Explanation:
1. Import classes: Import the necessary classes for reading console input.
2. Create a BufferedReader object: Create a BufferedReader object to read input from the standard
input stream.
3. Read input: Use the readLine() method to read a complete line of input.
4. Process the input: Process the input as needed.
Using System.out.println():
Explanation:
System.out.println() prints the specified text to the console and adds a newline character.
Using System.out.print():
System.out.print() prints the specified text to the console without adding a newline character.
1 MARK:
1. What is the primary difference between extending Thread and implementing Runnable?
3. What is a deadlock?
a) A state where two or more threads are blocked, waiting for each other.
a) FileReader
b) FileWriter
c) FileInputStream
d) BufferedReader
5. What is the purpose of a buffer in I/O operations?
a) read()
b) readLine()
c) next()
d) get()
7. What is a thread?
a) A lightweight process
b) A heavy-weight process
c) A function
d) A variable
a) Runnable
b) Thread
c) Process
d) Task
a) A state where two or more threads are blocked, waiting for each other
a) A sequence of bytes
b) A sequence of characters
c) A sequence of objects
d) A sequence of data
12. Which class is used to read characters from a character-based input stream?
a) InputStreamReader
b) BufferedReader
c) FileReader
d) DataInputStream
a) PrintWriter
b) FileWriter
c) BufferedWriter
d) DataOutputStream
14. Which class is used to read and write primitive data types to a file?
a) DataInputStream
b) DataOutputStream
c) FileInputStream
d) FileOutputStream
5-MARK & 10 MARK
6. Explain the difference between byte streams and character streams. Provide examples of their
usage.
7. Discuss the concept of buffering in I/O operations. How does it improve performance?
8. Write a Java program to read a file line by line and print each line to the console.
9. Explain the concept of file handling in Java. Discuss the use of File, FileReader, and FileWriter
classes.
10. How can you read user input from the console in Java? Provide a code example.
UNIT-IV:
The Abstract Window Toolkit (AWT) is a platform-independent API for creating graphical user
interfaces (GUIs) in Java. It provides a hierarchy of classes to build various UI components.
java.lang.Object
|- java.awt.Component
|- java.awt.Container
|- java.awt.Panel
|- java.awt.Window
|- java.awt.Frame
|- java.awt.Dialog
Additional Components:
Java provides a rich set of tools and libraries for creating user interfaces. Two primary toolkits are
commonly used:
Basic Components:
o Label: Displays text or images.
o Button: Triggers actions when clicked.
o TextField: Allows single-line text input.
o TextArea: Allows multi-line text input.
o Checkbox: Selects or deselects an option.
o CheckboxGroup: Groups checkboxes for exclusive selection.
o Choice: Presents a dropdown list of options.
o List: Displays a scrollable list of items.
o Scrollbar: Allows scrolling through content.
o Menu: Creates hierarchical menus.
oPopupMenu: Displays a context menu on right-click.
oPanel: Organizes and groups components.
oFrame: Creates a top-level window.
oDialog: Creates a modal or modeless dialog box.
Layout Managers:
o FlowLayout: Arranges components in a row or column.
o BorderLayout: Divides the container into five regions: North, South, East, West, and
Center.
o GridLayout: Arranges components in a grid.
o CardLayout: Displays one component at a time.
o GridBagLayout: Provides flexible layout with precise control over component placement.
2. Swing:
Basic Components:
o JButton: Similar to AWT Button, but more customizable.
o JLabel: Similar to AWT Label, but more flexible.
o JTextField: Similar to AWT TextField, but with additional features.
o JTextArea: Similar to AWT TextArea, but with additional features.
o JCheckBox: Similar to AWT Checkbox, but more customizable.
o JRadioButton: Similar to AWT CheckboxGroup, but for radio buttons.
o JComboBox: Similar to AWT Choice, but more flexible.
o JList: Similar to AWT List, but more customizable.
o JScrollPane: Provides scrollable views of large components.
o JMenu: Creates hierarchical menus.
o JMenuItem: An individual item in a menu.
o JPanel: Organizes and groups components.
o JFrame: Creates a top-level window.
o JDialog: Creates a modal or modeless dialog box.
Advanced Components:
o JTable: Displays tabular data.
o JTree: Displays hierarchical data.
o JProgressBar: Displays progress.
o JSlider: Allows users to select a value from a range.
o JSplitPane: Divides a container into two scrollable panes.
o JTabbedPane: Displays multiple components in tabs.
Key Considerations:
Labels:
In Java, labels are used to identify specific points within a code block, primarily to control the flow of
nested loops using break and continue statements.
Syntax:
label: statement;
Buttons:
Buttons are essential UI components in Java that trigger specific actions when clicked. They are used to
initiate various operations, such as submitting forms, opening dialogs, or executing commands.
Example (Swing):
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
JButton
button = new JButton("Click Me");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent
e) {
System.out.println("Button clicked!");
}
});
frame.add(button);
frame.setVisible(true);
}
}
Text Components:
Text components are essential UI elements that allow users to input and display text. Java provides
various text components, primarily through the AWT and Swing libraries.
Key Concepts:
Text Input and Output: Text components can be used to both display text to the user and receive
input from the user.
Event Handling: Event listeners can be attached to text components to handle user input events,
such as keystrokes and mouse clicks.
Formatting: Text components can be formatted using fonts, colors, and styles.
Validation: Input can be validated to ensure it meets specific criteria.
Check Boxes
Check boxes are UI elements that allow users to select or deselect an option. They are commonly used to
represent binary choices or to enable multiple selections.
Check box groups allow you to group multiple check boxes together, often to restrict the selection to a
specific number of options.
CheckboxGroup Class: Groups check boxes together, allowing only one to be selected at a time.
Example (Swing):
Java
import javax.swing.*;
group.add(checkBox1);
group.add(checkBox2);
group.add(checkBox3);
frame.add(checkBox1);
frame.add(checkBox2);
frame.add(checkBox3);
frame.setVisible(true);
}
}
Choice:
A Choice component presents a drop-down list of options. The user can select one option from the list.
List Box:
A List component displays a scrollable list of items. The user can select one or multiple items from
the list.
Example (Swing):
import javax.swing.*;
JList<String> list = new JList<>(new String[]{"Item 1", "Item 2", "Item 3"});
frame.add(choice, BorderLayout.NORTH);
frame.add(new JScrollPane(list), BorderLayout.CENTER);
frame.setVisible(true);
}
}
Panels: Panels are container components that organize other components. They are used to group related
components and to create complex layouts.
Scroll Pane: A JScrollPane provides scrollable views of large components. It is often used with
JTextArea, JList, and other components that may exceed the visible area.
Menu: A Menu component creates a hierarchical menu structure. It can be a menu bar or a popup menu.
Scroll Bar: A Scrollbar component allows users to scroll through content that exceeds the visible area.
Frame: A Frame is a top-level window with a title bar, menu bar, and borders. It is used to create
standalone applications.
Color: You can set the color of components using the Color class.
Fonts: You can customize the font of text using the Font class.
Layout Managers: Layout managers are used to organize components within a container. Java provides
several layout managers:
Event Handling:
Event handling is a fundamental concept in Java programming that allows applications to respond
to user interactions and system events. It involves three main components:
Event Sources :
In Java, event sources are objects that can generate events. These events can be triggered by user
interactions, system events, or other actions. Once an event is generated, it's sent to registered listeners for
processing.
Common Event Sources:
1. UI Components:
o Buttons
o Text fields
o Text areas
o Checkboxes
o Radio buttons
o Combo boxes
o Lists
o Menus
o Scrollbars
2. Window Events:
o Window opening
o Window closing
o Window resizing
o Window activation/deactivation
3. Mouse Events:
o Mouse clicks
o Mouse drags
o Mouse movements
4. Keyboard Events:
o Key presses
o Key releases
5. Timer Events:
o Time intervals
import javax.swing.*;
import java.awt.event.*;
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent
e) {
System.out.println("Button clicked!");
}
});
frame.add(button);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Event Listeners:
Event listeners are objects that implement specific interfaces to listen for and handle events generated by
event sources. When an event occurs, the event source notifies the registered listeners, and their respective
methods are invoked.
1. ActionListener:
o Listens for action events, such as button clicks.
o actionPerformed() method is invoked when the event occurs.
2. MouseListener:
o Listens for mouse events, such as clicks, presses, releases, and movements.
o Methods like mouseClicked(), mousePressed(), mouseReleased(), mouseEntered(), and
mouseExited() are invoked.
3. MouseMotionListener:
o Listens for mouse motion events, such as dragging and moving.
o Methods like mouseDragged() and mouseMoved() are invoked.
4. KeyListener:
o Listens for keyboard events, such as key presses and releases.
o Methods like keyPressed(), keyReleased(), and keyTyped() are invoked.
5. ItemListener:
o Listens for item events, such as selecting an item from a list or a choice.
o itemStateChanged() method is invoked when the item's state changes.
The Event Delegation Model (EDM) is a design pattern used in Java to handle events efficiently. It
involves the following steps:
1. Event Source: An object generates an event, such as a button click or a mouse movement.
2. Event Object: The event source creates an event object that encapsulates information about the
event, like the type of event and the source object.
3. Event Listener: An object that implements a specific listener interface, such as ActionListener,
MouseListener, or KeyListener.
4. Event Registration: The event listener is registered with the event source using methods like
addActionListener(), addMouseListener(), etc.
5. Event Dispatching: When the event occurs, the event source dispatches the event object to all
registered listeners.
6. Event Handling: Each registered listener receives the event object and processes it according to
its implementation.
Key Benefits of EDM:
Decoupling: It separates the event source from the event handler, promoting loose coupling and
modularity.
Flexibility: It allows multiple listeners to be registered to a single event source, enabling complex
event handling scenarios.
Reusability: Event listeners can be reused in different parts of the application.
Efficiency: The event source handles the dispatching of events, reducing the overhead on
individual components.
Java provides a robust mechanism for handling mouse and keyboard events. By using appropriate
event listeners, you can create interactive applications that respond to user input.
Mouse Events:
To handle mouse events, you can use the MouseListener and MouseMotionListener interfaces.
MouseListener:
mouseClicked(MouseEvent e): Invoked when the mouse button is clicked and released.
mousePressed(MouseEvent e): Invoked when the mouse button is pressed.
mouseReleased(MouseEvent e): Invoked when the mouse button is released.
mouseEntered(MouseEvent e): Invoked when the mouse enters a component's bounds.
mouseExited(MouseEvent e): Invoked when the mouse exits a component's bounds.
MouseMotionListener:
mouseDragged(MouseEvent e): Invoked when the mouse is dragged while a button is pressed.
mouseMoved(MouseEvent e): Invoked when the mouse is moved without a button pressed.
Example (Swing):
import javax.swing.*;
import java.awt.event.*;
add(panel);
setVisible(true);
}
Keyboard Events:
KeyListener:
Example (Swing):
import javax.swing.*;
import java.awt.event.*;
add(textField);
setVisible(true);
}
Adapter Classes:
Adapter classes are a design pattern used to adapt an existing interface to a new one. In the context
of Java event handling, adapter classes provide a convenient way to implement only the necessary
methods of an interface.
For example, if you want to handle only a few specific mouse events, you can create an adapter class that
extends the MouseAdapter class and override only the required methods. This avoids the need to
implement all the methods of the MouseListener interface, which can be tedious and unnecessary in many
cases.
Example:
import java.awt.event.*;
In this example, the MouseClickAdapter class extends MouseAdapter and overrides only the
mouseClicked() method. This allows you to handle mouse clicks without having to implement the other
methods of the MouseListener interface.
Reduced Boilerplate Code: You only need to implement the methods you're interested in.
Improved Readability: The code becomes more focused and easier to understand.
Increased Flexibility: You can create custom adapter classes for specific use cases.
Inner Classes:
Inner classes are classes defined within another class. They provide a way to encapsulate code and data
within a larger class, promoting modularity and code organization.
Example:
1 MARK:
a) Panel
b) Label
c) Frame
d) Button
2) Which layout manager positions components in a flow-like manner, wrapping to the next line if
necessary?
a) Border Layout
b) Grid Layout
c) Card Layout
d) Flow Layout
a) Mouse Listener
c) Key Listener
d) Action Listener
a) Choice
b) List
c) Panel
d) Scroll Pane
a) Action Listener
b) Mouse Listener
c) Key Listener
d) Item Listener
a) Action Listener
b) Mouse Listener
c) Key Listener
d) Item Listener
12) Which type of inner class can access both static and instance members of the outer class?
2. Discuss the five primary layout managers and their use cases.
5. Describe the following event listener interfaces and their corresponding events:
8. Write a Java program to create a Frame with a label, a text field, and a button.
9. How do you set the foreground and background colors of a component in AWT?
11. Write a Java program to create a Frame with a label and a button. The label should display a message
in a specific font and color.
15. Write a Java program to create a Frame with a button. Use an inner class to handle the button click
event and display a message in a dialog box.
UNIT-V:
Swing is a powerful and flexible GUI toolkit in Java that provides a rich set of components for creating
user interfaces. It offers a more advanced and customizable approach to building GUIs compared to AWT.
Top-Level Containers:
o JFrame: A standalone window with a title bar, menu bar, and borders.
o JDialog: A modal or modeless dialog box.
o JWindow: A lightweight window without a title bar or borders.
Containers:
o JPanel: A lightweight container for grouping components.
o JScrollPane: Provides scrollable views of large components.
Basic Components:
o JButton: A clickable button.
o JToggleButton: A button that can be toggled on and off.
o JCheckBox: A check box for selecting or deselecting options.
o JRadioButton: A radio button for selecting one option from a group.
o JLabel: A label for displaying text or images.
o JTextField: A single-line text input field.
o JTextArea: A multi-line text input area.
o JList: A list of items that can be selected.
o JComboBox: A drop-down list of options.
import javax.swing.*;
frame.add(label);
frame.add(button);
frame.setVisible(true);
}
}
This code creates a simple JFrame with a label and a button. The JFrame is the top-level container,
and the JLabel and JButton are added to it.
Swing components are organized in a hierarchical structure, with JComponent as the base class for
most components. This hierarchical structure allows for efficient event handling, layout management, and
customization.
1. Top-Level Containers:
o JFrame: A standalone window with a title bar, menu bar, and borders.
o JDialog: A modal or modeless dialog box.
o JWindow: A lightweight window without a title bar or borders.
2. Containers:
o JPanel: A lightweight container for grouping components.
o JScrollPane: Provides scrollable views of large components.
o JSplitPane: Divides a container into two scrollable panes.
o JTabbedPane: Displays multiple components in tabs.
o JLayeredPane: Manages the layering of components.
o JInternalFrame: A window-like component that can be docked, floated, or maximized
within a container.
3. Basic Components:
o JButton: A clickable button.
o JToggleButton: A button that can be toggled on and off.
o JCheckBox: A check box for selecting or deselecting options.
o JRadioButton: A radio button for selecting one option from a group.
o JLabel: A label for displaying text or images.
o JTextField: A single-line text input field.
o JTextArea: A multi-line text input area.
o JList: A list of items that can be selected.
o JComboBox: A drop-down list of options.
o JProgressBar: A progress bar.
o JSlider: A slider for selecting a value from a range.
o JSpinner: A spinner for selecting a value from a set of values.
o JColorChooser: A dialog for selecting a color.
o JFileChooser: A dialog for selecting files.
o JMenu: A menu item in a menu bar.
o JMenuItem: An individual item in a menu.
o JCheckBoxMenuItem: A checkable menu item.
o JRadioButtonMenuItem: A radio button menu item.
Top-Level Containers:
Top-level containers are the foundation of any Swing application. They provide the main window or
frame where other components are placed. Swing provides three primary top-level containers:
1. JFrame:
o A standalone window with a title bar, menu bar, and borders.
o Commonly used for creating independent applications.
o Can be resized, moved, and closed by the user.
2. JDialog:
o A modal or modeless dialog box.
o Used for displaying messages, asking for user input, or providing additional information.
o Can be modal (blocks interaction with the parent window) or modeless (allows interaction
with the parent window).
3. JWindow:
o A lightweight window without a title bar or borders.
o Often used for simple pop-up windows or custom window decorations.
A JFrame is a top-level container in Swing, representing a standalone window with a title bar, menu bar,
and borders. It's the most commonly used container for creating desktop applications.
Key Features:
Creating a JFrame:
import javax.swing.*;
Key Methods:
Layout Managers:
To organize components within a JFrame, you can use different layout managers:
FlowLayout: Arranges components in a row or column, wrapping to the next line if necessary.
BorderLayout: Divides the container into five regions: North, South, East, West, and Center.
GridLayout: Arranges components in a grid of rows and columns.
CardLayout: Displays one component at a time, like cards in a deck.
GridBagLayout: Provides flexible layout with precise control over component placement.
frame.add(northLabel, BorderLayout.NORTH);
frame.add(eastButton, BorderLayout.EAST);
frame.add(westButton, BorderLayout.WEST);
frame.add(centerArea, BorderLayout.CENTER);
frame.add(southButton, BorderLayout.SOUTH);
frame.setSize(300, 200);
frame.setVisible(true);
JWindow:
A JWindow is a lightweight top-level container in Swing that doesn't have a title bar, menu bar, or
borders. It's often used for simple pop-up windows, tooltips, or custom window decorations.
Key Features:
Example:
import javax.swing.*;
import java.awt.*;
window.setVisible(true);
}
}
JWindow is often used in conjunction with JFrame or JDialog to create more complex user
interfaces.
You can customize the appearance of a JWindow using the setShape() method to create non-
rectangular windows.
Be mindful of the platform-specific limitations and restrictions when using JWindow.
A JDialog is a top-level container in Swing that represents a dialog box. It is often used for displaying
messages, asking for user input, or providing additional information.
Key Features:
Modal or Modeless:
o Modal dialogs: Block interaction with the parent window until they are closed.
o Modeless dialogs: Allow interaction with the parent window while they are open.
Title Bar: Displays a title.
Close Button: Can be closed by the user.
Customizable: Can be customized with various components and layouts.
Example:
import javax.swing.*;
import java.awt.*;
In this example, a modal dialog is created and displayed. The true argument in the JDialog constructor
makes the dialog modal, preventing interaction with the main frame until the dialog is closed.
Key Points:
A JPanel is a lightweight container in Swing that is used to group components together. It's a versatile
component that can be used to organize and structure your user interface.
Key Features:
Example:
Java
import javax.swing.*;
import java.awt.*;
panel.setLayout(new FlowLayout());
frame.add(panel);
frame.setVisible(true);
}
}
A JButton is a fundamental Swing component that triggers an action when clicked. It's widely used in user
interfaces to initiate various tasks, such as submitting forms, opening dialogs, or performing calculations.
Key Features:
Example:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
JButton
button = new JButton("Click Me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent
e) {
System.out.println("Button clicked!");
}
});
frame.add(button);
frame.setVisible(true);
}
}
JToggleButton:
A JToggleButton is a type of button that can be toggled between two states: selected and
deselected. It's often used to represent on/off switches, checkboxes, or radio buttons.
Key Features:
A JCheckBox is a Swing component that allows users to select or deselect an option. It's
commonly used to create checkboxes in forms and dialogs.
Key Features:
A JRadioButton is a Swing component that allows users to select one option from a group of
related options. It's often used in forms and dialogs to present mutually exclusive choices.
Key Features:
Grouped Selection: Radio buttons are typically grouped together using a ButtonGroup to ensure
that only one button can be selected at a time.
Customizable Text and Icons: You can set a label and icon for each radio button.
Event Handling: You can handle selection events using an ItemListener.
Example:
import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
group.add(radioButton1);
group.add(radioButton2);
group.add(radioButton3);
frame.add(radioButton1);
frame.add(radioButton2);
frame.add(radioButton3);
frame.setVisible(true);
}
}
JLabel
A JLabel is a simple component used to display text or images. It's often used to provide labels for other
components, such as text fields or buttons.
Example:
JTextField
A JTextField is a single-line text input field. It allows users to enter text, which can then be retrieved and
processed by the application.
Example:
JTextField textField = new JTextField(20); // Creates a text field with a width of 20 characters
JTextArea
A JTextArea is a multi-line text input area. It's useful for displaying large amounts of text or allowing
users to input multiple lines of text.
Example:
JTextArea textArea = new JTextArea(5, 20); // Creates a text area with 5 rows and 20 columns
JList
A JList displays a list of items from which the user can select one or multiple items.
Example:
JComboBox
A JComboBox is a drop-down list that allows the user to select one item from a list of options.
Example:
JScrollPane
A JScrollPane provides scrollable views of large components. It's often used with JTextArea, JList, and
other components that may exceed the visible area.
Example:
1-Mark:
1. What is Swing?
a) Component
b) Container
c) JComponent
d) JFrame
a) JPanel
b) JButton
c) JFrame
d) JLabel
a) To display text.
d) To display images.
a) JTextField
b) JTextArea
c) JLabel
d) JButton
6. Which component is used to display a list of items from which the user can select one or
more?
a) JComboBox
b) JList
c) JButton
d) JLabel
a) JTextArea
b) JTextField
c) JLabel
d) JButton
a) JScrollPane
b) JScrollBar
c) JViewport
d) JLayeredPane
a) JTextField
b) JTextArea
c) JLabel
d) JButton
10. Which component is used to display multiple lines of text, both editable and non-editable?
a) JTextField
b) JTextArea
c) JLabel
d) JButton
a) JTextField
b) JTextArea
c) JLabel
d) JButton
12. Which component is used to display a list of items from which the user can select one or
more?
a) JComboBox
b) JList
c) JButton
d) JLabel
13. Which component is used to display a drop-down list of items from which the user can select
one?
a) JComboBox
b) JList
c) JButton
d) JLabel
a) JScrollPane
b) JScrollBar
c) JViewport
d) JLayeredPane
a) JPanel
b) JButton
c) JFrame
d) JLabel
a) JFrame
b) JDialog
c) JPanel
d) JWindow
a) JWindow
b) JDialog
c) JFrame
d) JPanel
a) JButton
b) JToggleButton
c) JCheckBox
d) JRadioButton
a) JButton
b) JToggleButton
c) JCheckBox
d) JRadioButton
20. Which component is used to select multiple options from a group of options?
a) JButton
b) JToggleButton
c) JCheckBox
d) JRadioButton