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

Java semester 2 full notes

The document provides an introduction to Java, covering key concepts of Object-Oriented Programming (OOP) and features of Java such as platform independence, security, and garbage collection. It also compares Java with C++, discusses data types, control statements, and the structure of classes and methods, including constructors and inheritance. Additionally, it introduces the Abstract Window Toolkit (AWT) for GUI development, detailing layout management and event handling mechanisms.

Uploaded by

ckmanish8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Java semester 2 full notes

The document provides an introduction to Java, covering key concepts of Object-Oriented Programming (OOP) and features of Java such as platform independence, security, and garbage collection. It also compares Java with C++, discusses data types, control statements, and the structure of classes and methods, including constructors and inheritance. Additionally, it introduces the Abstract Window Toolkit (AWT) for GUI development, detailing layout management and event handling mechanisms.

Uploaded by

ckmanish8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

IntroductIon to java

Object-Oriented Programming (OOP)


Object-Oriented Programming (OOP) is a programming
paradigm based on the concept of "objects," which can
contain data (attributes) and code (methods). OOP focuses on
reusability, modularity, and organization. Its key concepts are:
• Class: A blueprint for objects, defining their attributes
and behaviors.
• Object: An instance of a class, representing real-world
entities.
• Encapsulation: Bundling of data and methods that
operate on the data into a single unit (class).
• Inheritance: Mechanism by which one class can inherit
fields and methods from another class, promoting code
reuse.
• Polymorphism: Ability of objects to take multiple forms,
usually through method overloading and overriding.
• Abstraction: Hiding implementation details and showing
only essential features.
Features of Java
Java is a high-level, object-oriented programming language
developed by Sun Microsystems (now owned by Oracle). It
has several features that make it powerful and widely used:
• Platform Independent: Java code is compiled into
bytecode, which runs on the Java Virtual Machine (JVM),
making it platform-independent.
• Object-Oriented: Java is purely object-oriented, meaning
everything in Java revolves around objects and classes.
• Simple: Java’s syntax is straightforward, making it easy to
learn and use.
• Secure: Java provides a secure environment with
bytecode verification, a security manager, and access
control features.
• Multithreaded: Java supports concurrent programming
with multithreading, allowing the execution of multiple
threads simultaneously.
• Robust: Java emphasizes strong memory management
and automatic garbage collection, reducing memory
leaks and crashes.
• Portable: Java programs can run on any system with a
JVM, making them portable across platforms.
• High Performance: Java’s performance is optimized
through Just-In-Time (JIT) compilers, making it relatively
fast for most applications.
How Java is Different from C++
Java and C++ are both object-oriented programming
languages, but they have several differences:
Feature Java C++
Manual memory
Memory Automatic garbage
management using
Management collection.
new and delete.
Does not support Supports multiple
Multiple
multiple inheritance inheritance using
Inheritance
directly. classes.
Feature Java C++
Platform- Platform-dependent
Platform
independent due to (compiled to native
Independence
the JVM. code).
Does not support Supports pointers
Pointers
pointers explicitly. explicitly.
Operator Not supported in
Supported in C++.
Overloading Java.
Compiled into
Compiled into
Compilation bytecode, which
machine code.
runs on the JVM.
Does not support Supports global
Global Variables
global variables. variables.
Data Types in Java
Java provides various data types, categorized into two types:
primitive and non-primitive.
• Primitive Data Types:
o byte: 8-bit integer.
o short: 16-bit integer.
o int: 32-bit integer.
o long: 64-bit integer.
o float: 32-bit floating-point number.
o double: 64-bit floating-point number.
o char: 16-bit Unicode character.
o boolean: Can store true or false.
• Non-Primitive Data Types:
o Classes, interfaces, arrays, and strings.

Control Statements
Control statements are used to control the flow of execution
in a program. Java provides the following control statements:
• Conditional Statements:
o if: Executes a block of code if a specified condition
is true.
o else: Executes a block of code if the condition is
false.
o else if: Used for multiple conditions.
o switch: Selects one of many code blocks to be
executed based on a variable's value.
• Looping Statements:
o for: Executes a block of code a certain number of
times.
o while: Executes a block of code as long as the
condition is true.
o do-while: Similar to while, but guarantees at least
one execution of the loop.
• Control Flow Statements:
o break: Terminates the loop or switch statement.
o continue: Skips the current iteration of the loop.
o return: Exits a method and optionally returns a
value.
Identifiers
In Java, identifiers are names used for classes, variables,
methods, and other elements in the program. Identifiers
must follow these rules:
• They must start with a letter, underscore (_), or dollar
sign ($).
• They can contain digits after the first character.
• They are case-sensitive (MyVar and myVar are different).
• Reserved keywords like int, class, and static cannot be
used as identifiers.
Arrays
An array in Java is a collection of variables of the same type
stored in contiguous memory locations. Arrays in Java are
objects and have the following characteristics:
• Arrays are zero-indexed.
• The size of the array is fixed and cannot be changed
once initialized.
• Arrays can be single-dimensional or multi-dimensional
(e.g., two-dimensional arrays).

