[Go to site: main page, start]

0% found this document useful (0 votes)
22 views97 pages

Java Programming Concepts and History

The document provides a comprehensive overview of programming in Java, covering fundamental concepts such as object-oriented programming, inheritance, polymorphism, and encapsulation. It details the architecture of the Java Virtual Machine (JVM), the features of Java, and the history of its development. Additionally, it discusses various Java components including AWT, Swing, multithreading, and exception handling.

Uploaded by

t.ambika1991
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)
22 views97 pages

Java Programming Concepts and History

The document provides a comprehensive overview of programming in Java, covering fundamental concepts such as object-oriented programming, inheritance, polymorphism, and encapsulation. It details the architecture of the Java Virtual Machine (JVM), the features of Java, and the history of its development. Additionally, it discusses various Java components including AWT, Swing, multithreading, and exception handling.

Uploaded by

t.ambika1991
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

PROGRAMMING IN JAVA

UNIT – I

Introduction: Review of Object Oriented concepts – History of Java – Java buzz words – JVM architecture – Data types -
Variables - Scope and life time of variables - arrays - operators – control statements - type conversion and casting - simple
java program - constructors - methods - Static block - Static Data – Static Method String and String Buffer Classes.

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-Access Protection -Importing Packages. Interfaces: Definition–Implementation–Extending Interfaces. Exception
Handling: try – catch- throw - throws – finally – Built-in exceptions - Creating own Exception classes.

UNIT – III

Multithreaded Programming: Thread Class - Runnable interface – Synchronization–Using synchronized methods– Using
synchronized statement- Inter thread Communication –Deadlock. I/O Streams: Concepts of streams - Stream classes- Byte
and Character stream - Reading console Input and Writing Console output - File Handling.

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: Introduction: Review of Object Oriented concepts – History of Java – Java buzz words – JVM architecture –
Data types - Variables - Scope and life time of variables - arrays - operators – control statements - type conversion and
casting - simple java program - constructors - methods - Static block - Static Data – Static Method String and String
Buffer Classes.

Object Oriented Programming (OOPs) Concept in Java

Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects.
It simplifies software development and maintenance by providing some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Apart from these concepts, there are some other terms which are used in Object-Oriented design:

o Coupling
o Cohesion
o Association
o Aggregation
o Composition

Object
Any entity that has state and behavior is known as an object. For example, a chair, pen, table, keyboard, bike, etc. It
can be physical or logical.

An Object can be defined as an instance of a class. It contains an address and takes up some space in memory.
Objects can communicate without knowing the details of each other's data or code.

Class
Collection of objects is called class. It is a logical entity.

A class can also be defined as a blueprint from which you can create an individual object. Class does not consume
any space.

Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It provides
code reusability. It is used to achieve runtime polymorphism.

Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to convince the customer
differently, to draw something, for example, shape, triangle, rectangle, etc.

In Java, we use method overloading and method overriding to achieve polymorphism.


Abstraction
Hiding internal implementation and showing functionality only to the user is known as abstraction. For example,
phone call, we do not know the internal processing.

In Java, we use abstract class and interface to achieve abstraction.

Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example, a
capsule, it is wrapped with different medicines.

A Java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members
are private here.

Coupling
Coupling refers to the knowledge or information or dependency of another class. It arises when classes are aware of
each other. If a class has the details information of another class, there is strong coupling. In Java, we use private,
protected, and public modifiers to display the visibility level of a class, method, and field. We can use interfaces for
the weaker coupling because there is no concrete implementation.

Cohesion
Cohesion refers to the level of a component which performs a single well-defined task. A single well-defined task is
done by a highly cohesive method. The weakly cohesive method will split the task into separate parts. The [Link]
package is a highly cohesive package because it has I/O related classes and interface. However, the [Link] package
is a weakly cohesive package because it has unrelated classes and interfaces.

Association

Association represents the relationship between the objects. Here, one object can be associated with one object or
many objects. There can be four types of association between the objects:

o One to One
o One to Many
o Many to One, and
o Many to Many

Aggregation
Aggregation is a way to achieve Association. Aggregation represents the relationship where one object contains
other objects as a part of its state.

It represents the weak relationship between objects. It is also termed as a has-a relationship in Java. Like,
inheritance represents the is-a relationship. It is another way to reuse objects.

Composition
The composition is also a way to achieve Association. The composition represents the relationship where one object
contains other objects as a part of its state.

is a strong relationship between the containing object and the dependent object. It is the state where containing
objects do not have an independent existence.

If we delete the parent object, all the child objects will be deleted automatically.
History of Java

Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling
and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]). History of even
naming of the Java is very interesting. It went under many names.

Java Name History

YEAR DEVELOPMENT

1990 Sun Microsystems decided to develop special software that could be used to manipulate consumer electronic devices.
A team of Sun Microsystems programmers headed by James Gosling was formed to undertake this task.

1991 After exploring the possibility of using the most popular object-oriented language C++, the team announced a new
language named “Oak”.

1992 The team, known as Green Project team by Sun, demonstrated the application of their new language to control a list
of home appliances using a hand-held device with a tiny touch-sensitive screen.

1993 The World Wide Web (WWW) appeared on the Internet and transformed the text-based Internet into a graphical-rice
environment. The Green Project team came up with the idea of developing Web applets using the new language that
could run on all types of computers connected to the Internet.

1994 The team developed a Web Browser called “Hot Java” to locate and run applet programs on Internet.

1995 Oak was renamed “Java”, due to some legal snags. Many popular companies including Netscape and Microsoft
announced their support to Java.

1996 Java established itself not only as a leader for Internet Programming but also as a general-purpose object-oriented
programming language. Sun releases Java Development Kit 1.0.

1997 Sun releases Java Development Kit 1.1 (JDK 1.1)

1998 Sun releases the Java 2 with version 1.2 of the Software Development Kit (SDK 1.2).

1999 Sun releases Java 2 Platform, Standard Edition (J2SE) and Enterprise Edition (J2EE).

2000 J2SE with SDK1.3 was released.

2002 J2SE with SDK 1.4 was released.

2004 J2SE with JDK 5.0 was released. This is known as J2SE 5.0

2006 JAVA SE 6
2011 JAVA SE 7

2014 JAVA SE 8

2017 JAVA SE 9

2018 JAVA SE 10

Java Buzzwords or Features of Java

The Java programming language can be characterized by the following buzzwords:

1. Simple
2. Object-Oriented
3. Distributed
4. Compiled and Interpreted
5. Robust
6. Secure
7. Architecture-Neutral
8. Portable
9. High Performance
10. Multithreaded
11. Dynamic

1. Simple
• Java is designed to be easy for beginners and professional programmers to learn and use effectively.
• It’s simple and easy to learn if you already know the basic concepts of Object-Oriented Programming.
• Java has removed many complicated and rarely-used features, such as explicit pointers and operator
overloading.
2. Object-Oriented

• Everything in Java revolves around objects and classes.


• Java allows you to model real-world entities (like a car or a bank account) as objects in your program,
making it easier to manage and build complex applications.
• Key Object-Oriented Programming (OOP) concepts include:
o Object: An instance of a class.
o Class: A blueprint for creating objects.
o Inheritance: Allows one class to inherit the properties of another.
o Polymorphism: The ability of objects to take on multiple forms.
o Abstraction: Hides the complex details and shows only the essentials.
o Encapsulation: Keeps the data safe by restricting access to it.
3. Distributed
• Java is designed to create distributed applications on networks.
• Java applications can access remote objects on the Internet as easily as they can do in the local system.
• Java enables multiple programmers at multiple remote locations to collaborate and work together on a
single project.
4. Compiled and Interpreted
• Java combines both compiled and interpreted approaches, making it a two-stage system.
• Compiled: Java compiles programs into an intermediate representation called Java Bytecode.
• Interpreted: Bytecode is then interpreted, generating machine code that can be directly executed by the
machine that provides a JVM.
5. Robust
• Java provides many features that make programs execute reliably in a variety of environments.
• Java is a strictly typed language that checks code at compile time and runtime.
• Java handles memory management with garbage collection and captures serious errors through exception
handling.
6. Secure
• Java does not use pointers, which helps prevent unauthorized memory access.
• The JVM verifies Java bytecode before execution, ensuring that it adheres to Java’s security constraints.
• Java applications run in a restricted environment (sandbox) that limits their access to system resources and
user data, enhancing security.
7. Architecture-Neutral
• Java language and JVM help achieve the goal of “write once; run anywhere, any time, forever.”
• Changes and upgrades in operating systems, processors, and system resources do not force any changes in
Java programs.
8. Portable
• Java provides a way to download programs dynamically to various types of platforms connected to the
Internet.
• Java is portable because of the JVM, which provides a consistent runtime environment across different
platforms.
9. High Performance
• Java performance is high because of the use of bytecode.
• The bytecode can be easily translated into native machine code.
10. Multithreaded
• Multithreaded programs handle multiple tasks simultaneously, which is helpful in creating interactive,
networked programs.
• Java run-time system supports multiprocess synchronization for constructing interactive systems.
11. Dynamic
• Java can link in new class libraries, methods, and objects dynamically.
• Java programs carry substantial amounts of run-time type information, enabling dynamic linking in a safe
and expedient manner.

JVM ARCHITECTURE
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which
java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).

What is JVM
It is:

1. A specification where working of Java Virtual Machine is specified. But implementation provider is
independent to choose the algorithm. Its implementation has been provided by Oracle and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run the java class, an
instance of JVM is created.

What it does
The JVM performs following operation:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JVM provides definitions for the:

o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.

1. Class Loader Subsystem


It is mainly responsible for three activities.
Loading
Linking
Initialization
Loading:
The Class loader reads the “.class” file, generate the corresponding binary data and save it in the method area. For
each “.class” file, JVM stores the following information in the method area.
The fully qualified name of the loaded class and its immediate parent class.
Whether the “.class” file is related to Class or Interface or Enum.
Modifier, Variables and Method information etc.
After loading the “.class” file, JVM creates an object of type Class to represent this file in the heap memory.
Linking
Performs verification, preparation, and (optionally) resolution.
Verification: It ensures the correctness of the .class file i.e. it checks whether this file is properly formatted
and generated by a valid compiler or not. If verification fails, we get run-time
exception [Link]. This activity is done by the component ByteCodeVerifier. Once this activity
is completed then the class file is ready for compilation.
Preparation: JVM allocates memory for class static variables and initializing the memory to default values.
Resolution: It is the process of replacing symbolic references from the type with direct references. It is done
by searching into the method area to locate the referenced entity.
Initialization
In this phase, all static variables are assigned with their values defined in the code and static block(if any). This is
executed from top to bottom in a class and from parent to child in the class hierarchy. In general, there are three
class loaders:
Bootstrap class loader: Every JVM implementation must have a bootstrap class loader, capable of loading
trusted classes.
Extension class loader: It is a child of the bootstrap class loader. It loads the classes present in the extensions
directories or any other directory specified by the [Link] system property
System/Application class loader: It is a child of the extension class loader. It is responsible to load classes
from the application classpath. It internally uses Environment Variable which mapped to [Link]. It is
also implemented in Java by the [Link]$AppClassLoader class.
2. JVM Memory Areas
Method area: In the method area, all class level information like class name, immediate parent class name,
methods and variables information etc. are stored, including static variables. There is only one method area
per JVM, and it is a shared resource.
Heap area: Information of all objects is stored in the heap area. There is also one Heap Area per JVM. It is
also a shared resource.
Stack area: For every thread, JVM creates one run-time stack which is stored here. Every block of this stack
is called activation record/stack frame which stores methods calls. All local variables of that method are
stored in their corresponding frame. After a thread terminates, its run-time stack will be destroyed by JVM. It
is not a shared resource.
PC Registers: Store address of current execution instruction of a thread. Obviously, each thread has separate
PC Registers.
Native method stacks: For every thread, a separate native stack is created. It stores native method
information.

3. Execution Engine
Execution engine executes the “.class” (bytecode). It reads the byte-code line by line, uses data and information
present in various memory area and executes instructions. It can be classified into three parts:
Interpreter: It interprets the bytecode line by line and then executes. The disadvantage here is that when one
method is called multiple times, every time interpretation is required.
Just-In-Time Compiler(JIT) : It is used to increase the efficiency of an interpreter. It compiles the entire
bytecode and changes it to native code so whenever the interpreter sees repeated method calls, JIT provides
direct native code for that part so re-interpretation is not required, thus efficiency is improved.
Garbage Collector: It destroys un-referenced objects
4. Java Native Interface (JNI)
It is an interface that interacts with the Native Method Libraries and provides the native libraries(C, C++)
required for the execution. It enables JVM to call C/C++ libraries and to be called by C/C++ libraries which may
be specific to hardware.
5. Native Method Libraries
These are collections of native libraries required for executing native methods.
Data Types in Java
Data types in Java are of different sizes and values that can be stored in the variable that is made as per
convenience and circumstances to cover up all test cases. Java has two categories in which data types are
segregated
1. Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double. The Boolean with
uppercase B is a wrapper class for the primitive data type boolean in Java.
2. Non-Primitive Data Type or Object Data type: such as String, Array, etc.

1. boolean Data Type

The boolean data type represents a logical value that can be either true or false.
Syntax:
boolean booleanVar;
2. byte Data Type
The byte data type is an 8-bit signed two’s complement integer. The byte data type is useful for saving memory in
large arrays.
Syntax:
byte byteVar;
3. short Data Type
The short data type is a 16-bit signed two’s complement integer.
Syntax:
short shortVar;
4. int Data Type
It is a 32-bit signed two’s complement integer.
Syntax:
int intVar;
5. long Data Type
The range of a long is quite large
Syntax:
long longVar;
6. float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float (instead of double) if you
need to save memory in large arrays of floating-point numbers. The size of the float data type is 4 bytes (32 bits).
Syntax:
float floatVar;
7. double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating-point. For decimal values, this data type is
generally the default choice. The size of the double data type is 8 bytes or 64 bits.
Syntax:
double doubleVar;
8. char Data Type
The char data type is a single 16-bit Unicode character with the size of 2 bytes (16 bits).
Syntax:
char charVar;
Non-Primitive (Reference) Data Types

