0% found this document useful (0 votes)
5 views

java notes2

The document provides an overview of fundamental Java concepts including tokens, variable scope, typecasting, constructors, methods, and inheritance. It explains various Java constructs such as arrays, strings, vectors, and wrapper classes, along with their key features and functionalities. Additionally, it discusses access modifiers, garbage collection, and the types of inheritance in Java programming.

Uploaded by

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

java notes2

The document provides an overview of fundamental Java concepts including tokens, variable scope, typecasting, constructors, methods, and inheritance. It explains various Java constructs such as arrays, strings, vectors, and wrapper classes, along with their key features and functionalities. Additionally, it discusses access modifiers, garbage collection, and the types of inheritance in Java programming.

Uploaded by

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

1.Java tokens :- In Java, Tokens are the smallest elements of a program that is meaningful to the .

. Narrow Type Casting:- The process of downsizing a bigger data type into a smaller one is known as
compiler. They are also known as the fundamental building blocks of the program. Tokens can be narrowing type casting. Casting up or explicit type casting are other names for it. It doesn’t just happen
classified as follows: by itself. If we don’t explicitly do that, a compile-time error will occur. Narrowing type casting is unsafe
because data loss might happen due to the lower data type’s smaller range of permitted values.
Keywords:- Keywords are pre-defined or reserved words in a programming language. Each keyword is
meant to perform a specific function in a program

Identifiers :- Identifiers are used as the general terminology for naming of variables, functions and arrays 4 Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of
the same type in a single variable. They are useful for storing and managing collections of data. Arrays in
Constants :- Constants are also like normal variables. But the only difference is, their values cannot be
Java are objects, which makes them work differently from arrays in C/C++ in terms of memory
modified by the program once they are defined
management. For primitive arrays, elements are stored in a contiguous memory location, For non-
Operators:- Java provides many types of operators which can be used according to the need. They are primitive arrays, references are stored at contiguous locations, but the actual objects may be at different
classified based on the functionality they provide. locations in memory.

Separators:- Separators are used to separate different parts of the codes. It tells the compiler about Key features of Arrays:
completion of a statement in the program. The most commonly and frequently used separator in java is
. Contiguous Memory Allocation (for Primitives): Java array elements are stored in continuous memory
semicolon (;)
locations, which means that the elements are placed next to each other in memory.

. Zero-based Indexing: The first element of the array is at index 0.


2. scope of variable:- The scope of a variable in Java defines the region within the code where the
. Fixed Length: Once an array is created, its size is fixed and cannot be changed.
variable can be accessed. There are three main types of variable scope in Java
. Can Store Primitives & Objects: Java arrays can hold both primitive types (like int, char, boolean, etc.)
Local Scope: Variables declared inside a method, constructor, or block (code enclosed in curly braces {})
and objects (like String, Integer, etc.)
have local scope. They are only accessible within that specific block of code. Once the block's execution
is complete, the variable is destroyed.