Operators
Java provides various operators to perform operations on
variables and values. These are categorized into:
• Arithmetic Operators: +, -, *, /, % (modulus).
• Relational Operators: ==, !=, <, >, <=, >=.
• Logical Operators: &&, ||, !.
• Bitwise Operators: &, |, ^, ~, <<, >>, >>>.
• Assignment Operators: =, +=, -=, *=, /=, %=.
• Ternary Operator: ? : (Used as a shorthand for if-else).

Variables
A variable is a container for storing data values. In Java,
variables must be declared with a data type before use. The
three types of variables in Java are:
• Local Variables: Declared within a method and
accessible only within that method.
• Instance Variables: Declared inside a class but outside
any method and are specific to an instance of a class.
• Static Variables: Declared with the static keyword and
shared among all instances of a class.
Applications and Applets
Java supports two types of programs: applications and
applets.
• Java Applications: These are standalone programs that
run on the Java Virtual Machine. They can be console-
based or GUI-based using libraries like AWT and Swing.
• Java Applets: Applets are small Java programs that can
run inside a web browser. They require a browser with a
Java plugin or an applet viewer. Applets are now largely
obsolete due to security concerns and the rise of other
technologies like JavaScript.
Java Programming

Java is a powerful, high-level programming language that


follows the principles of object-oriented programming (OOP).
It is designed to be platform-independent and emphasizes
code reusability and modularity. In this overview, we will
explore several core concepts of Java programming that are
essential for students in a Bachelor of Computer Applications
(BCA) program, including classes and methods, constructors,
inheritance, method overloading, garbage collection, and
string manipulation.
1. Classes and Methods
Classes
A class in Java serves as a blueprint for creating objects. It
encapsulates data and methods that operate on that data. By
defining a class, you specify the structure and behavior of the
objects that will be instantiated from it.
• Attributes: These are variables defined within a class
that hold the state or properties of an object. For
example, in a Car class, attributes may include color,
model, and speed.
• Methods: Methods are functions defined within a class
that describe the behaviors or actions that an object can
perform. They can manipulate the object's attributes and
perform operations.
Methods
Methods are fundamental to the functionality of classes,
allowing objects to exhibit behaviors. Each method has:
• A name, which identifies it.
• A return type, indicating what type of value the method
will return (if any).
• A parameter list, which defines the inputs the method
can accept.
Methods can be invoked on objects, enabling interaction with
the object's data.

2. Constructors
A constructor is a special type of method used to initialize
objects. When an object is created, the constructor is
automatically called to set up the initial state of the object.
Types of Constructors
1. Default Constructor: A constructor that takes no
parameters. It initializes attributes with default values
(typically zeros, null, or false).
2. Parameterized Constructor: A constructor that takes
parameters, allowing the creation of objects with specific
initial values.
Constructors play a vital role in ensuring that an object starts
its life in a valid state, ready for use.
3. Method Overloading
Method overloading occurs when multiple methods in the
same class share the same name but differ in their parameter
lists (type or number of parameters). This feature allows
developers to define methods that perform similar functions
but with different types or numbers of inputs.
Key Advantages of Method Overloading:
• Enhanced Readability: It makes the code easier to read
and understand since similar operations can be grouped
under a single method name.
• Flexibility: It allows a single method to handle different
data types or argument counts, promoting code
reusability.
4. Inheritance
Inheritance is a cornerstone of object-oriented programming,
allowing a new class (subclass) to inherit properties and
behaviors (methods) from an existing class (superclass). This
mechanism promotes code reusability and establishes a
natural hierarchy between classes.
Types of Inheritance
1. Single Inheritance: A subclass inherits from one
superclass. This is the simplest form of inheritance,
ensuring a clear parent-child relationship.
2. Multilevel Inheritance: A subclass derives from another
subclass, creating a chain of inheritance. For example, a
Vehicle class might have a subclass Car, which in turn has
a subclass ElectricCar.