The Non-Primitive (Reference) Data Types will contain a memory address of variable values because the
reference types won’t store the variable value directly in memory. They are strings, objects, arrays, etc.
1. Strings
Strings are defined as an array of characters. The difference between a character array and a string in Java is, that
the string is designed to hold a sequence of characters in a single variable whereas, a character array is a
collection of separate char-type entities. Unlike C/C++, Java strings are not terminated with a null character.
Syntax: Declaring a string
<String_Type> <string_variable> = “<sequence_of_string>”;
2. Class
1. A class is a user-defined blueprint or prototype from which objects are created. It represents the set of
properties or methods that are common to all objects of one type. In general, class declarations can include these
components, in order:
2. Modifiers : A class can be public or has default access
3. Class name: The name should begin with an initial letter (capitalized by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A
class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the
keyword implements. A class can implement more than one interface.
5. Body: The class body is surrounded by braces, { }.
3. Object
An Object is a basic unit of Object-Oriented Programming and represents real-life entities. A typical Java
program creates many objects, which as you know, interact by invoking methods. An object consists of :
1. State : It is represented by the attributes of an object. It also reflects the properties of an object.
2. Behavior : It is represented by the methods of an object. It also reflects the response of an object to other
objects.
3. Identity : It gives a unique name to an object and enables one object to interact with other objects.
4. Interface
Like a class, an interface can have methods and variables, but the methods declared in an interface are by default
abstract (only method signature, no body).
Interfaces specify what a class must do and not how. It is the blueprint of the class.
An Interface is about capabilities like a Player may be an interface and any class implementing Player must
be able to (or must implement) move(). So it specifies a set of methods that the class has to implement.
If a class implements an interface and does not provide method bodies for all functions specified in the
interface, then the class must be declared abstract.
A Java library example is Comparator Interface . If a class implements this interface, then it can be used to
sort a collection.
5. Array
An Array is a group of like-typed variables that are referred to by a common name..
In Java, all arrays are dynamically allocated
Since arrays are objects in Java, we can find their length using member length
A Java array variable can also be declared like other variables with [] after the data type.
The variables in the array are ordered and each has an index beginning with 0.
Java array can also be used as a static field, a local variable, or a method parameter.
The size of an array must be specified by an int value and not long or short.
The direct superclass of an array type is Object.
Every array type implements the interfaces Cloneable and [Link].
_

Variables in Java
Java variable is a name given to a memory location. It is the basic unit of storage in a program.
The value stored in a variable can be changed during program execution.
Variables in Java are only a name given to a memory location. All the operations done on the variable affect
that memory location.
In Java, all variables must be declared before use.

1. datatype: Type of data that can be stored in this variable.


2. data_name: Name was given to the variable.
In this way, a name can only be given to a memory location. It can be assigned values in two ways:
Variable Initialization
Assigning value by taking input
How to Initialize Variables in Java?
It can be perceived with the help of 3 components that are as follows:
datatype: Type of data that can be stored in this variable.
variable_name: Name given to the variable.
value: It is the initial value stored in the variable.

Types of Variables in Java


Now let us discuss different types of variables which are listed as follows:
1. Local Variables
2. Instance Variables
3. Static Variables
1. Local Variables
A variable defined within a block or method or constructor is called a local variable.
The Local variable is created at the time of declaration and destroyed after exiting from the block or when the
call returns from the function.
public SumExample
{
public void calculateSum() {
int a = 5; // local variable
int b = 10; // local variable
int sum = a + b;
[Link]("The sum is: " + sum);
} // a, b, and sum go out of scope here
}

2. Instance Variables
Instance variables are non-static variables and are declared in a class outside of any method, constructor, or
block.
As instance variables are declared in a class, these variables are created when an object of the class is created
and destroyed when the object is destroyed.
Unlike local variables, we may use access specifiers for instance variables

public class Circle {


double radius; // instance variable
public double calculateArea() {
return [Link] * radius * radius;
}
}

3. Static Variables
Static variables are also known as class variables.
These variables are declared similarly to instance variables. The difference is that static variables are declared
using the static keyword within a class outside of any method, constructor, or block.
public class Bank {
static double interestRate; // class variable
// ...
}

Arrays in Java
An array is typically a grouping of elements of the same kind that are stored in a single, contiguous block of
memory.

Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are
stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a
fixed set of elements in a Java array.

Table of Content
Basics of Arrays in Java
Creating, Initializing, and Accessing an Arrays in Java
Types of Arrays in Java
o 1. Single-Dimensional Arrays
o 2. Multi-Dimensional Arrays
Arrays of Objects in Java
Basics of Arrays in Java
There are some basic operations we can start with as mentioned below:
1. Array Declaration
To declare an array in Java, use the following syntax:
type[] arrayName;
type: The data type of the array elements (e.g., int, String).
arrayName: The name of the array.
2. Create an Array
To create an array, you need to allocate memory for it using the new keyword:
// Creating an array of 5 integers
numbers = new int[5];
This statement initializes the numbers array to hold 5 integers. The default value for each element is 0.
3. Access an Element of an Array
We can access array elements using their index, which starts from 0:
// Setting the first element of the array
numbers[0] = 10;
// Accessing the first element
int firstElement = numbers[0];
The first line sets the value of the first element to 10. The second line retrieves the value of the first element.
4. Change an Array Element
To change an element, assign a new value to a specific index:
// Changing the first element to 20
numbers[0] = 20;
5. Array Length
We can get the length of an array using the length property:
// Getting the length of the array
int length = [Link];
Creating, Initializing, and Accessing an Arrays in Java
For understanding the array we need to understand how it actually works. To understand this follow the flow
mentioned below:
Declare
Initialize
Access
i. Declaring an Array
The general form of array declaration is
Method 1:
type var-name[];
Method 2:
type[] var-name;
ii. Initialization an Array in Java
When an array is declared, only a reference of an array is created. The general form of new as it applies to one-
dimensional arrays appears as follows:
var-name = new type [size];
Example:
// declaring array
int intArray[];
// allocating memory to array
intArray = new int[20];
// combining both statements in one
int[] intArray = new int[20];
Array Literal in Java
In a situation where the size of the array and variables of the array are already known, array literals can be used.
// Declaring array literal
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
The length of this array determines the length of the created array.
There is no need to write the new int[] part in the latest versions of Java.
iii. Accessing Java Array Elements using for Loop
Now , we have created an Array with or without the values stored in it. Access becomes an important part to
operate over the values mentioned within the array indexes using the points mentioned below:
Each element in the array is accessed via its index.
The index begins with 0 and ends at (total array size)-1.
All the elements of array can be accessed using Java for Loop.
Let us check the syntax of basic for loop to traverse an array:
// Accessing the elements of the specified array
for (int i = 0; i < [Link]; i++)
[Link](“Element at index ” + i + ” : “+ arr[i]);
Types of Arrays in Java
Java supports different types of arrays:
1. Single-Dimensional Arrays
These are the most common type of arrays, where elements are stored in a linear order.
// A single-dimensional array
int[] singleDimArray = {1, 2, 3, 4, 5};

Arrays of Objects in Java


An array of objects is created like an array of primitive-type data items in the following way.
Syntax:
Method 1:
ObjectType[] arrName;
Method 2:
ObjectType arrName[];
Multidimensional Arrays in Java
Multidimensional arrays are arrays of arrays with each element of the array holding the reference of other
arrays. These are also known as Jagged Arrays. A multidimensional array is created by appending one set of
square brackets ([]) per dimension.
Syntax:
There are 2 methods to declare Java Multidimensional Arrays as mentioned below:
// Method 1
datatype [][] arrayrefvariable;
// Method 2
datatype arrayrefvariable[][];
Operators in Java
Operators in Java are the symbols used for performing specific operations in Java
Operators are the building blocks of Java expressions, allowing you to perform calculations,
comparisons, and more.
Java provides a rich operator environment.
Operators divided into four groups:
1. Arithmetic operators
2. Relational operators
3. Boolean/Logical operators
4. Assignment operators
5. Increment and Decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators

Arithmetic Operators
Arithmetic operators are used in mathematical
expression. OPR MEANING
The operands of the arithmetic operators must be of
numeric type. + Addition
Ex: a-b, a*b, a/b
- Subtraction(unary)

* Multiplication

Relational Operators / Division


We often compare two quantities and depending on
their relation, take certain decisions. % Modulus(return remainder division)

OPERATOR MEANING

== Equal to

!= not equal to

> Greater than


It determines the relationship that one operand has to the
other. < Less than

ae-1 relational operator ae-2 >= Greater than or equal to


ae-1 andae-2 are arithmetic expression.
<= Less than or equal to
[Link](“a<b is “+(a<b));

It displays result as true.

Logical Operators
It operates on Boolean operands.
The logical operators are used to form compound condition by OPERATOR MEANING
combining two or more relation.
It combines two Boolean values to form a resultant Boolean value. && Logical AND
EX: (Total>=100 || average >=80)
|| Logical OR
Truth table

Value of the expression ! Logical NOT

op-1 op-2 op-1 && op- op-1 || op-2


2

True True True True

True False False True

False True False True

False False False False

Op-1 && op-2 is true if both op-1 and op-2 are true and false otherwise.
Op-1 || op-2 is false if both op-1 and op-2 are false and true otherwise.

AND operator example:


public class OperatorExample{
public static void main(String Output:
args[]){int a=10; false
int b=5; 10
int c=20; false
[Link](a<b&&a++<c);//false && true = false 11
[Link](a);//10 because second condition is not checked
[Link](a<b&a++<c);//false && true = false
[Link](a);//11 because second condition is checked
}
}
Output:
OR operator
public class OperatorExample{ true
public static void main(String
args[]){int a=10; true
int b=5;
int c=20; true
[Link](a>b||a<c);//true || true = true
[Link](a>b|a<c);//true | true = true
[Link](a>b||a++<c);//true || true = true 10
[Link](a);//10 because second condition is not checked
[Link](a>b|a++<c);//true | true = true
[Link](a);//11 because second condition is checked
}
}

Assignment Operators
‘=’ is an assignment operator. It assigns the value/variable on right side to the variable on the left
side.
Syntax: op= exp;

Where v is a variable, exp is an expression and op is a java binary operator.

assignment operator Shorthand operator

a=a+1 a+=1

a=a-1 a-=1

a=a*(n+1) a*=n+1

a=a/n(n+1) a/=n+1

a=a%b a %=b

Java has some shorthand assignment operators.


Example for shorthand assignment operator: a+=5 which is equivalent to simple assignment
operator a=a+5.
The use of shorthand assignment operators has three advantages:
✓ What appears on the left-hand side need not be repeated and therefore it becomes easier to
write.
✓ The statement is more concise and easier to read.
✓ Use of shorthand operator results in a more efficient code.
Java allows the user to create a chain of assignment.
Ex: intx,y,z; x=y=z=100;

Example: Output:
public class OperatorExample{
public static void main(String[] 13
args){
int a=10; 9
a+=3;//10+3
[Link](a);
a-=4;//13-4
[Link](a);
a*=2;//9*2
[Link](a);
a/=2;//18/2
[Link](a);
}
}

Increment and Decrement Operators


++ and -- are increment and decrement operators.
The operator ++ adds 1 to the operand while –subtracts 1.
Both are unary operator.
Ex: ++m; or m++
--m or m—

Ex:
class inc
{
public static void main(String ar[])
{
int a=1;
int b=2;
intc,d;
c=++b;
d=a++;
c++;
[Link](“a= “+a);
[Link](“b= “+b);
[Link](“c= “+c);
[Link](“d= “+d);
}}

Conditional Operator
?: is a conditional operator.
It is also called as ternary operator. Syntax: exp1? exp2:exp3;
This operator replaces the if-then-else statement.

Java Ternary Operator Example:


public class OperatorExample{ Output:
public static void main(String
args[]){int a=2; 2
int b=5;
int min=(a<b)?a:b;
[Link](min);
}}

Bitwise Operators
The bitwise operators are used for testing the bits, or shifting them to the right or left.
Bit wise operator can’t apply to float and double.

Ex: [Link](x<<2);

OPERATO MEANING
R

~ One’s complement

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

>> Shift right

>>> Shift right with zero fill

<< Shift left


Ex:
a=13;
b=25;
binary numbers are:
a = 00001101
b = 00011001
a&b = 00001001
a|b = 00011101
a^b = 00010100
a=8;
a>>2;
a=00001000>>2 = 00000010 =
2a<<2;
a=00001000<<2 = 00100000 = 32

Shift right with zero fill is similar to shift right for positive numbers.
The different arises when we dealing with negative numbers. The negative numbers have the higher-
order bit set to 1. The right shift operator preserves the higher order bit as 1. The shift right zero fill
shifts zero into all upperbits including higher order bit

SPECIAL OPERATORS
Some special operators are:
✓ Instance operator
✓ Dot operator
✓ New operator

Instance operator:
The instance operator tests whether an instance derives from a particular class or interface.
The return type is Boolean.
The general form is: Person instanceof student

Dot operator:
The member variable and member methods can be accessed through the member selectionoperator
or dot operator (.)
The general form is [Link] // reference to the variable age

[Link]() // reference to the method salary()

DECISION MAKING AND BRANCHING STATEMENTS-

Introduction
When a program breaks the sequential flow and jump to another part of the code, it is called branching. When
the branching is based on a particular condition, it is known as conditional branching. If branching takes place
without any decision, it is known as unconditional branching.
Java support control or decision making statements.
1. If statement
2. Switch statement
3. Conditional operation statement

Decision Making With If Statement


The if statement is a powerful decision making statement and is used to control the flow of execution of
statements.
✓ Simple if statement
✓ If…else statement
✓ Nested if…else statement
✓ Else if ladder

Simple If Statement
Syntax:

if (test expression)

Statement block;

} Statement-x;
The statement block may be single statement or a group of statements.
If the test expression is true then statement block will be executed otherwise statement block willbe
skipped and execution will jump to statement x.