Instance Scope: Variables declared within a class but outside any method, constructor, or block are 5. strings :- In Java, a String is the type of object that can store a sequence of characters enclosed by
instance variables. Each object has its own copy of instance variables. double quotes, and every character is stored in 16 bits, i.e., using UTF 16-bit encoding. A string acts the
same as an array of characters. Java provides a robust and flexible API for handling strings, allowing for
Class (Static) Scope: Variables declared with the static keyword within a class but outside any method,
various operations such as concatenation, comparison, and manipulation.
constructor, or block are class variables (static variables
string buffer classes:- The StringBuffer class in Java represents a sequence of characters that can be
modified, which means we can change the content of the StringBuffer without creating a new object
3. typecasting:- Typecasting in Java is the process of converting one data type to another data type using every time. It represents a mutable sequence of characters.
the casting operator. When you assign a value from one primitive data type to another type, this is
known as type casting. To enable the use of a variable in a specific manner, this method requires
explicitly instructing the Java compiler to treat a variable of one data type as a variable of another data 6. vectors :- The Vector class in Java implements a growable array of objects. Vectors were legacy classes,
type. but now it is fully compatible with collections. It comes under java.util package and implement the List
interface.
Syntax:- <datatype> variableName = (<datatype>) value;
Key Features of Vector:
There are two types of Type Casting in java:
. It expands as elements are added.
. Widening Type Casting:- A lower data type is transformed into a higher one by a process known as
widening type casting. Implicit type casting and casting down are some names for it. It occurs naturally. . Vector class is synchronized in nature means it is thread-safe by default.
Since there is no chance of data loss, it is secure. Widening Type casting occurs when:
. Like an ArrayList, it maintains insertion order.

. It allows duplicates and nulls.


. It implements List, RandomAccess, Cloneable, and Serializable. 1. Default Constructor:- A constructor that has no parameters is known as default constructor. A
default constructor is invisible. And if we write a constructor with no arguments, the compiler
does not create a default constructor. Once you define a constructor (with or without
7. wrapper classes:- A Wrapper class in Java is one whose object wraps or contains primitive data types. parameters), the compiler no longer provides the default constructor. The default constructor
When we create an object in a wrapper class, it contains a field, and in this field, we can store primitive can be implicit or explicit.
data types. In other words, we can wrap a primitive value into a wrapper class object.
e.g

import java.io.*;
8. Constructors:- In Java, constructors play an important role in object creation. A constructor is a special
class Geeks{
block of code that is called when an object is created. Its main job is to initialize the object, to set up its
internal state, or to assign default values to its attributes. This process happens automatically when we Geeks() {
use the “new” keyword to create an object.
System.out.println("Default constructor");
Characteristics of Constructors:
}
. Same Name as the Class: A constructor has the same name as the class in which it is defined.
public static void main(String[] args)
. No Return Type: Constructors do not have any return type, not even void. The main purpose of a
{
constructor is to initialize the object, not to return a value.
Geeks hello = new Geeks();
. Automatically Called on Object Creation: When an object of a class is created, the constructor is called
automatically to initialize the object’s attributes. }
E.g }
import java.io.*;

class Geeks {

Geeks() 2. Parameterized Constructor:- A constructor that has parameters is known as parameterized


constructor. If we want to initialize fields of the class with our own values, then use a
{
parameterized constructor.
super();
e.g
System.out.println("Constructor Called");
import java.io.*;
}
class Geeks {
public static void main(String[] args)
String name;
{
int id;
Geeks geek = new Geeks();
Geeks(String name, int id) {
}
this.name = name;
}
this.id = id;

}
TYPES OF CONSTRUCTOR:-
}
class GFG . Compile-time polymorphism in Java: Constructor overloading is an example of compile-time
polymorphism. The appropriate constructor is selected depending on the arguments provided during
{
object instantiation.
public static void main(String[] args)
. Improved code readability and reusability: By providing different constructors, developers can offer
{ multiple ways of initializing an object, making the code easier to read and more reusable.

Geeks geek1 = new Geeks("Sweta", 68); e.g

System.out.println("GeekName: " + geek1.name class Car {

+ " and GeekId: " + geek1.id); String model;

} int year;

} Car() {

model = "Unknown";

3. Copy Constructor:- Unlike other constructors copy constructor is passed with another object year = 0;
which copies the data available from the passed object to the newly created object.
}
e.g
Car(String model, int year) {

this.model = model;
4.Java Methods:- Java Methods are blocks of code that perform a specific task. A method allows us to
this.year = year;
reuse code, improving both efficiency and organization. All methods in Java must belong to a class.
Methods are similar to functions and expose the behavior of object. }

Types of Methods in Java void display() {

1. Predefined Method System.out.println("Model: " + model + ", Year: " + year);


2. User-defined Method
}

public static void main(String[] args) {


5. Java method overloading allows a class to have multiple methods with the same name, but with
Car car1 = new Car();
different parameter lists. It enables performing similar tasks with different input types or numbers of
parameters. This is a form of compile-time polymorphism, as the compiler determines which method to Car car2 = new Car("Toyota", 2022);
call based on the method signature.
car1.display();
constructor overloading:- Constructor overloading in Java allows a class to have multiple constructors
with different parameter lists. This provides flexibility in object creation, enabling the initialization of car2.display();
objects in various ways depending on the available data. The compiler differentiates constructors based }
on the number, type, or order of parameters.
}
. Same constructor name but different parameter combinations: All overloaded constructors must have
the same name (the name of the class), but their parameters (number, type, or both) must differ. This
allows Java to differentiate between constructor 6. nesting of methods:- Nesting of methods in Java refers to the practice of calling one method from
within another method in the same class. It allows for code reusability and modularity by breaking down
complex tasks into smaller, manageable functions. When a method is called within another, the program class A {
execution flow transfers to the called method, and after its completion, it returns to the point where it
private void display() {
was initially called.
System.out.println("GeeksforGeeks");

}
7.garbage collection:- Garbage collection in Java is an automatic memory management process that
helps Java programs run efficiently. Java programs compile to bytecode that can be run on a Java Virtual }
Machine (JVM). When Java programs run on the JVM, objects in the heap are created, which is a portion
of memory dedicated to the program. Eventually, some objects will no longer be needed. The garbage Protected – The protected access modifier is specified using the keyword protected. The methods or
collector finds these unused objects and deletes them to free up memory. data members declared as protected are accessible within the same package or subclasses in different
packages.
Two types of garbage collection activities usually happen in Java. These are:
public class A {
. Minor or incremental Garbage Collection (GC): This occurs when unreachable objects in the Young
Generation heap memory are removed. protected void display() {

. Major or Full Garbage Collection (GC): This happens when objects that survived minor garbage System.out.println("GeeksforGeeks");
collection are removed from the Old Generation heap memory. It occurs less frequently than minor }
garbage collection.
}

Public – The public access modifier is specified using the keyword public.
8. visibility control: public, private, protected, default, private protected :- In Java, access modifiers are
essential tools that define how the members of a class, like variables, methods, and even the class itself The public access modifier has the widest scope among all other access modifiers.
can be accessed from other parts of our program. They are an important part of building secure and Classes, methods, or data members that are declared as public are accessible from everywhere in the
modular code when designing large applications. Understanding default, private, protected, and public program. There is no restriction on the scope of public data members.
access modifiers is essential for writing efficient and structured Java programs
package p1;
There are 4 types of access modifiers available in Java:
public class A {
Default – When no access modifier is specified for a class, method, or data member, it is said to have the
default access modifier by default. This means only classes within the same package can access it. public void display() {

e.g class Geek System.out.println("GeeksforGeeks");

{ }

void display() }

System.out.println("Hello World!"); 9. Inheritance: concept of inheritance , types of Inheritance: single inheritance, multilevel inheritance,
hierarchical inheritance:– It is the mechanism in Java by which one class is allowed to inherit the
} features(fields and methods) of another class. In Java, Inheritance means creating new classes based on
} existing ones. A class that inherits from another class can reuse the methods and fields of that class. In
addition, you can add new fields and methods to your current class as well