Method Overriding
Method overriding allows a subclass to provide a specific
implementation of a method already defined in its superclass.
This enables the subclass to customize or extend the behavior
of the inherited method.

Abstract Classes
An abstract class is a class that cannot be instantiated on its
own and may contain abstract methods (methods without a
body). Subclasses must implement these abstract methods,
allowing for a common interface while providing specific
functionality.
Interfaces
An interface is a reference type in Java that defines a contract
for classes. It specifies methods that implementing classes
must define. Interfaces allow for a form of multiple
inheritance, enabling a class to implement multiple
interfaces, which adds flexibility to the design of applications.
5. Final Classes
A final class is a class that cannot be subclassed. Declaring a
class as final ensures that its implementation remains
unchanged, which can be useful for security reasons or to
prevent unintended modifications to a class's behavior.
6. Garbage Collection
Garbage collection is an automatic memory management
process in Java. It identifies and discards objects that are no
longer in use, freeing up resources and preventing memory
leaks. This feature simplifies memory management for
developers, as they do not need to manually deallocate
memory.
Key Points About Garbage Collection:
• Java's garbage collector runs periodically to reclaim
memory.
• Objects that are no longer referenced by any part of the
program are eligible for garbage collection.
• While garbage collection is automatic, developers can
influence its behavior using certain methods and
techniques.
7. String Class
The String class in Java represents a sequence of characters
and is one of the most commonly used classes. Strings in Java
are immutable, meaning once a string object is created, its
value cannot be changed. Any modification results in the
creation of a new string object.
Key Features of the String Class:
• Immutability: Strings cannot be modified after
creation, which enhances security and
performance.
• Common Methods: o length(): Returns the length
of the string.
o substring(int beginIndex, int endIndex): Extracts a
portion of the string.
o indexOf(String str): Returns the index of the first
occurrence of a substring.
o toUpperCase() / toLowerCase(): Converts the string
to upper or lower case.
AWT And EvEnT
HAndling

Java provides a powerful framework for building graphical


user interfaces (GUIs) through the Abstract Window Toolkit
(AWT). This toolkit facilitates the creation of rich, interactive
applications by allowing developers to design interfaces that
respond to user actions. In this overview, we will discuss the
key concepts of AWT, including layout management, event
handling mechanisms, event models, and graphics, as well as
a brief introduction to HTML basics and applet classes.
1. Introduction to AWT
The Abstract Window Toolkit (AWT) is Java’s original
platform-dependent GUI toolkit. AWT provides a set of APIs
that enable developers to create graphical user interfaces for
Java applications. It offers a wide range of components,
including buttons, text fields, labels, and more, which can be
arranged and customized to create interactive interfaces.
Key Features of AWT:
• Platform Independence: While AWT components rely on
the underlying operating system for rendering, they
maintain Java's principle of "write once, run anywhere."
• Lightweight Components: AWT components are
referred to as heavyweight components because they
rely on native system resources, unlike Swing
components, which are lightweight and rendered by
Java.