Example program:
import [Link].*;
class first
{
Output:
public static void main(String args[ ])
{ int a=55, b= 32;
if (a>b) Largest value is a: 55
{
[Link] (“Largest value is a:”, +a);
}
}
}
The If…Else Statement

Syntax:
if(test expression)

{
Statement block (true);
}

else
{ Statement block (false);

}
Statement-x;
The if-else statement is an extension of simple if statement.
If the test expression is true, then the statement block true immediately following the if statement isexecuted;
otherwise the statement block false are executed.

Example program:
import [Link].*;
Output:

Largest value is b: 32
class first1
{
public static void main(String args[ ])
{
int a=25, b=
32;if (a>b)
{
[Link](“Largest value is a: ” , +a);
}
else
{
[Link](“Largest value is b: ” , +b);
}
}
}
Nesting Of If-Else Statement
When series of decisions are involved, we may have to use more then one if….else statement in
nested form as follows:
Syntax:
if test condition 1
{
if (test condition2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}

statement-x;
If the Condition-1 is false, the statement-3 will be executed; otherwise it continues to perform the
second test.
If the Condition-2 true, the statement-1 will be evaluated; otherwise the statement-2 will be
evaluated and then the control is transferred to the statement-.

Example program:
import [Link].*;
class Large
{ public static void main(String args[])
{
int a=325, b=712, c=478;
[Link](“Largest value
is:”);if(a>b)
{ if(a>c)
{
[Link](a);
}
else Output:
{
[Link](c);
}
}
else
{
if(c>b
) [Link](c);
{

}
else [Link](b);
{

}
}
}
}

The Else-If Ladder


This is another way of putting ifs together when multipath decisions are involved.
A multipath decision is a chain of ifs in which the statement associated with each else is an if.

Syntax
: if (condition1)
statement-1;
else if(condition2)
statement-2;
……
……
else if(condition n)
statement-n;
else
default-statement;
statement-x;
The conditions are evaluated from the top downwards. As soon as the true condition is found, the statement
associated with it is executed and the control is transferred to the statement-x.
When all the conditions becomes false, then the final else containing default-statement will be executed.
Example program:
import [Link].*;
class Second
{
public static void main(String args[])
{ Output:
introllnumber [] = {100, 101, 102, 103};
100 distinction
int marks[] = {81, 72, 43, 48};
for (int i =0; i<rollnumber; i++) 101 Ist class
102 Fail
103 2nd class
{
if(marks [i]> 75)
[Link](rollnumber[i] +”” distinction );
else if(marks[i] > 55)
[Link](rollnumber[i] +”” Ist class);
else if(marks[i] > 45)
[Link](rollnumber[i] +”” 2nd class);
else
[Link](rollnumber[i] +”fail”);
}
}
}
The Switch Statement
Java has a built-in multiway decision statement known as switch.
The switch statement tests the value of a given variable(or expression)against a list of case values and when a
match is found, a block of statements associated with that case is executed.
Syntax:
switch (expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
……
default:
default-block;
break;
}
Statement-x;
The expression is an integer expression or characters. Value-1, Value-2… are constants or constant expressions
and are known as case labels.
Block1, Block-2… are statement list and may contain zero or more statements. All case labels are end with
colon(:).
When the switch is executed, the value of the expression is successively compared against the values value-1,
value-2…..
If a case is found whose value matches with the value of the expression, then the block of statements follows the
case are executed.
The default is an optional case.
The break statement at the end of each block signals the end of a particular case and cause an exit from the
switch statement, transferring control to the statement-x following the switch.
Important points:
The case variables can be int, short, byte, char, or enumeration.
String type is also supported since version 7 of Java
Cases cannot be duplicate
Default statement is executed when any of the case doesn't match the value of expression. It is optional.
Break statement terminates the switch block when the condition is satisfied. It is optional, if not used, next case
is executed.
While using switch statements, we must notice that the case expression will be of the same type as the variable.
However, it will also be a constant value.
Example program:
import [Link].*;
class letter
{
public static void main(String args[])
{
char letter; Output:
switch (letter)
{
case ‘a’:
The given alphabet is a vowel
case ‘e’:
case ‘i’ :
case ‘o’:
case ‘u’: [Link](“The given alphabet is a
vowel”);break:
default: [Link](“the given alphabet is not a vowel”);
}
}
}
The? : (conditional) operator
The ?: is a conditional operator.
It is also called as ternary operator.
General form: (Boolean-expression) ? (expression1) : (expression2)
The exp1 is evaluated first. If it is true, then the expression exp2 is evaluated and its value becomes
the value of the conditional expression.
If exp1 is false, exp3 is evaluated and its value becomes the value of the conditional expression.
Example:
If(x<0
) flag = 0; flag = (x<0) ? 0 : 1

else ;flag = 1;
DECISION MAKING AND
LOOPING
Introduction
Sequences of statements are executed until some conditions for termination of the loop are
satisfied.
A program loop consists of two segments:
1. Body of the loop
2. Control statement
The control statement tests certain conditions and then directs the repeated execution of the
statements contained in the body of the loop.
Depending on the position of the control statements
in the loop, a control structure may classify in to two
types.
1. Entry-controlled loop
2. Exit-controlled loop

Entry-controlled loop:
The control conditions are tested before the start of
the loop execution.
If the conditions are not satisfied, then the body of the loop will not be executed. Otherwise it is
called as pre-test loop. Eg: while loop.

Exit-controlled loop:
The test is performed at end of the body of the loop and therefore the body is executed
unconditionally for the first time. Another name for Exit-controlled loop is post-test loop.

Eg: do while.

Iteration Statement:
The process of repeatedly executing a block of statements is known as looping (or) iteration.
The Java language provides for three constructs for performaing loop operations.
 The while statement
 The do… while statement
 The for statement
The While Statement

The simplest of all the looping structures in Java is the while statement.
Syntax:
Initialization;
while(test condition)
{
body of the loop;
}
The while is an entry-controlled loop statement.
The test condition is evaluated and if the condition is true, then the body of the loop is executed. After execution
of the body, the test condition is once again evaluated and if it is true, the body is executed once again.
Example program:
import [Link].*;
class a
{
public static void main(String args[])
{ j=1;
while(j <4) Output:
{ [Link] (j);
j= j + 1; 123
}
}}
The Do Statement
In some situations we can execute the body of the loop before the test is performed.
Such situations can be handled with the help of do statement.
Syntax:
Initialization;
do
{
body of the loop;
} while(test condition);
At the end of the loop, the test condition in the while statement is evaluated, if the condition is true, the program
continues to evaluate the body of the loop once again.
This process continues as long as the condition is true.
When the condition becomes false, the loop will be terminated and the control goes to the statement that
appears immediately after the while statement.
Since the test condition is evaluated at the bottom of the loop,the do-while construct provides an exit controlled
loop and therefore the body of the loop is always executed at least once.
Example program:
import [Link].*;
class a1
{
public static void main (String args[])
{
j=1:
do
{
[Link] (j);
j= j + 1; Output:
} while(j <4);
}
}

Difference between while and do while

while do-while
It is a looping construct that will execute only if the test It is a looping construct that will execute at least once
condition is true. even if the test condition is false.
It is an entry controlled loop. It is an exit controlled loop.

The For Statement


The for loop is another entry-controlled loop that provides a more concise loop structure.
Syntax:
for(initialization; test condition; increment) Output:
{ Number 10
body of the loop; Number 9
}
The execution of the for loop is as follows
Number 8
Initialization of the control variables is done first. Number 7
The value of the control varaible is tested using the test condition. Number 6
The test condition is relational expression. Number 5
When the body of the loop is executed, the control is transferred back to the for statement after Number 4
evaluating the last statement in the loop. Now ther control variable got the increment. Number 3
This process continues till the value of the control variable fails to satisfy the test condition. Number 2
Example:
Number 1
import [Link].*;

class Forcls{
public static void main (String args[])
{
int n;
for(n=10;n>0;n--)
[Link](“Number”+n);
}
}

Additional Features of FOR Loop


More than one variable can be initialized at a time in the for atatement.
Ex: for(int p=1, int n=1;n<10;n++)
Like initialization increment section may also have more than one part.
Ex; for(int n=1;int p=1;n<m;n=n+1,p=p+1)
The third feature is that the test condition may have any compound relation.
EX: for(int i=1; i<20 &&
sum<100;++i)Nesting of for loops
Nesting of loop,that is one for statement within another for statement,is allowed in java.
EX: for(i=1;i<10;i++)
{ ……..
……..
for(j=1;j<=5;++j)
{ …….
……
}
………
}
The Enhanced For Loop
The enhanced for loop, also called for each loop is an extended language feature introduced with the J2SE 5.0
release. This feature helps us to retrieve the array of elements efficiently rather than using array indexes.
for (Type Identifier: Expression)
{
// statements;
}
where Type represents the data type or object used; Identifier refers to the name of a variable; and Expression is
an instance of the [Link] interface or an array.
It starts with the keyword for like a normal for-loop.
Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the
base type of the array, followed by a colon, which is then followed by the array name.
In the loop body, you can use the loop variable you created rather than using an indexed array element.
It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)

Limitations of for-each loop:


For-each loops are not appropriate when you want to modify the array:
For-each loops do not keep track of index. So we can not obtain array index using For-Each loop
For-each only iterates forward over the array in single steps
For-each cannot process two decision making statements at once
For-each also has some performance overhead over simple iteration

Break
Jumping out of a loop - Skipping a part of a loop
Loops perform a set of operations repeatedly until the control variable fails to satisfy the test condition
Java permits a jump from one statement to the end or beginning of a loop as well as a jump out of a loop.
Break statement: (Jumping out of a loop)
The break statement is used for exit from a loop. It is used within while, do or for loops.
As the name suggests, the break statementis used to break the current flow of the program and transfer the
control to the next statement outside a loop or switch statement. However, it breaks only the inner loop in the
case of the nested loop. The break statement cannot be used independently in the Java program, i.e., it can only
be written inside the loop or switch statement.
Syntax: break;
Example: I=0;
while(I<=10)
{
I=I+1;
if(I==5)
break;
[Link](I);
}
Java Break Statement with Inner Loop
It breaks inner loop only if you use break statement inside the inner loop.
Java Break Statement with Labeled For Loop
We can use break statement with a label. The feature is introduced since JDK 1.5. So, we can break any loop in
Java now whether it is outer or inner loop.
Continue statement: (Skipping a part of a loop)
This statement causes the loop to be continued with the next iteration after skipping any statement in between.
Syntax: continue;
Example: I=0;
while(I<=10)
{
I=I+1;
if(I==5)
continue;
[Link](I);
}

Return Statement in Java

In Java programming, the return statement is used for returning a value when the execution of the block is completed

Syntax:
return return value;

public class SampleReturn2


{
/* Method with an integer return type and arguments */
public int CompareNum(int x, int y)
{
[Link]("x = " + x + "\ny = " + y);
if(x>y)
return x;
else
return y;
}

/* Driver Code */
public static void main(String ar[])
{
SampleReturn2 obj = new SampleReturn2();
int result = [Link](15,24);
[Link]("The greater number among x and y is: " + result);
}
}

Type Conversion and Casting

In Java, type conversion is the process of converting a data type to another. This is crucial for various
operations, such as arithmetic calculations, assignments, and method calls.

Implicit Type Conversion (Widening Conversion)

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

In this case, the byte value 10 is automatically converted to an int value.

Explicit Type Conversion (Narrowing Conversion)

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

Simple Java Program

publicclassHelloWorld{
publicstaticvoidmain(String[] args){
[Link]("Hello, World!");
}
}

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.
Key Points about Constructors:

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 Sample
{
Sample()
{
[Link](“Constructor Method”);
}
void display()
{
[Link](“Ordinary method”);
}
}
class Demo
{
public static void main(String arg[])
{
Sample obj = new Sample();
[Link]();
}
}
Output:
Constructor method
Ordinary method

Why Use Constructors?

• Initialization: Ensure that objects are created in a valid state.


• Flexibility: Provide different ways to create objects with various initializations.
• Code Reusability: Centralize object initialization logic in one place.

Methods

Methods are the building blocks of Java programs. They encapsulate a specific task or behavior and can be reused
throughout your code.
Basic Structure of a Method:

public static return_type method_name(parameter_list){


// Method body
// ...
return value; // If the method has a return type
}

Explanation of the components:

• public: Access modifier, making the method accessible from anywhere.


• static: Keyword indicating that the method belongs to the class itself, not to any specific object.
• return_type: The data type of the value returned by the method. If the method doesn't return anything, the
return type is void.
• method_name: The unique name of the method.
• parameter_list: A comma-separated list of parameters, each with its data type and name.
• Method body: The code that implements the method's functionality.
• return value: The value returned by the method, if any.