Inheritance promotes code reusability, method overriding, and polymorphism, which makes the Java
Private – The private access modifier is specified using the keyword private. The methods or data program more modular and efficient.
members declared as private are accessible only within the class in which they are declared.
1. Single Inheritance – In single inheritance, a sub-class is derived from only one super class. It class One {
inherits the properties and behavior of a single-parent class. Sometimes, it is also known as
2.Multilevel Inheritance:–– In Multilevel public void print_geek() {
simple inheritance
Inheritance, a derived class will be inheriting a
base class, and as well as the derived class also System.out.println("Geeks");
class One {
acts as the base class for other classes. In the }
public void print_geek() below image, class A serves as a base class for
the derived class B, which in turn serves as a }
{
base class for the derived class C. In Java, a class
class Two extends One {
System.out.println("Geeks"); cannot directly access the grandparent’s
members if they are private. public void print_for() {
}
System.out.println("for");
}
}
class Two extends One {
}
public void print_for() { System.out.println("for"); }
class Three extends Two {
}
public void print_lastgeek() {
public class Main {
System.out.println("Geeks");
public static void main(String[] args)
}
{
}
Two g = new Two();
public class Main {
g.print_geek();
public static void main(String[] args) {
g.print_for();
Geeks Three
g.print_geek();
for Three g = new Three();
}
Geeks g.print_geek();
}
g.print_for();

Three Geeks
g.print_lastgeek(); for
} Geeks
}
3.Hierarchical Inheritance :–– In Hierarchical class A { 4.Multiple Inheritance:–– In
Inheritance, one class serves as a superclass Multiple inheritances, one class interface Coder {
(base class) for more than one subclass. In the public void print_A() { System.out.println("Class A"); } can have more than one
below image, class A serves as a base class for superclass and inherit features void writeCode();
}
the derived classes B, C, and D. from all parent classes. Please }
class B extends A { note that Java does not support
multiple inheritances with interface Tester { void testCode();
public void print_B() { System.out.println("Class B"); }
classes. In Java, we can achieve
}
} multiple inheritances only
through Interfaces. In the image class DevOpsEngineer implements Coder, Tester {
class C extends A {
below, Class C is derived from
@Override
public void print_C() { System.out.println("Class C"); } interfaces A and B.
public void writeCode() {
}
System.out.println("DevOps Engineer writes automation scripts.");
class D extends A {
}
public void print_D() { System.out.println("Class D"); }
@Override
}
public void testCode() {
public class Test {
System.out.println("DevOps Engineer tests deployment pipelines.");
public static void main(String[] args)
}
{
DevOpsEngineer
B obj_B = new B();
public void deploy() {
obj_B.print_A();
System.out.println("DevOps Engineer deploys code to cloud.");
obj_B.print_B();
}
C obj_C = new C();
}
obj_C.print_A();
public class Main {
obj_C.print_C(); Class A
public static void main(String[] args) {
Class B
DevOpsEngineer devOps = new DevOpsEngineer();
D obj_D = new D(); Class A

obj_D.print_A(); Class C
devOps.writeCode();
obj_D.print_D(); Class A
devOps.testCode();
} Class D
devOps.deploy();
}
}

}
4.Hybrid Inheritance:–– It is a mix of two or more of the above types of inheritance. Since Java doesn’t 10.method overriding:–– Overriding in Java occurs when class Animal {
support multiple inheritances with classes, hybrid inheritance involving multiple inheritance is also not a subclass or child class implements a method that is
possible with classes. In Java, we can achieve hybrid inheritance only through Interfaces if we want to already defined in the superclass or base class. When a void move() { System.out.println(
involve multiple inheritance to implement Hybrid inheritance. subclass provides its own version of a method that is "Animal is moving."); }
already defined in its superclass, we call it method
class SolarSystem { overriding. The subclass method must match the parent void eat() { System.out.println(
class method’s name, parameters, and return type.
} "Animal is eating."); }
Rules for Overriding:
class Earth extends SolarSystem { }
. Name, parameters, and return type must match the
} class Dog extends Animal {
parent method.
class Mars extends SolarSystem { @Override void move()
. Java picks which method to run, based on the actual
} object type, not just the variable type. {
public class Moon extends Earth { . Static methods cannot be overridden. System.out.println("Dog is running.");
public static void main(String args[]) . The @Override annotation catches mistakes like typos }
in method names.
{ void bark() { System.out.println("Dog is barking."); }
SolarSystem s = new SolarSystem(); }
Earth e = new Earth(); public class Geeks {
11. final Keyword in Java:–– The final Keyword in Java is
Mars m = new Mars(); public static void main(String[] args)
used as a non-access modifier applicable to a variable, a
System.out.println(s instanceof SolarSystem); method, or a class. It is used to restrict a user in Java. We {
cannot use the final keyword in a block. It restricts the
System.out.println(e instanceof Earth); user from accessing that particular part of the program, Dog d = new Dog();
System.out.println(m instanceof SolarSystem); such as restricting the modification and inheriting the d.move(); // Output: Dog is running.
properties from the parent class or overloading.
} d.eat(); // Output: Animal is eating.
} d.bark(); // Output: Dog is barking.

}
12. Super Keyword in Java:–– The super keyword in Java is a reference variable that is used to refer to 15.Package: Define package, types of package, naming and creating package, accessing package:––
the parent class when we are working with objects. You need to know the basics of Inheritance and
In Java, a package serves as a namespace that organizes related classes and interfaces. It provides a way
Polymorphism to understand the Java super keyword.
to group related classes, interfaces, and sub-packages, similar to folders in a file system. Packages help to
13. What is Abstract Class in Java:–– Java abstract class is a class that can not be instantiated by itself, it prevent naming conflicts, control access to classes, and organize code.
needs to be subclassed by another class to use its properties. An abstract class is declared using the
Types of Packages
“abstract” keyword in its class definition.
a) Built-in Packages (Predefined Packages):- These packages consist of a large number of classes
abstract class Shape
which are a part of Java API. Java comes with many built-in packages. Some commonly used
{ ones include:

int color; java.lang Contains fundamental classes (String, Math)


// An abstract function java.util Contains utility classes (collections, Date)
java.io For input and output operations
abstract void draw();
java.net For networking
}
java.sql For database access using JDBC