2. Layout Manager
A Layout Manager is an interface that defines how
components are arranged in a container. Java provides
several layout managers, each offering different ways to
position and size components. Choosing the appropriate
layout manager is crucial for creating a visually appealing and
user-friendly interface.
Common Layout Managers:
• FlowLayout: Arranges components in a left-to-right flow,
much like words in a paragraph. If the container is too
narrow, the components wrap to the next line.
• BorderLayout: Divides the container into five areas:
north, south, east, west, and center. Components can be
added to these specific regions, allowing for flexible
arrangements.
• GridLayout: Arranges components in a grid format,
where each component occupies an equal amount of
space in a specified number of rows and columns.
• CardLayout: Allows multiple components to occupy the
same space, switching between them like a stack of
cards. This is useful for tabbed interfaces or wizard-like
forms.
3. Event Handling Mechanism
The event handling mechanism in AWT allows applications to
respond to user actions, such as mouse clicks, keyboard
inputs, or window events. Understanding this mechanism is
essential for creating interactive applications.
Event Model
The event model in AWT is based on the observer design
pattern, where objects (event sources) notify other objects
(event listeners) when an event occurs. The model consists of
the following components:
• Event Sources: Objects that generate events. For
example, a button can be an event source when it is
clicked.
• Event Listeners: Interfaces that define methods to
handle specific events. An event listener must be
registered with an event source to receive notifications
about events.
Event Classes
Java provides a hierarchy of event classes that represent
various types of events. Each event class encapsulates
information about the event, such as the source of the event
and additional details relevant to that event type.
Common event classes include:
• ActionEvent: Represents an action performed by the
user, such as clicking a button.
• MouseEvent: Captures mouse-related actions, like
mouse clicks, movements, or releases.
• KeyEvent: Represents keyboard actions, such as key
presses or releases.
4. Sources of Events
The sources of events are components that generate events
in response to user interactions. Examples of event sources
include:
• Buttons: Generate ActionEvent when clicked.
• Text Fields: Generate ActionEvent when the user presses
Enter.
• Mouse: Generates MouseEvent when a mouse button is
pressed or released.
• Windows: Generate events when they are opened,
closed, minimized, or resized.
5. Event Listener Interfaces
Event listener interfaces define the methods that need to be
implemented to handle specific events. When an event
occurs, the corresponding method in the listener interface is
invoked.
Common Event Listener Interfaces:
• ActionListener: Handles action events (e.g., button
clicks).
• MouseListener: Handles mouse events (e.g., mouse
clicks, entering/exiting a component).
• KeyListener: Handles keyboard events (e.g., key presses,
releases).
• WindowListener: Handles window events (e.g., closing,
opening, activating).
To respond to an event, a class must implement the
appropriate listener interface and register it with the event
source.

6. AWT: Working with Windows


AWT allows developers to create windows and dialogs that
can serve as containers for components. The main window of
an AWT application is created using the Frame class.
Key Points:
• Frames: A top-level window with a title and a border.
Frames can contain other components and can be
resized, minimized, or closed.
• Dialogs: A temporary window that prompts the user for
input or displays information. Dialogs can be modal
(blocking input to other windows) or non-modal.
Working with Windows
Developers can create and manipulate windows by setting
properties such as size, visibility, and layout. Proper
management of window events is essential for creating a
smooth user experience.
7. AWT Controls
AWT provides various controls (components) that allow users
to interact with the application. Common AWT controls
include:
• Button: Triggers an action when clicked.
• Label: Displays a non-editable text message.
• TextField: Allows users to input single-line text.
• TextArea: Allows users to input multi-line text.
• Checkbox: Represents a binary choice (checked or
unchecked).
• List: Displays a list of items from which users can select
one or more options.
These controls can be combined and customized to create
interactive user interfaces.
8. HTML Basic Tags
In addition to Java, understanding basic HTML tags is
essential for web development. HTML (HyperText Markup
Language) is the standard language for creating web pages.
Common HTML Tags:
• <html>: The root element of an HTML page.
• <head>: Contains metadata, including the title of the
document.
• <body>: Contains the content of the web page, including
text, images, and links.
• <h1> to <h6>: Header tags for defining headings of
different levels.
• <p>: Defines a paragraph of text.
• <a>: Creates a hyperlink to another page or resource.
• <img>: Embeds an image in the document.
Familiarity with HTML tags is beneficial for integrating Java
applets and web content.
9. Applet Classes
Java applets are small applications that run in a web browser.
They are created using the Applet class, which is part of the
AWT package. Applets can be used to create dynamic web
content, providing interactive experiences for users.
Key Points:
• Applets are initialized through the init() method, where
setup actions take place.
• The start() method is called when the applet becomes
visible, allowing it to begin executing.
• Applets can be embedded in HTML pages using the
<applet> tag (though deprecated in favor of the <object>
tag).

10. Graphics
AWT also provides capabilities for drawing graphics on the
screen. The Graphics class offers methods for rendering
shapes, text, and images.
Key Features:
• Drawing Shapes: Methods like drawLine(), drawRect(),
and drawOval() allow developers to create various
shapes.
• Filling Shapes: Methods like fillRect() and fillOval() fill
shapes with color.
• Rendering Text: The drawString() method allows text to
be displayed on the screen.
Developers can override the paint() method of a component
to implement custom drawing logic.
ExcEption Handling and
MultitHrEading

Understanding exception handling and multithreading is