METHOD OVERLOADING
Method overloading is one of the ways that java implements polymorphism
In java, it is possible to create methods that the same name, but different parameter list and different definition.
This is called method overloading.
Polymorphism means “one interface, multiple methods”.
When an overloaded method is invoked, java uses the type and/or number of arguments as its guide to
determine which version of the overloaded method to actually call.
While overloaded methods may have different return types, the return type alone is insufficient to distinguish
two versions of method.
When an overloaded method is called, java looks for a match between the arguments used to call the method
and method’s parameters.
Example: class Overload
class Sample {
{ public static void main(String arg[])
void sample() {
{ Sample s= new
[Link](“method overloading”);
Sample();[Link](10,5);
}
void sample(int a, int b) [Link](10)
{
[Link](“Rectangle:” +a*b); }
}
void sample(int a)
{ }
[Link](“square:” +a*a);
}

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:
publicclassMyClass{
static {
[Link]("Static block executed.");
}

public static void main(String[] args) {


[Link]("Main method executed.");

}
}
Output:
Static block executed.
Main method executed.
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:
publicclassMyClass{
staticint count = 0; // Static variable

publicvoidincrementCount(){
count++;
}

publicstaticvoidmain(String[] args){
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();

[Link]();
[Link]();

[Link]("Count: " + count); // Output: 2


}
}
Static Method
Static Methods in Java
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:
publicclassMathUtils{
publicstaticintadd(int a, int b){
return a + b;
}

publicstaticdoublecalculateArea(double radius){
return [Link] * radius * radius;
}
}

publicclassMain{
publicstaticvoidmain(String[] args){
int sum = [Link](5, 3);
double area = [Link](2.5);

[Link]("Sum: " + sum);


[Link]("Area: " + area);
}
}
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:
• Static methods cannot access instance variables or methods directly.
• Static methods are often used for utility functions that are independent of object state.
• Static methods can be useful for creating reusable code that can be called from anywhere in your
application.

String and String Buffer Classes


String Class
• Immutable: Once a String object is created, its value cannot be changed.
• Used for representing fixed character sequences.
Key Methods:
• length(): Returns the length of the string.
• charAt(index): Returns the character at the specified index.
• concat(str): Concatenates the specified string to the end of this string.
• substring(beginIndex): Returns a new string that is a substring of this string.
• substring(beginIndex, endIndex): Returns a new string that is a substring of this string.
• indexOf(str): Returns the index within this string of the first occurrence of the specified substring.
• toLowerCase(): Converts all of the characters in this String to lowercase.
• toUpperCase(): Converts all of the characters in this String to uppercase.
• trim(): Returns a copy of the string, with leading and trailing whitespace omitted.
StringBuffer Class
• Mutable: The contents of a StringBuffer object can be modified.
• Used for manipulating character sequences efficiently.
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;
[Link](str3);

// StringBuffer
StringBuffer sb = new StringBuffer("Java");
[Link](" Programming");
[Link](5, " is ");
[Link](sb);
}
}
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.

INHERITANCE

The mechanism of deriving a new classe from an old one is called Inheritance.
The old class is known as the base class or superclass or parent class and new one is called the
subclass or derived class or child class.
Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance variables
and methods defined by the superclass and add its own, unique elements.
Inheritance allows subclasses to inherit all the variables and methods of their parent classes.
TYPES OF INHERITANCE:

Inheritance may take different forms,

1. Single Inheritance (only one super class).


2. Hierarchical Inheritance (One super class, many subclasses).
3. Multilevel Inheritance (Derived from a derived class).
4. Hybrid Inheritance (Combination of inheritance).
Java does not directly implement multiple inheritance, this concepts is implemented using a
seconding inheritance path in the form of interfaces.
A
A
Super class A A
B
Sub class
B B
B C D
C D
Single Inheritance C

Multi level Inheritance Hierarchical Inheritance

Hybri

dMember Access And Inheritance

Use public if the fields is to be visible everywhere.


Use protected if the field is visible everywhere in the current package and also subclasses
inother packages.
Use default if the field is to be visible everywhere in the current package only.
Use private protected if the field is to be visible only in subclasses, regardless of packages.
Defining a Subclass(Single Inheritance):
The general form of defining subclass as follows:
class SubClassName extends SuperClassName
{
variable declaration;
methods declaration;
}
The keyword extends signifies that the properties of the SuperClassName are extended to the
subClassName.
The Sub class will now contain its own variables and methods as well those of the superclass.
This kind of situation occurs when we want to add some more properties to an existing class without
actually modifying it.
Example:
import [Link].*; class Demo
class A
{
{
void displayA() public static void main(String arg[])
{
[Link]("super class Method"); {
}
} B obj = new B();
class B extends A
{ [Link]()
void displayB()
{ ;
[Link]("Sub class Method");
}} [Link]()

;
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

1. Single Inheritance: A class inherits from only one parent class.

Class Animal{
// ...
}

Class DogextendsAnimal{
// ...
}
2. Multiple Inheritance: A class inherits from multiple parent classes (not directly supported in Java but can
be achieved using interfaces).
3. Hierarchical Inheritance: Multiple child classes inherit from a single parent class.

classVehicle{
// ...
}

classCarextendsVehicle{
// ...
}

classBikeextendsVehicle{
// ...
}

4. Multilevel Inheritance: A class inherits from a child class of another class.

The use of derived class as a super class is known as multilevel inheritance


This concept allows us to build a chain of classes.

Grand Father Super Class

Father B Intermediate Super Class

C
Child Subclass

The 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. The chain ABC is known as inheritance path.

Example:

class A
{
void methodA()
{
[Link]("Method from A");
}
}
class B extends A
{
void methodB()
{
methodA();
[Link]("Method from B");
}
}
class C extends B
{
void methodC()
{
methodB();
[Link]("Method from C");
}
}
class MultiDemo
{
public static void main(String arg[])
{
C obj = new
C();
[Link]();
}
}
Output
: Method from A
Method from B
Method from C
Hierarchical Inheritance
One super class shared by number of subclasses, this approach is called hierarchical inheritance.
Many programming problems can be cast into a hierarchy where certain features of one level are
shared by many others below level.
A
Super Class

B C D
Sub Classes

Example:

import [Link].*;
class A
{
void base()
{
[Link]("Student Name=");
}
}
class B extends A class HiDemo
{
void methodB() {
{
base(); public static void main(String arg[])
[Link]("B");
}
{
}
class C extends A B obj = new B();
{
void methodC() [Link]();
{
base(); C obj1 = new C();
[Link]("C");
} [Link]();
}
class D extends A D obj2 = new D();
{
void methodD() [Link]();
{
base();
[Link]("D");
}
}

Hybrid Inheritance:

A combination of multiple inheritance and hierarchical inheritance.


The combination of more then one inheritance is called Hybrid inheritance.
Here we combined multilevel and hierarchical inheritance to achieve Hybrid inheritance.
Super Class
A

Intermediate Super Class

C D

Sub Classes

Example:

class A
{
class HyDemo
void base()
{
{
public static void main(String arg[])
[Link]("Student Name=");
{
}
C obj1 = new C();
}
[Link]();
class B extends A
[Link]();
{
D obj2 = new D();
void methodB()
[Link]();
{
[Link]();
base();
}
[Link]("B");
}
}
}
Output:
class C extends B
{
Student Name: B
void methodC()
Student Name: C
{
Student Name: B
base();
Student Name: D
[Link]("C");
}
}
class D extends B
{
void methodD()
{
base();
[Link]("D");
}

this and super Keywords

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.

The thisand superKeywords in Java

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
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.
classPerson{
String name;
publicPerson(String name){
[Link] = name; // `[Link]` refers to the instance variable
}
}
2. Calling Other Constructors: You can use this() to call another constructor of the same class.
classPerson{
String name;
int age;

publicPerson(String name){
this(name, 25); // Calls the constructor with two arguments
}

publicPerson(String name, int age){


[Link] = name;
[Link] = age;
}
}
3. Returning the Current Object: You can use this to return the current object itself, often used in method
chaining.
Java
classStringBuilder{
// ...
public StringBuilder append(String str){
// ...
returnthis; // Returns the current StringBuilder object
}
}
The super Keyword
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.
classChildextendsParent{
publicChild(){
super(); // Calls the default constructor of the Parent class
}
}

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.
classAnimal{
voidmakeSound(){
[Link]("Generic animal sound");
}
}

classDogextendsAnimal{
voidmakeSound(){
[Link](); // Calls the parent class's makeSound() method
[Link]("Woof!");
}
}

Key Benefits of Inheritance:

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.

Member Access Rules in Java Inheritance

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.

Member Access Rules in Inheritance

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.

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;
}

public double add(double a, double b) {


return a + b;
}

public int add(int a, int b, int c) {


return a + b + c;

}
}
In this example, we have three add methods with different parameter lists:
1. add(int, int): Adds two integers.
2. add(double, double): Adds two doubles.
3. add(int, int, int): Adds three integers.
How the Compiler Distinguishes:
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:
Calculator calculator = new Calculator();
int sum1 = [Link](5, 3); // Calls add(int, int)
double sum2 = [Link](2.5, 3.7); // Calls add(double, double)
int sum3 = [Link](1, 2, 3); // Calls add(int, int, int)
Key Points to Remember:
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
Method overriding is a feature in object-oriented programming where a subclass provides a specific
implementation of a method that is already defined in its parent class. This allows the subclass to customize the
behavior of the inherited method.
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() {
[Link]("Generic animal sound");
}
}

class Dog extends Animal {


@Override
public void makeSound() {
[Link]("Woof!");

}
}

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.
Key Benefits of Method Overriding:
Polymorphism: Allows objects of different types to be treated as objects of a common superclass.
Code Reusability: Inherits the common behavior from the parent class and overrides it to provide specific
implementations.
Flexibility: Enables customization of behavior based on the specific needs of subclasses.

There are three basic differences between the method overloading and method overriding.

Method Overloading Method Overriding

1) Method overloading is used to increase Method overriding is used to provide the specific
the readability of the program. implementation of the method that is already
provided by its super class.

2) Method overloading is performed within Method overriding occurs in two classes that have
a class. IS-A relationship.

3) In case of method overloading parameter In case of method overriding parameter must be


must be different. same.

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.
Key characteristics of abstract classes:
Cannot be instantiated: You cannot create objects of an abstract class directly.
Can contain abstract methods: These methods have no body and must be implemented by subclasses.
Can contain concrete methods: These methods have a body and can be directly inherited or overridden by
subclasses.
Example:
abstractclassShape{
abstractvoiddraw(); // Abstract method

publicvoiderase(){
[Link]("Erasing shape"); // Concrete method
}
}

classCircleextendsShape{
@Override
voiddraw(){
[Link]("Drawing a circle");
}
}

Dynamic Method Dispatch

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.

Key points about dynamic method dispatch:


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:

Shape shape = new Circle();


[Link](); // Calls the `draw()` method of the Circle class

The final Keyword

The final keyword in Java has multiple uses:

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:

finalclassImmutableClass{
privatefinalint x;

publicImmutableClass(int x){
this.x = x;
}

publicintgetX(){
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.
Key Purposes of Packages:
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 [Link];

publicclassMyClass{
// ...
}
In this example, [Link] is the package name. All classes defined within this file belong to this
package.
To use a class from another package, you need to import it:
import [Link];

publicclassMain{
publicstaticvoidmain(String[] args){
MyClass obj = new MyClass();
// ...
}
}
Common Java Packages:
[Link]: Contains fundamental classes like String, Integer, System, etc.
[Link]: Provides utility classes like Date, Calendar, Random, and collections framework classes.
[Link]: Offers classes for input/output operations like file handling and network programming.
[Link]: Contains classes for network programming, such as sockets and URLs.
[Link]: Provides classes for database connectivity and operations.
ACCESS PROTECTION IN JAVA:
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.
Here are the four access modifiers in Java:
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 [Link].package1;

public class ParentClass {


public int publicVariable;
protected int protectedVariable;
int defaultVariable;
private int privateVariable;

public void publicMethod()


{
// ...
}

protected void protectedMethod() {


// ...
}

void defaultMethod() {
// ...
}

private void privateMethod() {


// ...
}
}

package
[Link].package2;

public class ChildClass extends ParentClass {


public void accessMembers() {
publicVariable = 10; // Accessible
protectedVariable = 20; // Accessible
// defaultVariable = 30; // Not accessible
// privateVariable = 40; // Not accessible

publicMethod(); // Accessible
protectedMethod(); // Accessible
// defaultMethod(); // Not accessible
// privateMethod(); // Not accessible
}
}
IMPORTING PACKAGES:
In 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 [Link];

public class MyClass {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter
a number: ");
int number = [Link]();
[Link]("You entered: " + number);
}
}
In this example, we import the Scanner class from the [Link] package. This allows us to create a Scanner
object to read input from the user.
Importing All Classes from a Package:
You can also import all classes from a package using the * wildcard:
import [Link].*;

publicclassMyClass{
// ...
}
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 [Link];
import [Link];

public class MyClass {


public static void main(String[] args) {
List<String> names = new ArrayList<>();

// ...
}
}
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:
[Link] scanner = new [Link]([Link]);
INTERFACES (Multiple Inheritance) – Introduction

An interface can have methods and variables just like the class but the methods declared I interface are by
defaultabstract.
The variables declared in an interface are public, static and final by default.
DEFINING INTERFACES
The interface defines only abstract methods and final fields. This means that interfaces do not specify any code to
implement these methods and data fields contain only constants.
General form:
interface InterfaceName
{
Variable declaration;
Methods declaration;
}

Here interface is the keyword and InterfaceName is any valid java variable. Variables are declared as follows:
Static final type varname = value;
All variables are declared as constants. Method declaration will contain a list of methods without the body
statements.
Return-type method name (parameter-list)
Difference between Class and Interface:
Class Interface

The members of a class can be constant or The members of an interface are always declared as
variables. constant i.e. their values are final.

The class definition can contain the code for each The methods in an interface are abstract in nature, ie. there
of its methods. The methods can be abstract or is no code associated with them.
non-abstract.

It can be instantiated by declaring objects. It cannot be used to declare objects. It can only be inherited
by a class.

It can use various access specifiers like public, It can only use the public access specifier.
private or protected.

public static void main(String ar[])


Example:
{
interface printhe
inheri i = new inheri();
{
[Link]();
void print();
}
}
}
class interfa implements printhe
{
public void print( )
{ Output:
[Link]("Hello"); Hello
}

The method declaration simply ends with a semicolon.

EXTENDING INTERFACES
An interface can be sub interfaced from other interfaces. The new sub interface will inherit all the members of the
super interface in the manner similar to subclasses. This is achieved using the keyword extends as follows below:
Syntax:
interface name2 extends name1 interface strdisplay
{ {
body of name 2; int no=700;
} String name=”java”;
}
interface str extends strdisplay
{
void display( );
Example: }
interface A
{
void add();
void sub();
}
interface B extends A
{
void mul();
}
class extend implements B
{
public void add()
{
[Link]("Addition of 5 & 3 is : "+(5+3)); OUTPUT
}
public void sub()
{ Addition of 5 & 3 is : 8
[Link]("Subtraction of 5 & 3 is : "+(5-3)); Subtraction of 5 & 3 is :2
} Multiplication of 5 & 3 is : 15
public void mul()
{
[Link]("Multiplication of 5 & 3 is : "+(5*3));
}
public static void main(String ar[])
{
extend e=new extend();
[Link](); [Link](); [Link]();
} }
IMPLEMENTING INTERFACES
Implementing interfaces:
Interfaces are used as “super classes” whose properties are inherited by classes. It is therefore necessary to
create a class that inherits the given interface.
Syntax:
class classname implements Interfacename
{
Body of class name
}

Here, the class classname ‘implements’ the interface interfacename.


General form of implementation:
class classname extends superclass implements interface1, interface2
{
Body of class name
}

When a class implements more than one interface, they are separated by a comma.

Various forms of interface implementation:


A B

A A D

A
B B E C

C C B C
D

Example:
interface area // interface defined
{
final static float pi = 3.14f;
final compute(float x, float y);
}
class rectangle implements area // interface implemented
{
public float compute(float x, float y)
{
return (x*y);
}
}
class circle implements area // another implementation
{
public float compute (float x, float y)
{
return (pi * x * x ); } Output:
} Area of rectangle = 200
class interfacetest Area of circle = 314
{
public static void main (String args[])
{
rectangle rect = new rectangle( );
circle cir = new circle( );
area a;
a = rect;
[Link] ( “ Area of rectangle = ” + [Link] (10, 20));
a = cir;
[Link] ( “ Area of circle = ” + [Link] (10, 10));
}
}
ACCESSING INTERFACE VARIABLE
Interfaces can be used to declare a set of constants that can be used in different classes.
The constant values will be available to any class that implements the interface.
The values can be used in any method, as part of any variable declaration, or any where we can use a final
value.
Example:
class student void display( )
{ {
int rno; total = part1 + part2 + sports;
void get(int n) put();
{ putmark();
rno = n; putsp();
} [Link]("total : "+total);
void put() }
}
{
[Link]("Roll No.: " + rno); class final
} {
} public static void main(String arg[])
class test extends student {
{ result obj = new result();
float part1, part2; [Link](107);
void getmark(int m1, int m2) [Link](20,30);
{ [Link]();
part1 = m1; }
part2 = m2;
}
}
void putmark( )
{
[Link]("Part1: "+ part1);
[Link]("\Part2: "+ part2);
}
}
interface sport
{ Output:
float sports = 5.0;
void putsp(); Roll No. : 107
}
class result extends test implements sport Part1: 20
{
float total; Part2: 30
public void putsp( )
{ [Link]("Sports: "+ sports);
}

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

Exception handling is a mechanism in java to handle unwanted interruptions like exceptions and continue with
the normal flow of the program.
An exception is a condition that is caused by a run-time error in the program.
When the java interpreter encounters an error such as dividing an integer by zero, it creates an exception object
and throws it.
If the exception object is not caught and handled properly, the interpreter will display an error message and will
terminate the program.
The purpose of exception handling mechanism is to provide a means to detect and report an “exceptional
circumstance” so that appropriate action can be taken.
Error handling code that performs the following tasks…
Find the problem (Hit) Inform that an error has occurred (throw)
Receive the error information (catch) Take corrective actions (handle)
Error Handling and Exception Handling
Exception in java can be categorized into two types.
Checked exception
Unchecked exception
Checked exception: These exceptions are explicitly handled in the code itself with the help of try catch
blocks. Checked exceptions are extended from the [Link] class.
Unchecked exception: JVM handles such exceptions. Unchecked exceptions are extended from the
[Link] class.

• Exception Types And Hierarchy


EXCEPTION TYPE CAUSE OF EXCEPTION

ArithmeticException Caused by math errors such as division by zero

ArrayIndexOutOfBoundsException Caused by bad array indexed

ArrayStoreException Caused when a program tries to store the wrong type data in an array.

FileNotFoundException Caused by an attempt to access a nonexistent file

IOException Caused by general I/O failures, such as inability to read from a file.

NullPointerException Caused by referencing a null object

NumberFormatException Caused when a conversion between strings and number fails.

OutOfMemoryException Caused when there’s not enough memory to allocate a new object.

SecurityException Caused when an applet tries to perform an action not allowed by the
browser’s security settings.

StackOverflowException Caused when the system runs out of stack space.

StringIndexOutOfBoundsException Caused when a program attempts to access a nonexistent character


position in a string.

IllegalStateException Environment or state in incorrect state

SecurityException Attempt to violate security

TRY BLOCKS

Syntax of Exception Handling Code:

The basic concepts of exception handling are throwing an exception and catching it. The
following program shows this:
try block

Exception object creator


Statement that cause an
exception

Catch block

Statement that handles the Exception Exception handler

Fig: exception handling mechanism


Java uses a keyword try to preface a block of code that is likely to cause an error condition and “throw” an
exception.
A catch block defined by the keyword catch catches the exception thrown by the try block and handles it
appropriately.
The catch block is added immediately after the try block.
try
{
Statement; //generates an exception
}
catch (Exception-Type e)
{
Statement; // processes the exception
}
Example Program:
Ordinary program:
class Error
{
public static void main(String arg[])
{
int a=20,b=10,c=10;
int x,y;
x=a/(b-c);
y=a/(b+c);
}
}
Output:
Exception in thread main [Link]: / by zero
This program has exception, so remaining code does not work. Program end with that error statement.
THROWING AN EXCEPTION

Program with try/catch block:


class Error
{ { [Link](“Division by zero”); }
public static void main(String args[]) y=a/(b+c);
{ [Link](“y = “+y);
int a=20,b=10,c=10; }
int x,y; }
try Output:
{ x=a/(b-c); }
catch(ArithmeticException e) Division by Zero

Y=1

Here we are handle that exception with the help of try and catch block, so he next statement will be execute
properly.

CATCHING AN EXCEPTION

❖ It is possible to have more than one catch statements in the catch block.
try
{
statement; // generates an exception
}
catch (ExceptionType1 e)
{
statement; // process ExceptionType1
}

Rule:
At a time only one Exception is occurred and at a time only one catch back is executed.
All catch block must be ordered from most specified to most general, (ie) catch for ArithmeticException must
come before catch for Exception.
catch(ArithmeticException e)
Example Program: {
import [Link].*; [Link]("divided by 0:"+e);
class multicatch }
{ catch(ArrayIndexOutOfBoundsException e)
public static void main(String args[]) {
[Link]("array index oob:"+e);
{ }
try [Link]("after try/catch blocks.");
{ }
int a=[Link]; }
[Link]("a="+a); Output:
int b=42/a; a=0
int Divided by 0:[Link]:/by zero after
c[]={1}; try/catch blocks.
c[42]=99;
}

FINALLY STATEMENT
Java supports another statement known as finally statement that can be used to handle an exception that is not
caught by any of the previous catch statements.
Finally block can be used to handle any exception generated within a try block
The finally block will execute whether or not an exception is thrown.
It may be added immediately after the try block or after the last catch block.
When a finally block is defined, this is guaranteed to execute, regardless of whether or not an exception is
thrown.
Example Program:

class a
{
public static void main(String args[]) Output:
{
int a=10,b=20,c=20;
try Division by Zero
{
a=a/(b-c); Sample for Finally
}
catch(ArithmeticException e)
{
[Link]("Division by Zero");
}
finally
{
[Link]("Sample for finally"); }
}
}
Built-in Exceptions:

Java provides a rich set of built-in exceptions, categorized into different hierarchies. Some common exceptions
include:

• ArithmeticException: Occurs when an arithmetic operation fails, like division by zero.


• NullPointerException: Occurs when trying to access a member of an object that is null.
• ArrayIndexOutOfBoundsException: Occurs when trying to access an array element with an invalid
index.
• IOException: Occurs during input/output operations.
• ClassNotFoundException: Occurs when a class cannot be found.

Creating Custom Exception Classes:

You can create your own custom exception classes by extending the Exception class or one of its subclasses.

publicclassMyCustomExceptionextendsException{
publicMyCustomException(String message){
super(message);
}
}

Best Practices for Exception Handling:

• Catch Specific Exceptions: Catch specific exceptions to handle them appropriately.


• Avoid Empty Catch Blocks: Always provide meaningful error handling within catch blocks.
• Use finally Block for Cleanup: Ensure resources are released properly.
• Throw Exceptions Appropriately: Throw exceptions only when necessary.
• Provide Informative Error Messages: Include relevant details in exception messages.
• Test Exception Handling: Write unit tests to verify exception handling behavior.
UNIT III: Multithreaded Programming: Thread Class - Runnable interface – Synchronization–Using
synchronizedmethods– Using synchronized statement- InterthreadCommunication –Deadlock. I/O Streams:
Concepts of streams - Stream classes- Byte and Character stream - Reading console Input and Writing Console
output - File Handling.

MULTITHREADING
Introduction
• Multithreading is a conceptual programming paradigm where a program (process) is divided into 2 or more
subprograms(processes),which can be implemented at the same time in parallel.
Ex:
❖ One subprogram can display an animation on the screen while another may build the next animation to be displayed.
❖ This is something similar to dividing a task into subtasks and assigning them to different people for execution
independently and simultaneously.
Thread:
A thread is similar to a program that has a single flow of control. It has a beginning, a body, and an end, and executes
commands sequentially.
class abc
{
-- beginning
-- Single-threaded body of execution
-- End
}
❖ A unique property of java is its support for [Link] java enables us to use multiple flows of control in
developing programs.
❖ Each flow of control may be thought of as
a separate tiny program known as a thread
that runs in parallel.

❖ A program that contains multiple flows of control is known as multithreaded program.


Here, java program with four threads, one main and three others
❖ The main thread is actually the main method module, which is designed to create and starts the other three threads,
namely A, B, & C.
❖ Once initiated by the main thread, the threads A, B, and C run concurrently and share the resource jointly.
❖ The ability of a language to support multithreads is referred to as concurrently. Since threads in java are subprograms of a
main application program and share the same memory space, they are known as light-weight threads are light weight
processes.
Multithreading Multitasking
1. It is a programming concept in which a program or a It is an operating system concept in which multiple tasks
process is divided into 2 or more subprograms or are performed simultaneously.
threads that are executed at the same time in parallel.
2. It supports execution of multiple parts of a single It supports execution of multiple programs
program simultaneously. simultaneously.
3. The processor has to switch between different parts The processor has to switch software different programs
or threads of a program. or processes.
[Link] is highly efficient It is less efficient in comparison to multithreading
5.A thread is the smallest unit in multithreading A program or process is the smallest unit in a
multitasking environment.
6. It helps in developing efficient programs. It helps in developing efficient operating system.
7. It is lost-effective in case of context switching It is expensive in case of context switching
Creating Threads

Creating threads in java is simple.


Threads are implemented in the form of objects that contain a method called run ( ).
It makes up the entire body of a thread and is the only method in which the thread‘s behavior can be implemented.
Syntax:

public void run ( )


{
-- (statements for implementing thread)
--
--
}
❖ The run ( ) method should be invoked by an object of the concerned thread.
❖ This can be achieved by creating the thread and initiating it with the help of another thread method called start ( ).
A new thread can be created in 2 ways:

1. By creating a thread class:

❖ Define a class that extends thread class and override its run ( ) method with the code required by the thread.
2. By converting a class to a thread:

❖ Define a class that implements Runnable interface.


❖ The Runnable interface has only one method, run ( ), that is to be defined in the method with the code to be executed by
the thread.

Thread Class in Java

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:

1. Extending the Thread class:


o Create a new class that extends the Thread class.
o Override the run() method to define the thread's behavior.

classMyThreadextendsThread{
publicvoidrun(){
// Thread's execution code
}
}

2. Implementing the Runnable interface:


o Create a new class that implements the Runnable interface.
o Implement the run() method to define the thread's behavior.
o Pass an instance of this class to a Thread object.

classMyRunnableimplementsRunnable{
publicvoidrun(){
// Thread's execution code
}
}

Thread t = new Thread(new MyRunnable());

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.
MyThread t = new MyThread();
[Link]();

Thread Lifecycle:

A thread goes through the following states:

1. New: The thread is created but not yet started.


2. Runnable: The thread is ready to run but waiting for CPU time.
3. Running: The thread is currently executing.
4. Blocked: The thread is waiting for a resource or event.
5. Terminated: The thread has finished execution.

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:

• wait() and notify(): Used to pause and resume threads.


• join(): Waits for a thread to finish execution.

THREAD
METHODS

Thread class methods can be used to control the behavior of a thread. They are:-
o start()
o run()
o yield()
o sleep()
o stop()
DEFINING AND RUNNING THREAD
To make our class runnable as thread by extending the class [Link].
It includes the following steps:
✓ Declare the class as extending the Thread class.
✓ Implement the run ( ) method that is responsible for executing the sequence of code that the thread
will execute.
✓ Create a thread object and call the start ( ) method to initiate the thread execution.
Declaring the class:
The thread class can be extended as follows:
class Mythread extends Thread
{
---
---
}
Now we have a new type of thread Mythread.
Implementing the run ( ) method:
The run ( ) method has been inherited by the class Mythread.
To override this method in order to implement the code to be executed by our thread.
public void run ( )
{
---
--- //thread code here
--- }
When start the new thread, java calls the thread’s run ( ) method, so it is the run ( ) where all the action takes
place.
Starting new thread:
To actually create and run an instance of our thread class, we must write the following:
Syntax: Mythread obj = new Mythread( );
[Link]( ); //invoke run( ) method
❖ The first line instantiate a new object of class Mythread.
❖ The second line calls the start ( ) method causing the thread to more into the runnable state.
❖ Then the java runtime will schedule the thread to run by invoking its run ( ) method. This is called as the
running state.
Example program: class Threaddemo
class Mythread extends Thread {
{ public static void main(String args[])
public void run() {
{ Mythread mt=new Mythread();
for(int i=0;i<10;i++) [Link]();
{
}
[Link]("\t"+i);
} }
} Output
} 0 1 2 3456789
Stopping a Thread:
Whenever we want to stop a thread from running, we may calling a stop() method by the following code
[Link]();
This statement causes the thread to move to the dead state. A thread will also move to the dead state
automatically when it reaches the end of its method. The stop () method may be used when the premature death
of a thread is desired.
Blocking a Thread:
A thread can also be temporarily suspended or blocked from entering into the runnable and subsequently running
state by using either of the following thread methods:
sleep() Blocked for a specified time
suspend () Blocked until further orders
wait() Blocked until certain condition occurs
The thread will return to the runnable state when the specified time is elapsed in the case of sleep(), the
resume() method is invoked in the case of suspend(), and the notify() method is called in the case of wait().

Runnable Interface

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.

IMPLEMENTING THE RUNNABLE INTERFACE


The thread can be created by implementing the runnable interface.
The Runnable interface declares the run() method that is required for implementing threads in our programs. To
do this, we must perform the steps listed below:
✓ Declare the class as implementing the Runnable interface.
✓ Implement the run() method.
✓ Create a thread by defining an object that is instantiated from this "runnable" class as the target of
the thread.
✓ Call the thread's start() method to run the thread.
Example:
class x implements Runnable
{
public void run( )
{
for (int i=1; i<=10; i++)
{
[Link] (“Thread X:”+ i);
}
}}
class RunnableTest
{
public static void main (String [] args)
{
x runnable = new x();
Thread threadX = new Thread(runnable);
[Link]( );
[Link] ("End of main thread");
}}
Implementing the Runnable Interface:
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.
2. Implement the run() method:
o Override the run() method to specify the actions the thread should perform.
3. Create a Thread object:
o Instantiate a Thread object and pass an instance of the class that implements Runnable to its
constructor.
4. Start the thread:
o Call the start() method on the Thread object to initiate execution.
Advantages of using Runnable interface:
• 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.
Key Points to Remember:
• The run() method is the entry point for a thread.
• Multiple threads can share the same Runnable object.
• The start() method initiates the thread's execution.
• The Thread class provides various methods for controlling thread execution, such as join(), sleep(), and
interrupt().
• Synchronization is essential for handling shared resources and preventing race conditions.
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 [Link] 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.
publicsynchronizedvoidsynchronizedMethod(){
// Critical section of code

}
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.
publicvoidsomeMethod(){
synchronized(object) {
// Critical section of code
}
}
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:
• wait() and notify():
o Used to pause and resume threads.
o wait() releases the lock and waits for a notification.
o notify() wakes up a waiting thread.
• join():
o Waits for a thread to finish execution.

Using Synchronized Methods


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.
When to Use Synchronized Methods:
• 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.
Considerations and Best Practices:
• 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 [Link] for
more complex synchronization scenarios.
Using Synchronized Statements
Synchronized statements provide a more granular approach to synchronization than synchronized
methods. They allow you to specify a specific block of code within a method that needs to be synchronized, rather
than synchronizing the entire method.
Syntax:
synchronized (object) {
// Critical section of code
}
Advantages of Synchronized Statements:
• 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:
• Deadlocks: Be careful to avoid deadlocks, especially when using multiple locks.
• Performance Impact: Excessive synchronization can degrade performance.
• Alternative Approaches: Consider using higher-level concurrency utilities like [Link] for
more complex synchronization scenarios.

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:
1. wait() and notify():
o wait(): Pauses the current thread and releases the lock on the object.
o notify(): Wakes up a single waiting thread.
o notifyAll(): Wakes up all waiting threads.

publicclassProducerConsumer{
privateint value;
privateboolean produced = false;

publicsynchronizedvoidproduce(){
while (produced) {
try {
wait();
} catch (InterruptedException e) {
// Handle exception
}
}
// Produce value
produced = true;
notify();
}

publicsynchronizedvoidconsume(){
while (!produced) {
try {
wait();
} catch (InterruptedException e) {
// Handle exception
}
}
// Consume value
produced = false;
notify();
}
}
2. join():
o Waits for a thread to finish execution before proceeding.
Thread t = new Thread(new MyRunnable());
[Link]();
[Link](); // Waits for t to finish
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:
• Synchronization: Always use synchronization mechanisms to protect shared resources and prevent race
conditions.
• Deadlocks: Be careful to avoid deadlocks by acquiring locks in a specific order and using timeouts.
• Liveness: Ensure that threads can make progress and avoid starvation.
• Performance: Excessive synchronization can impact performance, so use it judiciously
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:
1. Mutual Exclusion: Multiple threads need to access shared resources exclusively.
2. Hold and Wait: A thread holds a resource and waits for another resource.
3. No Preemption: Resources cannot be forcibly taken away from a thread.
4. Circular Wait: A circular chain of threads exists, where each thread is waiting for a resource held by the
next thread in the chain.
Preventing Deadlocks:
1. Careful Resource Allocation:
o Acquire locks in a specific order to avoid circular wait.
o Release locks as soon as possible.
2. Timeout Mechanisms:
o Set timeouts for acquiring locks to prevent indefinite waiting.
o If a lock cannot be acquired within the timeout, the thread can release other held locks and retry.
3. Deadlock Detection and Recovery:
o Monitor the system for deadlock conditions.
o Use algorithms to detect and break deadlocks by preempting resources or terminating threads.
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:
• Deal with raw bytes.
• Used for binary data like images, audio, and executable files.
Common Classes:
InputStream: Abstract class for reading byte streams.
OutputStream: Abstract class for writing byte streams.
FileInputStream: Reads bytes from a file.
FileOutputStream: Writes bytes to a file.
BufferedInputStream: Reads bytes from a buffer.
BufferedOutputStream: Writes bytes to a buffer.
2. Character Streams:
• Deal with characters.
• Used for text-based data like plain text files, HTML, and XML.
Common Classes:
• Reader: Abstract class for reading character streams.
• Writer: Abstract class for writing character streams.
• FileReader: Reads characters from a file.
• FileWriter: Writes characters to a file.
• BufferedReader: Reads characters from a buffer.
• BufferedWriter: Writes characters to a buffer.
• InputStreamReader: Converts byte streams to character streams.
• OutputStreamWriter: Converts character streams to byte streams.
Reading Console Input:
import [Link];
import [Link];
import [Link];

public class ConsoleInput {


public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader([Link]));

[Link]("Enter your name: ");


String name = [Link]();
[Link]("Hello,
" + name + "!");
}
}
Writing Console Output:
[Link]("Hello, World!");
[Link]("This is a line of text.");

