Java semester 2 full notes
Java semester 2 full notes
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
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
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.
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