crucial for developing robust applications. This unit covers the
fundamental concepts of exception handling and the
principles of multithreading, providing a comprehensive
overview for BCA students.
1. Exception Handling
Exception handling is a mechanism to manage errors that
occur during program execution. It allows programs to
respond to error conditions gracefully, without crashing.
a) Fundamentals of Exception Handling
An exception is an event that disrupts the normal flow of a
program's execution. It can be caused by various issues, such
as invalid input, resource unavailability, or logical errors.
Proper handling of exceptions is essential to maintain
program stability.
b) Exception Types
Exceptions are generally classified into two categories:
1. Checked Exceptions: These are exceptions that the
compiler forces the programmer to handle. They must
be either caught using a try-catch block or declared
using the throws keyword in the method signature.
Examples include IOException and SQLException.
2. Unchecked Exceptions: These exceptions are not
checked at compile time. The programmer is not
required to handle them, and they typically indicate
programming errors, such as NullPointerException and
ArithmeticException.
c) Uncaught Exceptions
An uncaught exception occurs when the program does not
handle an exception, resulting in abrupt termination. This can
lead to data loss and instability. To prevent uncaught
exceptions, developers should implement comprehensive
exception handling throughout the code.
d) Exception Handling Keywords
Key keywords in exception handling include:
• try: This block contains code that may throw an
exception. If an exception occurs, control is transferred
to the catch block.
• catch: This block handles the exception thrown by the
try block. You can have multiple catch blocks to handle
different exception types.
• finally: This block contains code that executes regardless
of whether an exception was thrown. It is commonly
used for cleanup activities, such as closing files or
releasing resources.
• throws: This keyword indicates that a method may
throw specific exceptions. It informs the caller that they
must handle or propagate the exception.
• throw: This keyword is used to explicitly throw an
exception from a method or a block of code.
e) Built-in Exceptions
Most programming languages offer a variety of built-in
exceptions that help developers handle common error
scenarios efficiently. Examples of built-in exceptions include:
• IOException: Occurs during input/output operations.
• NumberFormatException: Triggered when trying to
convert a string to a numeric type fails.
• ClassNotFoundException: Raised when the Java Virtual
Machine cannot find a specified class.
f) Creating Your Own Exception
Developers can define custom exceptions by extending the
existing Exception class. This is beneficial for creating
application-specific error conditions and providing
meaningful error messages. Custom exceptions enhance
clarity and maintainability in error handling.
2. Multithreading Fundamentals
Multithreading enables concurrent execution of multiple
threads, which allows programs to perform several tasks
simultaneously, enhancing performance and responsiveness.
a) Creating Threads
There are two primary approaches to creating threads:
1. Extending the Thread Class: A class can extend the
Thread class and override its run method, which
contains the code to be executed by the thread.
2. Implementing the Runnable Interface: A class can
implement the Runnable interface and define its run
method. This approach allows multiple threads to share
the same object and is often preferred for better design
flexibility.
b) Implementing and Extending Threads
Once a thread is created using either approach, it can be
started using the start() method. This method invokes the
run() method, which contains the logic that will be executed
in the new thread.
c) Thread Priorities
Thread priorities determine the relative importance of
threads when it comes to scheduling by the operating
system. Threads can be assigned different priorities ranging
from Thread.MIN_PRIORITY (1) to Thread.MAX_PRIORITY
(10), with Thread.NORM_PRIORITY (5) being the default.
Threads with higher priorities may be executed before those
with lower priorities.
d) Synchronization
Synchronization is a crucial concept to ensure that multiple
threads can access shared resources without causing data
inconsistency. It prevents issues like race conditions, where
the final output depends on the sequence of thread
execution.
• Synchronized Methods: A method can be declared
synchronized, ensuring that only one thread can execute
it at a time. This is particularly useful when a method
modifies shared resources.
• Synchronized Blocks: These provide a more granular
approach to synchronization. Instead of synchronizing an
entire method, only a specific block of code is
synchronized, which can improve performance.
e) Suspending, Resuming, and Stopping Threads
Managing the lifecycle of threads is essential in
multithreading:
• Suspending Threads: The suspend() method can pause a
thread temporarily. However, it is deprecated due to
potential deadlocks. Alternatives like wait() and notify()
are recommended for controlling thread execution flow.
• Resuming Threads: The resume() method can restart a
suspended thread. Like suspend(), it is deprecated.
Developers should use synchronization techniques to
resume threads based on conditions.
• Stopping Threads: The stop() method is also deprecated
due to the risk of leaving shared resources in an
inconsistent state. Instead, a safer approach is to use a
boolean flag that signals a thread to finish its execution
gracefully.
Java Packages

Java packages are a crucial aspect of organizing Java classes