File Handling:
import [Link];
import [Link];
import [Link];
public class FileHandling {
public static void main(String[] args) throws IOException {
File
file = new File("[Link]");
FileWriter writer = new FileWriter(file);
[Link]("This is a line of text.");
[Link]();
}

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.
Example: Reading and Writing to a File
import [Link].*;

public class FileIOExample {


public static void main(String[] args) throws IOException {
// Write to a file
FileWriter writer = new FileWriter("[Link]");
[Link]("Hello, world!");
[Link]();

// Read from a file


FileReader reader = new FileReader("[Link]");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = [Link]()) != null) {
[Link](line);

}
[Link]();

[Link]();
}
}
Stream Classes in Java
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
Byte streams are used to handle raw binary data.
Key Classes:
• InputStream: Abstract class for reading byte streams.
o FileInputStream: Reads bytes from a file.
o BufferedInputStream: Reads bytes from a buffer for efficient reading.
o ByteArrayInputStream: Reads bytes from a byte array.
o PipedInputStream: Reads bytes from a pipe.
• OutputStream: Abstract class for writing byte streams.
o FileOutputStream: Writes bytes to a file.
o BufferedOutputStream: Writes bytes to a buffer for efficient writing.
o ByteArrayOutputStream: Writes bytes to a byte array.
o PipedOutputStream: Writes bytes to a pipe.
Character Streams
Character streams are used to handle textual data.
Key Classes:
• Reader: Abstract class for reading character streams.
o FileReader: Reads characters from a file.
o BufferedReader: Reads characters from a buffer for efficient reading.
o StringReader: Reads characters from a string.
o PipedReader: Reads characters from a pipe.
• Writer: Abstract class for writing character streams.
o FileWriter: Writes characters to a file.
o BufferedWriter: Writes characters to a buffer for efficient writing.
o StringWriter: Writes characters to a string.
o PipedWriter: Writes characters to a pipe.
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.
Example: Reading and Writing to a File
import [Link].*;

publicclassFileIOExample{
publicstaticvoidmain(String[] args)throws IOException {
// Write to a file
FileWriter writer = new FileWriter("[Link]");
[Link]("Hello, world!");
[Link]();

// Read from a file


FileReader reader = new FileReader("[Link]");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = [Link]()) != null) {
[Link](line);

}
[Link]();

[Link]();
}
}

Byte and Character Streams


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:
• InputStream: Abstract class for reading byte streams.
o FileInputStream: Reads bytes from a file.
o BufferedInputStream: Reads bytes from a buffer for efficient reading.
o ByteArrayInputStream: Reads bytes from a byte array.
o PipedInputStream: Reads bytes from a pipe.
• OutputStream: Abstract class for writing byte streams.
o FileOutputStream: Writes bytes to a file.
o BufferedOutputStream: Writes bytes to a buffer for efficient writing.
o ByteArrayOutputStream: Writes bytes to a byte array.
o PipedOutputStream: Writes bytes to a pipe.
Character Streams
Character streams deal with text data. They are suitable for handling text files, HTML, and other text-based formats.
Key classes:
• Reader: Abstract class for reading character streams.
o FileReader: Reads characters from a file.
o BufferedReader: Reads characters from a buffer for efficient reading.
o StringReader: Reads characters from a string.
o PipedReader: Reads characters from a pipe.
• Writer: Abstract class for writing character streams.
o FileWriter: Writes characters to a file.
o BufferedWriter: Writes characters to a buffer for efficient writing.
o StringWriter: Writes characters to a string.
o PipedWriter: Writes characters to a pipe.

Key Differences:
Feature Byte Stream Character Stream
Data
Byte Character
Unit
Usage Binary data Textual data

InputStream,
Classes Reader, Writer
OutputStream

Example: Reading and Writing Text to a File


import [Link].*;

publicclassFileIOExample{
publicstaticvoidmain(String[] args)throws IOException {
// Write to a file
FileWriter writer = new FileWriter("[Link]");
[Link]("Hello, world!");
[Link]();

// Read from a file


FileReader reader = new FileReader("[Link]");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = [Link]()) != null) {
[Link](line);

}
[Link]();

[Link]();
}
}
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.

Reading Console Input


Using Scanner class:
import [Link];

public class ReadConsoleInput {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

[Link]("Enter your name: ");


String name = [Link]();

[Link]("Hello, " + name


+ "!");
}
}
Explanation:
1. Import Scanner: Import the Scanner class from the [Link] package.
2. Create a Scanner object: Create a Scanner object to read input from the standard input stream
([Link]).
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.
Using BufferedReader:
import [Link];
import [Link];
import [Link];

public class
ReadConsoleInput {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader([Link]));

[Link]("Enter your name: ");


String name = [Link]();