14. Define interface, implementing interface, accessing interface variables and methods, extending
interfaces:––

In Java, an interface is a blueprint of a class, specifying a set of abstract methods that a class must b)User-defined Packages:- These are the packages that are defined
implement. It defines a contract for classes to adhere to, ensuring they provide specific functionalities. by the user.user can define their own packages. Creating a package

Implementing Interface package mypackage; // declares the package

A class implements an interface using the implements keyword, providing concrete implementations for 16.import Statement in Java:- The import statement allows you to public class MyClass {
all the abstract methods declared in the interface. If a class does not implement all methods, it must be use classes and interfaces from other packages without needing to
public void display() {
declared abstract. use their fully qualified names.
interface Drawable {
System.out.println("Hello from MyClass in
Accessing Interface Variables and Methods import package_name.ClassName;
void draw(); mypackage!");
Variables: import package_name.*;
} }
Interface variables are implicitly public, static, and final (constants). They are class Circle implements Drawable { static import in Java:- The static import feature allows you to
}
accessed using the interface name. import static members (fields and methods) of a class so you can
@Override
use them without class qualification.
Methods: public void draw() {

Interface methods are implicitly public and abstract (prior to Java 8). They are System.out.println("Drawing circle");
accessed through objects of the class that implements the interface. }

Extending Interfaces: }

An interface can extend another interface using the extends keyword,


inheriting its methods. This allows for creating hierarchies of interfaces. A class implementing the
extended interface must implement all methods from the parent and child interfaces.
17.What is error:- an error is an unplanned or unwanted program behavior that leads to the failure of  They occur due to logical errors or programming mistakes, like using a null reference or dividing
the program or generates erroneous results. Error is an illegal operation performed by the user which by zero.
results in the abnormal working of the program. Programming errors often remain undetected until the
 They are subclasses of RuntimeException.
program is compiled or executed. Some of the errors inhibit the program from getting compiled or
executed. Thus errors should be removed before compiling and executing

Types of Errors:- 19. try and catch statement:-


Run Time Error:- The try and catch statement in Java is used to handle exceptions and ensure that the program continues
running even when an error occurs. Instead of crashing, Java lets you catch and deal with the error in a
Run Time errors occur or we can say, are detected during the execution of the program. Sometimes
structured way.
these are discovered when the user enters an invalid data or data which is not relevant. Runtime errors
occur when a program does not contain any syntax errors but asks the computer to do something that try {
the computer is unable to reliably do. During compilation, the compiler has no technique to detect these
kinds of errors. It is the JVM (Java Virtual Machine) that detects it while the program is running. // Code that may throw an exception

Compile Time Error:- } catch (ExceptionType name) {

Compile Time Errors are those errors which prevent the code from running because of an incorrect // Code to handle the exception
syntax such as a missing semicolon at the end of a statement or a missing bracket, class not found, etc. }
These errors are detected by the java compiler and an error message is displayed on the screen while
compiling. Compile Time Errors are sometimes also referred to as Syntax errors. 20. throws and finally statement:-

1. throws Keyword in Java

18.what is exception:- An exception in Java is an event that occurs during the execution of a program The throws keyword is used in a method declaration to indicate that the method might throw one or
that disrupts the normal flow of instructions. It typically occurs due to runtime errors such as dividing by more exceptions. This informs the caller that it must handle (or further declare) the exception.
zero, accessing an invalid index in an array, or trying to open a file that doesn’t exist. When such events returnType methodName() throws ExceptionType1, ExceptionType2 {
happen, Java creates an object of the exception class and throws it, which can then be caught and
handled by the program. // code that may throw exception

Exception handling in Java is an effective mechanism for managing runtime errors to ensure the }
application’s regular flow is maintained. Some Common examples of exceptions include
2. finally Block in Java
ClassNotFoundException, IOException, SQLException, RemoteException, etc. By handling these
exceptions, Java enables developers to create robust and fault-tolerant applications. The finally block is used to execute important code such as resource cleanup, regardless of whether an
exception was thrown or caught. It always executes after the try and catch blocks.
Types of Exceptions
try {
Checked Exceptions
// code that may throw an exception
 These are checked at compile-time.
} catch (Exception e) {
 The compiler forces the programmer to handle them using try-catch or by declaring them with
throws. // code to handle the exception

 These typically occur due to external factors like file I/O, database access, etc. } finally {

Unchecked Exceptions (Runtime Exceptions) // code that will always execute

 These are not checked at compile-time. }


21. built-in exceptions, throwing our own exception:-

1. Built-in Exceptions in Java

Built-in exceptions are part of Java’s standard library and cover most common programming and runtime
errors. These exceptions are defined in the java.lang.

Types of Built-in Exceptions:-

Checked Exceptions:- These are checked at compile time, and the programmer is forced to handle them.

Unchecked Exceptions (Runtime Exceptions):- These are not checked at compile time, and occur due to
programming errors.

2.Throwing Our Own (Custom) Exception in Java


Thread priority determines the importance of a thread. Java allows you to set the priority of a thread,
Sometimes, the built-in exceptions are not enough to express business logic violations or application-
which may affect the order in which threads are executed. However, thread priority does not guarantee
specific errors. In such cases, Java allows us to define and throw our own exceptions by extending the
the order of execution.
Exception class or its subclasses.
Synchronization in Java

In a multithreaded environment, multiple threads may access and modify shared data simultaneously,
22. Multithreaded Programming in Java:-
leading to race conditions. To avoid this, synchronization is used to ensure that only one thread can
Multithreading is the ability of a CPU to execute multiple tasks (threads) concurrently. In Java, access the critical section of code at a time.
multithreading allows a program to perform multiple operations at once, such as handling user input
Synchronized Methods: You can use the synchronized keyword to prevent multiple threads from
while processing data in the background.
accessing a method at the same time.
java provides two main ways to create threads: by extending the Thread class and by implementing the
Runnable interface. Let's break down the concepts into simpler steps.
23. Component: The superclass for all AWT components (e.g., Button, Label).
Life Cycle of a Thread
Container: A subclass of Component that can hold other components (e.g., Panel, Frame).
A thread in Java goes through several states during its life cycle:
Window: A top-level window with no borders or menu bar.
1. New: A thread is in this state when it is created but not yet started.
Frame: A top-level window with borders, title, and buttons (minimize, maximize, close).
2. Runnable: When the start() method is called, the thread enters the runnable state, ready for
execution. Panel: A generic container for organizing components, often used inside Frames.

3. Blocked: The thread is blocked when it is waiting to acquire a lock on a resource.

4. Waiting: A thread enters the waiting state when it is waiting indefinitely for another thread to AWT Controls:-
perform a specific action.
Label
5. Timed Waiting: When a thread is waiting for a specified period (using methods like sleep()).
Used to display a single line of read-only text.
6. Terminated: A thread reaches this state when it has completed its execution.
Button

Creates a button that can be clicked to trigger an action.

Checkbox

Creates a checkbox that can be selected or deselected.


CheckboxGroup Java, making them lightweight and more portable. Swing supports pluggable look-and-feel, which
means the appearance of components can be changed at runtime to mimic different operating systems.
Used to create radio buttons where only one can be selected at a time.
It also provides advanced features such as double buffering, MVC architecture, and a richer event
TextField handling mechanism. All Swing components start with the letter "J" (e.g., JFrame, JButton, JPanel), and
are placed in the javax.swing package. Swing is a preferred choice for Java GUI development due to its
A single-line text input field. flexibility, extensibility, and consistent behavior across platforms.
TextArea . Swing is a Set of API (API- Set of Classes and Interfaces)
A multi-line text area for input/output. . swing is Provided to Design Graphical User Interfaces

. Swing is an Extension library to the AWT (Abstract Window Toolkit)


Layout Managers:– . Includes New and improved Components that have been enhancing the looks and Functionality of
a. FlowLayout GUIs’

 Default for Panel. . Swing can be used to build (Develop) The Standalone swing GUI Apps as Servlets and Applets

 Places components in a row, wraps to next line if needed. . It Employs model/view design architecture.

b. BorderLayout . Swing is more portable and more flexible than AWT, the Swing is built on top of the AWT.

 Default for Frame. . Swing is Entirely written in Java.

 Divides container into 5 regions: North, South, East, West, Center.

c. GridLayout

 Divides container into a grid of equally sized cells.

d. GridBagLayout

 Most flexible. Allows components to span multiple rows/columns.

MenuBars and Menus:–

a. MenuBar, Menu, MenuItem

Used to create application menus.

b. FileDialog

Provides a platform-independent file chooser dialog.

Introduction to swing:-

Swing is a part of Java's Java Foundation Classes (JFC) and provides a rich set of GUI components for
building platform-independent desktop applications. It is built on top of the older Abstract Window
Toolkit (AWT) but offers more sophisticated components like tables, trees, sliders, tabbed panes, and
more. Unlike AWT, which relies on native system components, Swing components are written entirely in
24.Basic Swing Components

1. Icons and Labels 24.Event Handling:–

 JLabel is used to display a short string or an image icon. An event is a change in the state of an object triggered by some action such as Clicking a button, Moving
the cursor, Pressing a key on the keyboard, Scrolling a page, etc. In Java, the java.awt.event package
2. TextField
provides various event classes to handle these actions.
 JTextField allows single-line text input.
Events in Java can be broadly classified into two categories based on how they are generated:-
3. ComboBox
Foreground Events: Foreground events are the events that require user interaction to generate.
 JComboBox lets users choose from a drop-down list. Examples of these events include Button clicks, Scrolling the scrollbar, Moving the cursor, etc.

4. Button Background Events: Events that don’t require interactions of users to generate are known as background
events. Examples of these events are operating system failures/interrupts, operation completion, etc.
 JButton is a push button used to trigger an action.
Event Handling Mechanism
5. Checkbox
Event handling is a mechanism that allows programs to control events and define what should happen
 JCheckBox allows the user to make multiple selections. when an event occurs. Java uses the Delegation Event Model to handle events. This model consists of
6. RadioButton two main components:

 JRadioButton allows a single selection within a group. Source: Events are generated from the source. There are various sources like buttons, checkboxes, list,
menu-item, choice, scrollbar, text components, windows, etc., to generate events.

Listeners: Listeners are used for handling the events generated from the source. Each of these listeners
represents interfaces that are responsible for handling events.
Advanced Swing Components

1. Tabbed Panes 25.event classes are part of the Event Delegation Model, which allows GUI components to communicate
 JTabbedPane lets you switch between tabs. user actions (like clicks, typing, or selection) to the program. Each type of user interaction is represented
by a specific event class in the java.awt.event package
2. Scroll Panes
1. ActionEvent Class
 JScrollPane adds scrollbars to components like text areas, panels, or tables.
 Triggered by: Buttons, menu items, and other components like JButton, JMenuItem.
3. Trees
 Listener interface: ActionListener
 JTree displays a hierarchical tree structure.
 public void actionPerformed(ActionEvent e)
4. Tables
2. ItemEvent Class
 JTable is used for displaying tabular data.
 Triggered by: Checkbox, radio buttons, combo boxes when an item is selected or deselected.
5. Progress Bar
 Listener interface: ItemListener
 JProgressBar visually shows the progress of a task.
 public void itemStateChanged(ItemEvent e)
6. Tool Tips
3. KeyEvent Class
 Tool tips provide helpful text when the user hovers over a component.
 Triggered by: Keyboard actions like typing or pressing keys.
 Listener interface: KeyListener 3. KeyListener

 public void keyPressed(KeyEvent e)  Used for: Capturing keyboard input.

public void keyReleased(KeyEvent e)  Event Class: KeyEvent

public void keyTyped(KeyEvent e)  void keyPressed(KeyEvent e);

4. MouseEvent Class void keyReleased(KeyEvent e);

 Triggered by: Mouse actions (click, press, release, move, drag). void keyTyped(KeyEvent e);

 Listener interfaces: MouseListener, MouseMotionListener 4. MouseListener

 public void mouseClicked(MouseEvent e)  Used for: Mouse actions like clicking, entering, or exiting a component.

public void mousePressed(MouseEvent e)  Event Class: MouseEvent

public void mouseReleased(MouseEvent e)  void mouseClicked(MouseEvent e);

public void mouseEntered(MouseEvent e) void mousePressed(MouseEvent e);

public void mouseExited(MouseEvent e) void mouseReleased(MouseEvent e);

5. TextEvent Class void mouseEntered(MouseEvent e);

 Triggered by: Text components like TextField, TextArea when text changes. void mouseExited(MouseEvent e);

 Listener interface: TextListener 5. MouseMotionListener

 public void textValueChanged(TextEvent e)  Used for: Detecting mouse movement and dragging.

 Event Class: MouseEvent

26.event listener interfaces are used to handle different types of user interactions in GUI applications.  void mouseMoved(MouseEvent e);
These interfaces belong to the java.awt.event package and are implemented to listen for specific events
void mouseDragged(MouseEvent e);
like button clicks, key presses, mouse movements, etc.
6. TextListener
1. ActionListener
 Used for: Detecting changes in text components like TextField or TextArea.
 Used for: Handling actions like button clicks, menu item selections, etc.
 Event Class: TextEvent
 Event Class: ActionEvent
 void textValueChanged(TextEvent e);
 void actionPerformed(ActionEvent e);

2. ItemListener

 Used for: Item state changes in components like checkboxes, radio buttons, or combo boxes.

 Event Class: ItemEvent

 void itemStateChanged(ItemEvent e);

You might also like