and interfaces, promoting better modularity and reusability
in programming. This unit will explore the creation of
packages, additional packages provided by Java, the java.io
package for input and output operations, and an overview
of Swing classes and controls, along with the advantages of
Swing over AWT (Abstract Window Toolkit).
1. Package Creation
A Java package is a namespace that groups related classes and
interfaces. By organizing classes into packages, developers
can avoid naming conflicts and control access levels.
Creating a package involves the following steps:
• Defining a Package: At the beginning of a Java source file,
the package keyword is used to specify the package name.
The package name is typically in lowercase to avoid
conflicts with class names.
• Directory Structure: The physical structure of the package
must match the package declaration. For example, if a
class is declared in package com.example, it should reside
in the directory path com/example.
• Compilation: To compile the classes within a package, the
javac command is used along with the -d option to specify
the destination for the compiled classes.
• Using Packages: To use classes from a package, the import
statement is utilized in the Java file. This allows access to
the classes defined in the package without needing to
reference their full package name each time.
2. Additional Packages
Java provides numerous built-in packages that extend its
functionality, including:
• java.lang: This is automatically imported and contains
fundamental classes like String, Math, and System.
• java.util: Contains utility classes such as collections
framework (List, Set, Map), date and time facilities, and
random number generation.
• java.net: Provides classes for network operations,
including handling URLs, sockets, and HTTP connections.
• java.awt: Contains classes for creating graphical user
interfaces (GUIs), including components like buttons and
text fields.
• java.swing: A more advanced set of GUI components built
on top of AWT.

3. Input/Output: Exploring java.io


The java.io package is essential for handling input and output
operations in Java, providing classes for reading and writing
data to files and other data streams. Some key classes in this
package include:
• File: Represents file and directory pathnames in an
abstract manner. It provides methods for creating,
deleting, and checking the properties of files and
directories.
• InputStream and OutputStream: These are abstract
classes that represent byte streams for reading and
writing binary data.
• Reader and Writer: Abstract classes for character
streams, allowing for the handling of character data,
which is essential for text files.
• BufferedReader and BufferedWriter: These classes
provide buffering for reading and writing operations,
enhancing performance by reducing the number of I/O
operations.
• PrintWriter: A convenient class for printing formatted text
to a file or output stream.
Using the java.io package, developers can perform various I/O
operations, such as reading from or writing to files, working
with console input and output, and handling data streams.
4. Swing Classes and Controls
Swing is a powerful GUI toolkit in Java that extends the
capabilities of AWT. It provides a rich set of GUI components
and a more flexible architecture. Key features of Swing
include:
• Lightweight Components: Unlike AWT components,
Swing components are lightweight, meaning they are not
tied to the native system's GUI. This allows for a more
consistent look and feel across different platforms.
• Pluggable Look and Feel: Swing allows developers to
customize the appearance of their applications. They can
choose from various look-and-feel options or create their
own.
• Rich Set of Components: Swing provides a wide array of
components, such as buttons, labels, text fields, combo
boxes, and tables, allowing developers to create
sophisticated user interfaces.
• Event Handling: Swing components support event-driven
programming, enabling the application to respond to user
actions such as clicks, key presses, and mouse
movements.
Common Swing Controls
Some of the commonly used Swing components include:
• JFrame: A top-level window that provides a frame for the
GUI application.
• JPanel: A generic container that can hold other
components.
• JButton: A clickable button that can trigger actions.
• JLabel: A non-editable text display component.
• JTextField: An editable text input field for user input.
• JTextArea: A multi-line area for displaying and editing
text.
• JComboBox: A drop-down list of options.
• JTable: A component for displaying data in tabular format.

5. Advantages of Swing over AWT


While AWT was the original toolkit for building GUIs in Java,
Swing offers several advantages that make it the preferred
choice for modern Java applications:
• Platform Independence: Swing components are drawn
using Java code, which means they do not rely on native
system resources, resulting in a consistent appearance
across platforms.
• Enhanced Features: Swing provides more advanced
components and features, such as tables, trees, and text
areas, which are not available in AWT.
• Better Performance: Swing's lightweight components
consume fewer resources, leading to improved
performance in GUI applications.
• Customizable Look and Feel: Swing supports pluggable
look-and-feel architecture, allowing developers to switch
themes without altering the underlying code.
• Rich Event Handling: Swing offers a more sophisticated
event handling mechanism that allows for greater
flexibility in managing user interactions.
• Improved Rendering: Swing provides better graphics
rendering capabilities, enabling smoother animations and
effects.

You might also like