[Link]("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.
Writing Console Output:
Using [Link]():
publicclassWriteConsoleOutput{
publicstaticvoidmain(String[] args){
[Link]("Hello, World!");
[Link]("This is a new line.");
}
}
Explanation:
• [Link]() prints the specified text to the console and adds a newline character.
Using [Link]():
publicclassWriteConsoleOutput{
publicstaticvoidmain(String[] args){
[Link]("Hello, ");
[Link]("World!");
}
}
• [Link]() prints the specified text to the console without adding a newline character.
File Handling in Java
Why File Handling is Required?
• File Handling is an integral part of any programming language as file handling enables us to store the output of
any particular program in a file and allows us to perform certain operations on it.
• In simple words, file handling means reading and writing data to a file.
Java File Class Methods
Return
Method Name Description Type
Return
Method Name Description Type

It tests whether the file is


canRead() Boolean
readable or not.

It tests whether the file is writable


canWrite() Boolean
or not.

createNewFile() It creates an empty file. Boolean

delete() It deletes a file. Boolean

It tests whether the file exists or


exists() Boolean
not.

Returns the size of the file in


length() Long
bytes.

getName() Returns the name of the file. String

Returns an array of the files in the


list() String[]
directory.

mkdir() Creates a new directory. Boolean

File operations in Java


File operations in Java
The following are the several operations that can be performed on a file in Java :
• Create a File
• Read from a File
• Write to a File
• Delete a File
Now let us study each of the above operations in detail.
1. Create a File
• In order to create a file in Java, you can use the createNewFile() method.
• If the file is successfully created, it will return a Boolean value true and false if the file already exists.
2. Read from a File: We will use the Scanner class in order to read contents from a file.
3. Write to a File: We use the FileWriter class along with its write() method in order to write some text to the
file.
4. Delete a File: We use the delete() method in order to delete a file.
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

AWT Class Hierarchy:

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.

Here's a simplified view of the AWT class hierarchy:

[Link]
|- [Link]
|- [Link]
|- [Link]
|- [Link]
|- [Link]
|- [Link]

Key Components and Their Roles:

1. Component:
o The base class for all AWT components.
o Defines common properties like size, location, visibility, and event handling.
2. Container:
o A component that can hold other components.
o Used to organize and group UI elements.
o Examples: Panel, Window, Frame, and Dialog.
3. Panel:
o A lightweight container used to group components.
o Often used to create custom layouts and organize complex UI elements.
4. Window:
o A top-level container with a title bar and borders.
o Can be either a frame or a dialog.
5. Frame:
o A standalone window with a title bar, menu bar, and borders.
o Used to create independent applications.
6. Dialog:
o A modal or modeless window that depends on a parent frame.
o Used for displaying messages, asking for user input, or providing additional information.

Additional Components:

• Button: A clickable button to trigger actions.


• Label: A display area for text or images.
• TextField: A single-line text input field.
• TextArea: A multi-line text input area.
• Checkbox: A toggle button to select or deselect an option.
• CheckboxGroup: A group of checkboxes where only one can be selected at a time.
• Choice: A drop-down list of options.
• List: A scrollable list of items.
• Menu: A hierarchical menu structure.
• MenuItem: An individual item in a menu.
• PopupMenu: A context menu that appears when the user right-clicks.
• Scrollbar: A control for scrolling through content.

User Interface Components:

Java provides a rich set of tools and libraries for creating user interfaces. Two primary toolkits are commonly used:

1. AWT (Abstract Window Toolkit):

• 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.
o PopupMenu: Displays a context menu on right-click.
o Panel: Organizes and groups components.
o Frame: Creates a top-level window.
o Dialog: 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.

Choosing the Right Toolkit:

• AWT: Simpler and lightweight, but less flexible and platform-dependent.


• Swing: More powerful, flexible, and platform-independent, but more complex.

Key Considerations:

• Layout Managers: Use them to organize components effectively within a container.


• Event Handling: Implement event listeners to respond to user actions.
• User Experience: Design intuitive and visually appealing interfaces.
• Accessibility: Ensure your UI is accessible to users with disabilities.
• Testing: Thoroughly test your UI to identify and fix issues.

Labels

• A Label displays the string it contains.


• Labels are passive controls that do not support any interaction with the user.
• The three forms of constructors are:

Label( ) ; It creates an empty label

Label(String s) ; It creates a label with specified text

Label(String s, int alignment) ; It creates a label with the specified alignment

• The alignment values are: [Link], [Link] and [Link].


• The four methods are:
setText(String s); It is used to set the text to the specified string.

getText( ); It is used to get the text from the label.

setAlignment(int alignment); It is used to set the alignment of the string within the label.

getAlignment( ) It is used to get the alignment from the label.

Push Button or Button

• A Button is a component that has a label and can respond when pressed.
• The two forms of constructors are:
Button( ) ; It constructs a button with no label
Button(String s) ; It constructs a button with specified label

• The two methods are:


setLabel(String s) ; It is used to set the label to the specified string

getLabel( ) ; It is used to get the label from the button

➢ Each time a button is pressed, an action event is generated.


➢ Button must be created using the new keyword.
➢ Button must be added to the containers before they can be used,
➢ This can be done by using the keyword add.
Text Component
TextField Class:
• A Text Field is the subclass of Text component.
• It is used to accept a line of text data from the user.
• The four forms of constructors are:
TextField( ) ; It creates an empty text field
TextField(int numchars) It creates a text field with numchars characters
TextField(String s) ; It creates a text field with the initial text content
TextField(String s, int numchars) It creates a text field and sets its width.
• The two methods are:
setText(String s) ; It is used to set the specified string to the TextField
getText( ) ; It is used to get the text from the TextField

Example:
import [Link].*;
import [Link].*;
import [Link].*;
public class textfield extends Applet implements ActionListener
{
Button b;
Label p;
public void init()
{
setLayout(new GridLayout(3,2));
Label l1=new Label("Enter user name",[Link]);
add(l1);
TextField t1=new TextField(10);
add(t1);
Label l2=new Label("Enter password",[Link]);
add(l2);
TextField t2=new TextField(10);
add(t2);
[Link]('*');
p=new Label("Hello",[Link]);
[Link]([Link]);
add(p);
b=new Button("CLICK ME");
add(b);
[Link](this);
}
public void actionPerformed(ActionEvent e)
{
[Link]("Button is clicked");
}
}
/* <applet code=[Link] height=100 width=100></applet> */
Checkbox

• The Checkbox class is used to create a labeled check box.


• It has two parts:
1. Caption – It is the text that represents the label of the control.
2. State – It is the Boolean value (true/false).
• By default, the state is false which means the check box is unchecked.
• The four forms of constructors are:
Checkbox( ) It creates a checkbox whose label is blank.

Checkbox(String s) ; It creates an unchecked checkbox

Checkbox(String s, boolean state) ; It creates a checkbox depending on the specified state

Checkbox(String s, boolean state, It creates a checkbox whose label is specified by s and whose
CheckboxGroup cbgroup) group is specified by cbgroup

• The four methods are:


getState( ) ; It is used to get the current state of the Checkbox

setState(boolean state) ; It is used to set the state of the Checkbox

getLabel( ) We obtain the current label associated with the checkbox

setLabel(String str) It is used to set the label.

Example:

import [Link].*;
import [Link].*;
import [Link].*;
public class checkbox extends Applet implements ItemListener
{
String msg=" ";
Checkbox win200,linux,unix;
public void init()
{
win200=new Checkbox("windows2000",null,true);
linux=new Checkbox("Linux");
unix=new Checkbox("unix");
add(win200);
add(linux);
public void paint(Graphics g)
add(unix);
{
[Link]( this);
[Link](th is);msg="current stat";
[Link](thi s);[Link](msg,6,80);
msg="windows 2000"+[Link]();
}
[Link](msg,6,100);
public void itemStateC hanged(ItemEvent e)
{ msg="linus"+[Link]();
repaint(); [Link](msg,6,120);
} msg="unix"+[Link]();
[Link](msg,6,140);
}}
/* <applet code=[Link] height=100
width=100></applet> */
Choice

• A Choice is a pull-down list.


• It is also called as combo box.
• It is used to display a list of choices and a list item is selected by mouse click on the choice control.
• It defines only default constructor.
• The seven methods are:
add(String name) To add an item to the list

getSelectedItem( ) It returns a string containing the name of the item

It returns the index of the item. The first item is at index


getSelectedIndex( )
0;

getItemCount( ) ; It is used to get the number of items in the choice menu

select(int position) ; It is used to select the item at the given position

select(String name) It is used to select the item

getItem(int index) ; It is used to get the text of a given index

Scrollbars

• Scrollbars are used to select continuous values between a specified minimum and maximum.
• It may be oriented horizontally and vertically.
• The three forms of constructors are:
Scrollbar( ); It creates a vertical scroll bar

Creates a scrollbar with 0,0 as its initial maximum and initial


Scrollbar(int style);
minimum values.

Scrollbar(int style, int initial-value, int thumb-size, int min, int max)

1. First argument-> orientation of scroll bar: [Link] and [Link].


2. Second arg-> initial value of scroll bar.
3. Third argument-> specifies overall width ( or height depending on the orientation of the scroll bar).
4. 4 th and 5th argument-> minimum and maximum values for the scrollbar.

• The six methods are:


getValue( ) ; It is used to get the current value of the scroll bar

setValue(int new-value) ; It is used to set the value for the scroll bar
getMinimum( ); It is used to get the minimum value of the scroll bar

getMaximum( ); It is used to get the maximum value of the scroll bar

setUnitIncrement(int n) ; It is used to set the increment value

setBlockIncrement(int n); It is used to change the page-up and page-down value

JList with examples


Constructor for JList are :

1. JList(): creates an empty blank list


2. JList(E [ ] l) : creates an new list with the elements of the array.
3. JList(ListModel d): creates a new list with the specified List Model
4. JList(Vector l) : creates a new list with the elements of the vector
method explanation

getSelectedIndex() returns the index of selected item of the list

returns the selected value of the element ofthe


getSelectedValue()
list

setSelectedIndex(int i) sets the selected index of the list to i

setSelectionBackground(Color c) sets the background Color of the list

setSelectionForeground(Color c) Changes the foreground color of the list

Changes the elements of the list to the


setListData(E [ ] l)
elements of l .

setVisibleRowCount(int v) Changes the visibleRowCount property

setSelectedValue(Object a, boolean s) selects the specified object from the list.

changes the selection to be the set of


setSelectedIndices(int[] i)
indices specified by the given array.

constructs a read-only ListModel from a


setListData(Vector l)
Vector specified.

setLayoutOrientation(int l) defines the orientation of the list


method explanation

Changes the cell width of list to the value


setFixedCellWidth(int w) passed as parameter.

Changes the cell height of the list to the


setFixedCellHeight(int h)
value passed as parameter.

returns true if the specified index is


isSelectedIndex(int i)
selected, else false.

returns the origin of the specified item in the


indexToLocation(int i)
list’s coordinate system.

returns the tooltip text to be used for the


getToolTipText(MouseEvent e)
given event.

getSelectedValuesList() returns a list of all the selected items.

returns an array of all of the selected


getSelectedIndices()
indices, in increasing order

returns the smallest selected cell index, or -1 if


getMinSelectionIndex()
the selection is empty.

returns the largest selected cell index, or -1if the


getMaxSelectionIndex()
selection is empty.

getListSelectionListeners() returns the listeners of list

returns the largest list index that is currently


getLastVisibleIndex()
visible.

returns whether or not automatic drag


getDragEnabled()
handling is enable

addListSelectionListener(ListSelectionListener l)
adds a listSelectionlistener to the list

Menu
• Java provides two types of menus:
1. Pull-down menu
2. Pop-up menu
• Pull down menus are accessed via a menu bar.
• Pop-up menus are displayed when user clicks the right mouse button.

• Java provides the following classes for menu creating:


1. MenuBar
2. Menu
3. MenuItem
➢ MenuBar contains one or more Menu Objects.
➢ Each Menu contains a list of MenuItem.
➢ Each MenuItem represents something that can be selected by the user.
➢ CheckboxMenuItem have a check mark next to them when they are selected.

1. MenuBar:
This class only defines the default constructor: MenuBar( );
2. Menu:
Menu( );
Menu(String optname);
Menu(Strig optname, boolean removable);

➢ Here, optname specifies the name of the menu selection.


If removable is true, the pop-up menu can be removed. Otherwise, it will remain attached to the
menu bar.
3. MenuItem:
MenuItem( )
MenuItem( String item_name)
MenuItem( String item_name, MenuShortcut keyacc)

➢ Here, item_name is the name shown in the menu.


keyacc is the menu shortcut for the item.
Methods are:

setEnabled(Boolean flag) We can disable or enable a menu item.

isEnabled( ) We can determine as item’s status.

setLabel( ) We can change the name of the menu item.

getLabel( ) We can retrieve the current name.

Steps for creating menus:


1. Creating an object of the menu bar. This class only defines the default constructor.
MenuBar mb=new MenuBar( );
2. Call the window’s setMenuBar() method to give the menu bar to the window.
setMenuBar(mb);
3. create objects of the menu class for each menu the user wants in the menu bar
Menu m=new Menu(“color”);
4. Call the menubar object’s add() method to add each menuobject to the manu bar.
[Link](m);
5. Create objects of the menuItem class for each item the user wants to appear in the menus.
MenuItem a=new MenuItem(“red’);
6. Call the menu’s add{} methods in order to add each item to its appropriate menu.
[Link](a);

Frame, Color, Fonts, and Layout Managers:

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:

• FlowLayout: Arranges components in a row or column.


• 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.

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

Example: A Button Click Event


import [Link].*;
import [Link].*;

public class ButtonClickExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Button Click Example");
JButton button = new JButton("Click Me");

[Link](new ActionListener() {
public void actionPerformed(ActionEvent
e) {
[Link]("Button clicked!");
}
});

[Link](button);
[Link](300, 200);
[Link](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.
Common Event Listener Interfaces:
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.

Event Delegation Model (EDM)


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.
Handling Mouse and Keyboard Events :
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.

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 [Link].*;

publicclassMouseClickAdapterextendsMouseAdapter{
@Override
publicvoidmouseClicked(MouseEvent e){
[Link]("Mouse clicked at: " + [Link]() + ", " + [Link]());
}
}
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.
Benefits of Using Adapter Classes:
• 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.
Java supports four types of inner classes:
1. Static Nested Classes:
o Declared with the static keyword.
o Can access static members of the outer class but not instance members.
o Can be instantiated without creating an instance of the outer class.
2. Instance Inner Classes:
o Declared without the static keyword.
o Can access both static and instance members of the outer class.
o Can be instantiated only after creating an instance of the outer class.
3. Local Inner Classes:
o Declared within a method or block of code.
o Can access local variables of the enclosing method or block.
o Can only be instantiated within the enclosing method or block.
4. Anonymous Inner Classes:
o A special type of inner class that is declared and instantiated in a single statement.
o Often used to create event listeners or implement interfaces concisely.
Example:
public class OuterClass {
private int outerVariable = 10;

public class InnerClass {


public void innerMethod() {
[Link]("Inner class method: " + outerVariable);
}
}

public void outerMethod() {


InnerClass innerObject = new InnerClass();
[Link]();
}
}
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.

Swing: A Powerful GUI Toolkit:

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.

Key Features of Swing:

• Platform Independence: Swing components can be rendered consistently across different operating
systems.
• Customizability: You can customize the appearance and behavior of Swing components using various
properties and methods.
• Pluggable Look and Feel: Swing supports different look and feels, allowing you to mimic the appearance
of native platforms or create custom looks.
• Model-View-Controller (MVC) Architecture: Swing components follow the MVC pattern, separating
concerns and promoting modularity.
• Event Handling: Swing provides a robust event handling mechanism to respond to user interactions.

Core Swing Components:

• 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.

Example: A Simple Swing Application

import [Link].*;

publicclassSwingExample{
publicstaticvoidmain(String[] args){
JFrame frame = new JFrame("My Swing Application");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](300, 200);
JLabel label = new JLabel("Hello, Swing!");
JButton button = new JButton("Click me");

[Link](label);
[Link](button);

[Link](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.

Key Advantages of Swing:

• Flexibility: Swing offers a wide range of components and customization options.


• Performance: Swing components are lightweight and efficient.
• Cross-Platform Compatibility: Swing applications can run on different operating systems with a
consistent look and feel.

Hierarchy of swing components:

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.

Key Components and Their Hierarchy:

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.

JFrame: The Main Window

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:

• Title Bar: Displays the window's title.


• Menu Bar: Can hold menus and menu items.
• Border: Defines the window's boundary.
• Resizable: Can be resized by the user.
• Closable: Can be closed by the user.
• Iconifiable: Can be minimized to the taskbar.

Creating a JFrame:

import [Link].*;

publicclassJFrameExample{
publicstaticvoidmain(String[] args){
JFrame frame = new JFrame("My First JFrame");
[Link](JFrame.EXIT_ON_CLOSE); // Set the default close operation
[Link](300, 200); // Set the size of the frame
[Link](true); // Make the frame visible
}
}

Key Methods:
• setDefaultCloseOperation(int operation): Sets the default close operation.
• setSize(int width, int height): Sets the size of the frame.
• setVisible(boolean visible): Makes the frame visible or invisible.
• setTitle(String title): Sets the title of the frame.
• add(Component component): Adds a component to the frame.
• pack(): Automatically sizes the frame to fit its contents.

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.

Example with BorderLayout:

JFrame frame = new JFrame("BorderLayout Example");


[Link](JFrame.EXIT_ON_CLOSE);
[Link](new BorderLayout());

JLabel northLabel = new JLabel("North");


JButton eastButton = new JButton("East");
JButton westButton = new JButton("West");
JTextArea centerArea = new JTextArea("Center");
JButton southButton = new JButton("South");

[Link](northLabel, [Link]);
[Link](eastButton, [Link]);
[Link](westButton, [Link]);
[Link](centerArea, [Link]);
[Link](southButton, [Link]);

[Link](300, 200);
[Link](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:

• Lightweight: Doesn't require heavyweight components like AWT components.


• Customizable: Can be customized to have any shape or transparency.
• Modal and Modeless: Can be modal (blocks interaction with other windows) or modeless.

Common Use Cases:

• Tooltips: Small pop-up windows that display information about a component.


• Custom Dialogs: Creating custom dialogs with unique appearances.
• Splash Screens: Displaying a welcome screen while the application loads.

Example:

import [Link].*;
import [Link].*;

publicclassJWindowExample{
publicstaticvoidmain(String[] args){
JWindow window = new JWindow();
[Link](200, 100);
[Link](null); // Center the window on the screen

JLabel label = new JLabel("Hello, World!");


[Link](label);

[Link](true);
}
}

Key Points to Remember:

• 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.

JDialog: A Modal or Modeless Dialog Box

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.

Common Use Cases:

• Message Dialogs: Displaying simple messages to the user.


• Input Dialogs: Prompting the user for input.
• File Chooser Dialogs: Allowing the user to select files.
• Color Chooser Dialogs: Allowing the user to select colors.
Example:

import [Link].*;
import [Link].*;

publicclassJDialogExample{
public static void main(String[] args) {
JFrame frame = new JFrame("Main Frame");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](300, 200);
[Link](true);

// Create a modal dialog


JDialog dialog = new JDialog(frame, "Modal Dialog", true);
[Link](200, 100);
[Link](new FlowLayout());
[Link](new JLabel("This is a modal dialog."));
[Link](true);
}
}

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:

• JDialog is often used to create custom dialogs for specific purposes.


• You can customize the appearance and behavior of a JDialog using various properties and methods.
• Modal dialogs are useful for ensuring user input before proceeding with other actions.
• Modeless dialogs can be used for additional information or options that don't require immediate user
attention.

JPanel: A Versatile Container

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:

• Lightweight: Doesn't require heavyweight components like AWT components.


• Customizable: Can be customized with various layouts, borders, and background colors.
• Flexible: Can be used to create complex layouts and group related components.

Common Use Cases:

• Grouping Components: Organizing related components into logical groups.


• Creating Custom Panels: Building reusable custom panels with specific layouts and components.
• Adding Scrolling: Using JScrollPane to create scrollable panels for large content.
• Card Layout: Implementing card-based layouts to switch between different views.

Example:
Java
import [Link].*;
import [Link].*;

public class JPanelExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Panel Example");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](300, 200);

JPanel panel = new JPanel();

[Link](new FlowLayout());

JLabel label = new JLabel("Hello, JPanel!");


JButton button = new JButton("Click Me");

[Link](label);
[Link](button);

[Link](panel);
[Link](true);
}
}

JButton: The Clickable Button

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:

• Text Label: Displays text on the button.


• Icon: Can display an icon instead of or in addition to text.
• Enabled/Disabled State: Can be enabled or disabled to control user interaction.
• Focusable: Can receive keyboard focus.
• Tool Tips: Can display informative text when the mouse hovers over the button.

Example:

import [Link].*;
import [Link];
import [Link];

public class JButtonExample {


public static void main(String[] args)
{
JFrame frame = new JFrame("Button Example");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](300, 200);

JButton
button = new JButton("Click Me");
[Link](new ActionListener() {
public void actionPerformed(ActionEvent
e) {
[Link]("Button clicked!");
}
});

[Link](button);
[Link](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:

• Two States: Selected and deselected.


• Customizable Appearance: Can be customized to display different text or icons in each state.
• Focusable: Can receive keyboard focus.
• Event Handling: Can trigger events when the button's state changes.

Common Use Cases:

• Toggle Switches: For turning features on and off.


• Checkboxes: For selecting multiple options.
• Radio Buttons: For selecting one option from a group.

JCheckBox: A Versatile Check Box

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:
• Two States: Selected and deselected.
• Customizable Text: You can set a label to describe the option.
• Icon Support: You can add icons to visually represent the option.
• Event Handling: You can handle selection and deselection events using ItemListener.
JRadioButton: Selecting One Option
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 [Link].*;
import [Link];
import [Link];

public class JRadioButtonExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JRadioButton Example");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](300, 200);

ButtonGroup group = new ButtonGroup();

JRadioButton radioButton1 = new JRadioButton("Option 1");


JRadioButton radioButton2 = new JRadioButton("Option 2");
JRadioButton radioButton3 = new JRadioButton("Option 3");

[Link](radioButton1);
[Link](radioButton2);
[Link](radioButton3);

[Link](new ItemListener() {@Override


public void itemStateChanged(ItemEvent e) {
if ([Link]() == [Link]) {
[Link]("Option 1 selected");
}
}
});

// Add similar listeners for other radio buttons

[Link](radioButton1);
[Link](radioButton2);
[Link](radioButton3);
[Link](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:
JLabel label = new JLabel("Name:");
Constructor of the class are :
JLabel() : creates a blank label with no text or image in it.
JLabel(String s) : creates a new label with the string specified.
JLabel(Icon i) : creates a new label with a image on it.
JLabel(String s, Icon i, int align) : creates a new label with a string, an image and a specified horizontal alignment
Commonly used methods of the class are :
getIcon() : returns the image that the label displays
setIcon(Icon i) : sets the icon that the label will display to image i
getText() : returns the text that the label will display
setText(String s) : sets the text that the label will display to string s
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
JTextField() : constructor that creates a new TextField
JTextField(int columns) : constructor that creates a new empty TextField with specified number of columns.
JTextField(String text) : constructor that creates a new empty text field initialized with the given string.
JTextField(String text, int columns) : constructor that creates a new empty textField with the given string and a
specified number of columns .
JTextField(Document doc, String text, int columns) : constructor that creates a textfield that uses the given text
storage model and the given number of columns.
Methods of the JTextField are:

setColumns(int n) :set the number of columns of the text field.


setFont(Font f) : set the font of text displayed in text field.
addActionListener(ActionListener l) : set an ActionListener to the text field.
int getColumns() :get the number of columns in the textfield.
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
Constructors of JTextArea are:

JTextArea() : constructs a new blank text area .


JTextArea(String s) : constructs a new text area with a given initial text.

JTextArea(int row, int column) : constructs a new text area with a given number of rows and columns.

JTextArea(String s, int row, int column) : constructs a new text area with a given number of rows and columns and a
given initial text.

Commonly used methods :

append(String s) : appends the given string to the text of the text area.

getLineCount() : get number of lines in the text of text area.

setFont(Font f) : sets the font of text area to the given font.

setColumns(int c) : sets the number of columns of the text area to given integer.
JList
A JList displays a list of items from which the user can select one or multiple items.
Example:
String[] items = {"Item 1", "Item 2", "Item 3"};
JList<String> list = new JList<>(items);
Constructor for JList are :

1. JList(): creates an empty blank list


2. JList(E [ ] l) : creates an new list with the elements of the array.
3. JList(ListModel d): creates a new list with the specified List Model
4. JList(Vector l) : creates a new list with the elements of the vector
JComboBox
A JComboBox is a drop-down list that allows the user to select one item from a list of options.
Example:
String[] items = {"Item 1", "Item 2", "Item 3"};
JComboBox<String> comboBox = new JComboBox<>(items);
Constructor of the JComboBox are:

[Link]() : creates a new empty JComboBox .


[Link](ComboBoxModel M) : creates a new JComboBox with items from specified
ComboBoxModel
3. JComboBox(E [ ] i) : creates a new JComboBox with items from specified array.
4. JComboBox(Vector items) : creates a new JComboBox with items from the specified vector
Commonly used Methods are :

1. addItem(E item) : adds the item to the JComboBox


2. addItemListener( ItemListener l) : adds a ItemListener to JComboBox
3. getItemAt(int i) : returns the item at index i
4. getItemCount(): returns the number of items from the list
5. getSelectedItem() : returns the item which is selected
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:
JTextArea textArea = new JTextArea(10, 20);
JScrollPane scrollPane = new JScrollPane(textArea);
Constructor of JScrollPane

Constructors Descriptions

JScrollPane() It is a default constructor that creates an empty JScrollPane.

This constructor creates a JScrollPane with the specified view component


JScrollPane(Component comp)
as the scrollable content.

JScrollPane(int vertical, int This constructor creates an empty JScrollPane with the specified vertical
horizontal) and horizontal scrollbar.

JScrollPane(LayoutManager
This constructor creates a JScrollPane with the specified layout manager.
layout)

Common questions

Powered by AI

The advantages of using the Runnable interface include the ability to implement multiple interfaces, as Java doesn't support multiple inheritance of classes. It also offers flexibility, as different Thread objects can share the same Runnable object, which is not possible with Thread class inheritance .

JDialog is used to create dialog boxes and can be modal, blocking interaction with other windows until closed, unlike JFrame, which is used for creating the main application window. JDialogs are typically used for capturing user input or displaying messages, whereas JFrames represent main program windows with wider functionality like title bars, icons, and more complex layouts .

Method overloading supports polymorphism in Java by allowing multiple methods to have the same name but different parameter lists and implementations. This aligns with polymorphism's capability of providing "one interface, multiple methods" . However, the limitation is that method overloading cannot differentiate methods based solely on their return types; Java does not consider return types when resolving overloaded methods .

The MVC architecture in Swing applications benefits modularity by separating data handling, user interface, and control logic, which promotes easier maintenance and scalability. It allows developers to decouple the three aspects so they can be developed, modified, and tested independently, enhancing flexibility and promote a cleaner architecture .

A JPanel in Java Swing serves as a lightweight container for grouping other components, enhancing UI design by allowing complex layouts and organizing components logically. It supports customization with layout managers, enabling developers to create reusable components or custom panels for specific uses, such as building dashboards with various nested elements .

Layout managers in Swing define how components are arranged within containers like JFrame. Each layout manager provides different arrangements; for instance, BorderLayout divides a container into five regions (North, South, East, West, Center), allowing components to be added with relative positioning, which enhances UI design flexibility. By precisely managing component positioning, complex and scalable UIs can be created .

Static blocks are used for initializing static data members or perform one-time setup operations when a class is first loaded into memory. An example scenario where static blocks are useful is for loading a configuration file or initializing a static counter needed before any class methods are executed .

Synchronization in Java is crucial for controlling access to shared resources by multiple threads, preventing race conditions and data corruption. It involves using synchronized methods or blocks to ensure that only one thread can execute a critical section of code at a time, offering implicit locking mechanisms that manage thread access .

Using the stop() method incorrectly can lead to resource leaks or data corruption because it terminates threads abruptly, preventing run() methods from completing execution properly. This improper resource deallocation and inconsistent data states might compromise application stability; therefore, controlled shutdown using mechanisms like interrupts is recommended instead .

Event handling in Java Swing is crucial for responding to user interactions with GUI components. It operates on a listener model, where event listeners are registered to components and are triggered by specific actions, such as button clicks. This allows developers to define behaviors like updating the UI or triggering application logic, thus enabling dynamic and interactive applications .

You might also like