0% found this document useful (0 votes)
30 views402 pages

Object-Oriented Programming in Java

The document provides an overview of Object Oriented Programming (OOP) and its benefits, particularly focusing on Java as an object-oriented language. It discusses key features of Java, including its simplicity, security, portability, and performance, while also highlighting the differences between Java and other programming languages like C++. Additionally, it explains the Java execution process, including compilation to bytecode and the role of the Java Virtual Machine.
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)
30 views402 pages

Object-Oriented Programming in Java

The document provides an overview of Object Oriented Programming (OOP) and its benefits, particularly focusing on Java as an object-oriented language. It discusses key features of Java, including its simplicity, security, portability, and performance, while also highlighting the differences between Java and other programming languages like C++. Additionally, it explains the Java execution process, including compilation to bytecode and the role of the Java Virtual Machine.
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

Course :

Paper Code:
Faculty : Dr. Shivanka
Assistant Professor
VIPS
Ø Introduction to Object Oriented Programming
Ø Benefits of Object Oriented Programming
Ø Java Features
Ø How Java Differs from other OO languages
Ø Java Environment
Ø Execution Process organization of the Java virtual Machine Model of Java
Ø Build your first Java Program
Ø General Structure of Java program
Ø Classes and objects
Ø Inheritance
Ø Data Encapsulation and Abstraction:
Object-oriented programming (OOP) is a programming
paradigm using "objects" – data structures consisting of
data fields and methods together with their interactions
– to design applications and computer programs.
Programming techniques may include features such as
data abstraction, encapsulation, messaging, modularity,
pol ym orphi sm , a nd i nhe ri t a nc e . M a n y m o d e rn
programming languages now support OOP.
Benefits of Object Oriented Programming

•Ability to reflect the real world


•Easy to Maintain the code
•Information Hiding
•Reusability of Code
•Flexibility of Code
•Security
•Troubleshooting is easy
Ability to reflect the real world

❖ Every Entity in the real world can be expressed as an object in OOP.


❖ An Object is an entity with has state and behavior.
❖ Eg. Dog is a real world entity
• It has state: breed, color etc.,
• behavior: barks, eats etc.,
• It can be expressed as Object, by defining state and behavior in the
class.
Easy to Maintain the code
• Object Oriented Programming relies on classes, creation and
communication among objects.
• It is easy to maintain the code.
• Part of the code can be modified without affect the entire program.
• Eg. Overriding, inheritance etc.,
Information Hiding

• Variables,Methods are bundled in


class and accessed byobjects.
• Variables of a class are used by
methods of that class only.
• Data Abstraction provide the concept
of hiding implementation details and
workingonly with the
[Link]. Though users
do not know the internal mechanism
ofTV-Remote,they operate them by
pressing buttons of the remote.
Reusability of Code

•The existing classes properties can be acquired by subclasses through


the concept of inheritance.
•Reusability of Code adds essence to the Object Oriented Paradigm.
•Several types of Inheritances like single level, multilevel , hierarchical
etc., help in reusability of code
Flexibility of the code

It is easy to modify the a part of the code without affecting the entire
program. It is easy to reuse the existing code. It is easy to extend the
code for performing new operations.
Security

• Object Oriented Programming provides security.


• The concept of Encapsulation bundles variables and methods into a
component.
• The code can be protected from further modification, enhancement if
required.
For example: final keyword is used for not letting the class to be used
for inheritance.
Troubleshooting is easy

• Object Oriented Programming follows modular division and bottom


up programming approach.
• Hence, makes troubleshooting easy.
Characteristics of Java

vJava Is Simple
vJava Is Object-Oriented
vJava Is Distributed
vJava Is Interpreted
vJava Is Robust
vJava Is Secure
vJava Is Architecture-Neutral
vJava Is Portable
vJava's Performance
vJava Is Multithreaded
vJava Is Dynamic
Characteristics of Java
vJava Is Simple
vJava Is Object-Oriented
vJava Is Distributed
vJava Is Interpreted
vJava Is Robust
vJava Is Secure
vJava Is Architecture-Neutral
vJava Is Portable
vJava's Performance
vJava Is Multithreaded
vJava Is Dynamic

14
Characteristics of Java
vJava Is Simple Java is inherently object-oriented. Object-oriented
vJava Is Object-Oriented programming (OOP) is a popular programming
approach that is replacing traditional procedural
vJava Is Distributed programming techniques.
vJava Is Interpreted
One of the central issues in software development
vJava Is Robust is how to reuse code. Object-oriented
vJava Is Secure p r o g r a m m i n g p r o v i d e s g r e a t f l e x i b i l i t y,
modularity, clarity, and reusability through
vJava Is Architecture-Neutral encapsulation, inheritance, and polymorphism.
vJava Is Portable • focus on the data (objects) and methods
manipulating the data
vJava's Performance • all functions are associated with objects
vJava Is Multithreaded • almost all datatypes are objects (files, strings,
vJava Is Dynamic etc.)
• potentially better code organization and reuse

15
Characteristics of Java
vJava Is Simple Distributed computing involves several
computers working together on a network.
vJava Is Object-Oriented Java is designed to make distributed
vJava Is Distributed c o m p u t i n g e a s y. S i n c e n e t w o r k i n g
capability is inherently integrated into
vJava Is Interpreted Java, writing network programs is like
vJava Is Robust sending and receiving data to and from a
vJava Is Secure file.

vJava Is Architecture-Neutral
vJava Is Portable
vJava's Performance
vJava Is Multithreaded
vJava Is Dynamic

16
Characteristics of Java
vJava Is Simple
vJava Is Object-Oriented You need an interpreter to run Java
vJava Is Distributed programs. The programs are compiled into
vJava Is Interpreted the Java Virtual Machine code called
bytecode. The bytecode is machine-
vJava Is Robust independent and can run on any machine
vJava Is Secure that has a Java interpreter, which is part of
vJava Is Architecture-Neutral the Java Virtual Machine (JVM).
vJava Is Portable
vJava's Performance
vJava Is Multithreaded
vJava Is Dynamic

17
Characteristics of Java
vJava Is Simple Java compilers can detect many problems
vJava Is Object-Oriented that would first show up at execution time
in other languages. It has extensive
vJava Is Distributed compile-time and runtime error checking
vJava Is Interpreted • It has eliminated certain types of error-
vJava Is Robust prone programming constructs found
in other languages. There are no
vJava Is Secure pointers. Memory corruptions or
vJava Is Architecture-Neutral unauthorized memory accesses are
impossible
vJava Is Portable • Java has a runtime exception-handling
vJava's Performance feature to provide programming
vJava Is Multithreaded support for robustness.
• It has automatic garbage collection
vJava Is Dynamic tracks objects usage over time

18
Characteristics of Java
vJava Is Simple
vJava Is Object-Oriented
vJava Is Distributed
Java implements several security mechanisms
vJava Is Interpreted to protect your system against harm caused by
vJava Is Robust stray programs.
vJava Is Secure • usage in networked environments requires
more security
vJava Is Architecture-Neutral • memory allocation model is a major
vJava Is Portable defense
vJava's Performance • access restrictions are forced (private,
public)
vJava Is Multithreaded
vJava Is Dynamic

19
Characteristics of Java
vJava Is Simple
vJava Is Object-Oriented
vJava Is Distributed
vJava Is Interpreted
vJava Is Robust
vJava Is Secure
Write once, run anywhere
vJava Is Architecture-Neutral
vJava Is Portable With a Java Virtual Machine (JVM),
vJava's Performance you can write one program that will
run on any platform.
vJava Is Multithreaded
vJava Is Dynamic

20
Characteristics of Java
vJava Is Simple
vJava Is Object-Oriented
vJava Is Distributed
vJava Is Interpreted
vJava Is Robust
vJava Is Secure
vJava Is Architecture-Neutral
vJava Is Portable Because Java is architecture neutral,
vJava's Performance Java programs are portable. They can
be run on any platform without being
vJava Is Multithreaded recompiled.
vJava Is Dynamic

21
Characteristics of Java
vJava Is Simple
vJava Is Object-Oriented
vJava Is Distributed
vJava Is Interpreted
vJava Is Robust
vJava Is Secure
vJava Is Architecture-Neutral
vJava Is Portable Java’s performance is very high
vJava's Performance because of its architecture neutral and
vJava Is Multithreaded portable features.
vJava Is Dynamic

22
Characteristics of Java
vJava Is Simple
vJava Is Object-Oriented
vJava Is Distributed
vJava Is Interpreted
vJava Is Robust
vJava Is Secure
vJava Is Architecture-Neutral
vJava Is Portable
Multithread programming is smoothly
vJava's Performance integrated in Java, whereas in other
vJava Is Multithreaded languages you have to call procedures
specific to the operating system to enable
vJava Is Dynamic multithreading.

23
Characteristics of Java
vJava Is Simple
vJava Is Object-Oriented
vJava Is Distributed
vJava Is Interpreted
vJava Is Robust
vJava Is Secure
vJava Is Architecture-Neutral
vJava Is Portable
Java was designed to adapt to an evolving
vJava's Performance environment. New code can be loaded on the
vJava Is Multithreaded fly without recompilation. There is no need for
developers to create, and for users to install,
vJava Is Dynamic major new software versions. New features can
be incorporated transparently as needed.

24
ØSlower than compiled language such as C
ü an experiment in 1999 showed that Java was 3 or 4 times slower than C or C++
ü title of the article: “Comparing Java vs. C/C++ Efficiency Issues to Interpersonal Issues” (Lutz
Prechelt)
ü Running bytecode through the interpreter is not as fast as running machine code, which is
specific to that platform.

ØBecause it is platform independent, it is difficult to use platform specific


features (e.g., Windows taskbar, quick launch) in Java.

ØJava interpreter must be installed on the computer in order to run Java


programs.
Programmer

Source Code Object Executable


Code Code
Text Editor Compiler linker
.c file .o/.obj [Link] file
file
Notepad, gcc
emacs,vi
Java is Compiled and Interpreted
Hardware and
Programmer
Operating System

Source Code Byte Code


Text Editor Compiler Interpreter
.java file .class file
Notepad, javac java
emacs,vi, appletviewer
textpad, netscape
Java Interpreter
vJava is a little different.
vJava compiler produces bytecode not machine code.
vBytecode can be run on any computer with the Java interpreter
installed.
Win

eter
er pr
Java Program Java Bytecode Int
MAC
compiler Interpreter
Inte
r pret
er Unix
ØFor most languages, compilation produces machine code
ØJava compilation produces “bytecode”
üIntermediate code readable by the VM
üTransferable across the Internet as applets
ØVM interprets BC into instructions
üPartly responsible for performance lag
ØByteCode produced on any platform may be executed on
any other platform which supports a VM
(translator)

(same for all platforms)

(one for each different system)

Windows 95 Macintosh Solaris Windows NT


Write Once, Run Anywhere
source bytecode
(text) compiler (aka. class file)
JVML
dynamic
loading

verifier
virtual machine

JIT compiled
bytecode code
compiler
interpreter

CPU
ØJust-In-Time compiler
ØTranslates bytecode into machine code at runtime
ü1-time overhead when run initiated
üPerformance increase 10-30 times
ØNow the default for most JVM’s
üCan be turned off if desired
üJIT can apply statistical optimizations based on runtime usage
profile
ØJVM (J2EE & J2SE)
üWell-known Java Virtual Machine.
ØCVM , KVM (J2ME)
üSmall devices.
üReduces some VM features to fit resource-
constrained devices.
ØJCVM (Java Card)
üSmart cards.
üIt has least VM features.
and there are also lots of other JVMs
C++

C Java
In a first contact, Java seems like C++, and it's logical because Java takes the C and C++ syntax.
But Java has some important differences with C++. For instance, you can't use pointers in Java,
neither operators overload, neither multiple inheritance, neither predefined types. These features
of C++ that Java doesn't has, make it a simplest and more robust language. Interpreted Java is
furthermore slower than C++ (even 20 to 50 times slower than C in the original Java
interpreters).

Java memory administration is automatic; memory is assigned


automatically when you create an object, and also a garbage collector frees the memory when
that object is not used.
Functions malloc() and free() don't exist in Java.

: In Java, Primitive data types (like char, int, long...) have sizes and behaviors which
may be different in some platforms and operative systems. In Java language, unsigned data don't
exist. The boolean data has two values in Java : true and false. So it isn't an integer type, but you
can force "0" and "1" (which are integers) to be booleans.
The execution order of the operators in Java is same as in C.

The syntax of the following statements if, while, for and do is the
same as in C and C++. But there is an important difference : the proof expression
for each flux construction should return a boolean value (true or false). In C and
C++, the expression can return an integer.

In Java all method definitions have to have an specific number of


arguments. The arguments in the command line have a different behavior than in C
and C++. So, in these languages argv[0] is the name of the program but in Java this
is the first of additional arguments.
Ø No Typedefs, Defines, or Preprocessor
Ø No Global Variables
Ø No Goto statements
Ø No Pointers
Ø No Unsafe Structures
Ø No Multiple Inheritance
Ø No Operator Overloading
Ø No Automatic Coercions
Ø No Fragile Data Types
Feature C++ Objective C Ada Java
Encapsulation Yes Yes Yes Yes

Inheritance Yes Yes No Yes

Multiple Inherit. Yes Yes No No

Polymorphism Yes Yes Yes Yes

Binding (Early or Both Both Early Late


Late)
Concurrency Poor Poor Difficult Yes

Garbage Collection No Yes No Yes

Genericity Yes No Yes Limited

Class Libraries Yes Yes Limited Yes


üjavac - The Java Compiler
üjava - The Java Interpreter
üjdb- The Java Debugger
üappletviewer -Tool to run the applets
üjavap - to print the Java bytecodes
üjavaprof - Java profiler
üjavadoc - documentation generator
üjavah - creates C header files
Text Editor

Java Source
javadoc HTML Files
Code

javac

Java Class File javah Header Files

java jdb

Output
ØJava API and Virtual Machine insulate the Java program from hardware
dependencies.
ØJava API
• Collection of ready- • Core API
made software • Essentials: Object, String,
components that Input and Output...
provide many useful • Applets
capabilities. • Networking
• Internationalization
• Grouped into libraries • Security
(packages) of related • Software Components
components. • Object Serialization
• Java Database
Connectivity (JDBC)
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello World!");
}
}
ØCompile
üjavac [Link]
ØOne file named [Link] is created if the
compilation succeeds.
ØRun
üjava HelloWorld
• Since Java is object-oriented, programs are organized into modules called classes,
which may have data in variables and subroutines called methods.

class HelloWorld
{ public static void main (String[] args)
{ [Link](“Hello World!”);
}
}
•class keyword is used to declare a class in java.

•public keyword is an access modifier which represents visibility, it means it is


visible to all.

•static is a keyword, if we declare any method as static, it is known as static


method. The core advantage of static method is that there is no need to create object
to invoke the static method. The main method is executed by the JVM, so it doesn't
require to create object to invoke the main method. So it saves memory.

•void is the return type of the method, it means it doesn't return any value.

•main represents startup of the program.

•String[] args is used for command line argument.

•[Link]() is used print statement.


In object-oriented programming, a class is a construct that is used as a blueprint to create instances
of the class (class instances, class objects, instance objects or just objects). A class defines
constituent members which enable class instances to have state and behavior. Data field members
(member variables or instance variables) enable a class object to maintain state. Other kinds of
members, especially methods, enable a class object's behavior. Class instances are of the type of the
associated class.

For example, an instance of the class "Fruit" (a "Fruit" object) would be of the type "Fruit". A class
usually represents a noun, such as a person, place or (possibly quite abstract) thing. Programming
languages that include classes as a programming construct subtly differ in their support for various
class-related features. Most support various forms of class inheritance. Many languages also support
advanced encapsulation control features, such as access specifiers.
Object is an run time entity.

Is an Instance of class

Represents a Place ,Person ,anything that have some


attributes.
There is a very important distinction between an object
and an instance of an object. An object is actually a
definition, or a template for instances of that object. An
instance of an object is an actual thing that can be
manipulated.
For instance, we could define a Person object, which may
include such member data as hair color, eye color, height,
weight, etc. An instance of this object could be "Dave"
and Dave has values for hair color, eye color, etc. This
allows for multiple instances of an object to be created.
Data encapsulation, sometimes referred to as data hiding.
Data Encapsulation and Data Abstraction is one of the most striking feature of object
oriented programming.

The wrapping up of data and code into a single unit is called data encapsulation. The
data is not accessible to the outside world only those functions which are wrapped
into a class can only access the private data of the class.

Contd…
Data Encapsulation and Abstraction:
• The concept of data encapsulation is supported in C++ through the use of the public,
protected and private keywords which are placed in the declaration of the class.

• Note :
v Anything in the class placed after the public keyword is accessible to all the users of
the class

v Elements placed after the protected keyword are accessible only to the methods of the
class or classes derived from that class

v Elements placed after the private keyword are accessible only to the methods of the
class.
Inheritance is one of the most striking feature of object
oriented programming.

Inheritance is the process by which one class can acquire the


properties of another class.

The new classes, known as subclasses (or derived classes),


inherit attributes and behavior of the pre-existing classes,
which are referred to as superclasses (or ancestor classes).
The inheritance relationships of classes gives rise to a
hierarchy
Contd…
A superclass, base class, or parent class is a class from
which other classes are derived. The classes that are derived
from a superclass are known as child classes, derived
classes, or subclasses.

In object-oriented programming (OOP), inheritance is a


way to compartmentalize and reuse code by creating
collections of attributes and behaviors called objects
which can be based on previously created objects.
Course :
Paper Code:
Faculty : Dr. Shivanka
Assistant Professor
VIPS
What is Polymorphism?

• The derivation of the word Polymorphism is from two different Greek


words- poly and morphs. “Poly” means numerous, and “Morphs”
means forms. So, polymorphism means innumerable
[Link], therefore, is one of the most significant features
of Object-Oriented Programming.
Real-Life Examples of Polymorphism

• An individual can have different relationships with different people. A


male can be a father, a customer, an employee, and a friend, all at the
same time, i.e. he performs other behaviors in different situations.
Real-Life Examples of Polymorphism

• The human body has different organs. Every organ has a different
function to perform; the heart is responsible for blood flow, the lungs
for breathing, the brain for cognitive activity, and the kidneys for
excretion. So we have a standard method function that performs
differently depending upon the organ of the body.
Polymorphism in Java Example

• A superclass named “Shapes” has a method called “area()”. Subclasses


of “Shapes” can be “Triangle”, “circle”, “Rectangle”, etc. Each
subclass has its way of calculating area. Using Inheritance and
Polymorphism means, the subclasses can use the “area()” method to
find the area’s formula for that shape.
Compile-Time Polymorphism in Java

• Compile Time Polymorphism exist at the tIme of compilation is called


compile time polymorphism in Java is also known as Static
Polymorphism or early binding. .
• C om pi l e -Ti m e pol ym orphi sm i s a c hi e ve d t hroug h M e t h o d
Overloading. This type of polymorphism can also be achieved through
Operator Overloading. However, Java does not support Operator
Overloading.
Compile-Time Polymorphism in Java

• Method Overloading:- whenever a class contain more than


one method or multiple methods with the same name, but
types of parameters and the return type of the methods are
different are called Method Overloading.
• Syntax: return_type method_name(para1);
• return_type method_name(para1,para2);
Compile-Time Polymorphism in Java
package compiletimepolymorphism; void add(int x,double y){

public class methodoverloading{ double c;

void add(){ c=x+y;

int a=10,b=20,c; [Link]("Addition Value of int x=16 & double y =10.5:");

c=a+b; [Link](c);

[Link]("Addition Value of int a=10 & int b =20: "); }

[Link](c);
public static void main(String[] args){
}
methodoverloading r=new methodoverloading();
void add(int x,int y){
[Link]();//call add() method with no parameters
int c;
[Link](34,10); //call add() method with two int parameters
c=x+y;
[Link](16,10.5);//call add() method with int and double parameters
[Link]("Addition Value of parameter int x =34 & int y=10 :
");
[Link](c); }

} }
Run Time Polymorphism in Java
Example class Main {
public class polymorphismshapes {
public void area() { public static void main(String[] args) {
[Link]("The formula for area of "); polymorphismshapes myShape = new
polymorphismshapes();
}} // Create a polymorphismshapes class object
class Triangle extends polymorphismshapes{ polymorphismshapes myTriangle = new Triangle();
public void area(){ // Create a Triangle object
[Link]("Triangle is ½ * base * height "); polymorphismshapes myCircle = new Circle();
}} // Create a Circle object
class Circle extends polymorphismshapes { [Link]();
public void area() { [Link]();
[Link]("Circle is 3.14 * radius * radius "); [Link]();
}} [Link]();
}}
Polymorphism in Java Example

• Output:
• The formula for the area of the Triangle is ½ * base * height
• The formula for the area of the Circle is 3.14 * radius * radius
• In this process, an overridden method is called through the reference
variable of a superclass. The determination of the method to be called
is based on the object being referred to by the reference variable.

• Let's first understand the upcasting before Runtime Polymorphism.

• Upcasting
• If the reference variable of Parent class refers to the object of Child
class, it is known as upcasting. For example
Run-Time Polymorphism

class Square extends Shape {


class Shape { @Override
public void draw() { public void draw() {
[Link]("Drawing a shape"); [Link]("Drawing a square");
} }
} }
class Circle extends Shape { class Main {
@Override public static void main(String[] args) {
Shape s1 = new Circle();
public void draw() {
Shape s2 = new Square();
[Link]("Drawing a circle");
[Link](); // Output: "Drawing a circle"
}
[Link](); // Output: "Drawing a square"
}
}}
Output
• The program will
output: “Drawing a
circle” and “Drawing a
square
Course :
Paper Code:
Faculty : Dr. Shivanka
Assistant Professor
VIPS
Data Types in Java

• Data types specify the different sizes and values that can be stored in
the variable. There are two types of data types in Java:

• Primitive data types: The primitive data types include boolean, char,
byte, short, int, long, float and double.
• Non-primitive data types: The non-primitive data types include
Classes, Interfaces, and Arrays.
Data Types in Java
Boolean Data Type

• The Boolean data type is used to store only two possible values: true
and false. This data type is used for simple flags that track true/false
[Link] Boolean data type specifies one bit of information, but
its "size" can't be defined precisely.
• Example:
Boolean one = false
Byte Data Type

• The byte data type is an example of primitive data type. It isan 8-bit
signed two's complement integer. Its value-range lies between -128 to
127 (inclusive). Its minimum value is -128 and maximum value is 127.
Its default value is 0.
• The byte data type is used to save memory in large arrays where the
memory savings is most required. It saves space because a byte is 4
times smaller than an integer. It can also be used in place of "int" data
type.
• Example:
• byte a = 10, byte b = -20
Short Data Type

• The short data type is a 16-bit signed two's complement integer. Its
value-range lies between -32,768 to 32,767 (inclusive).

• The short data type can also be used to save memory just like byte
data type. A short data type is 2 times smaller than an integer.
short s = 10000, short r = -5000
Int Data Type

• The int data type is a 32-bit signed two's complement integer. Its
value-range lies between - 2,147,483,648 (-2^31) to 2,147,483,647
(2^31 -1) (inclusive). Its default value is 0.
• The int data type is generally used as a default data type for integral
values unless if there is no problem about memory.

• Example:
• int a = 100000, int b = -200000
Float Data Type

• The float data type is a single-precision [Link] value range is


unlimited. It is recommended to use a float (instead of double) if you
need to save memory in large arrays of floating point numbers. The
float data type should never be used for precise values, such as
currency. Its default value is 0.0F.

• Example:

• float f1 = 234.5f
Long Data Type

• The long data type is a 64-bit two's complement integer. Its value-
ra nge l i e s b e t w e e n -9 , 2 2 3 , 3 7 2 , 0 3 6 , 8 5 4 , 7 7 5 , 8 0 8 (-2 ^ 6 3 ) t o
9,223,372,036,854,775,807(2^63 -1)(inclusive). Its default value is 0.
The long data type is used when you need a range of values more than
those provided by int.
• Example:

• long a = 100000L, long b = -200000L


Double Data type

The double data type is a double-precision 64-bit IEEE 754 floating


point. Its value range is unlimited. The double data type is generally
used for decimal values just like float. The double data type also should
never be used for precise values, such as currency. Its default value is

0.0d.

Example:

double d1 = 12.3
Char Data Type

• The char data type is a single 16-bit Unicode character. Its value-range
lies between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char
data type is used to store characters.
• Example:
• char letterA = 'A'

Q Why char uses 2 byte in java and what is \u0000 ?


Ans:-It is because java uses Unicode system not ASCII code system.
The \u0000 is the lowest range of Unicode system.
Unicode System
• Unicode is a universal international standard character encoding that is
capable of representing most of the world's written languages.
• Why java uses Unicode System?
• Before Unicode, there were many language standards:
• ASCII (American Standard Code for Information Interchange) for the
United States.
• ISO 8859-1 for Western European Language.
• KOI-8 for Russian.
• GB18030 and BIG-5 for chinese, and so on.
Problem

This caused two problems:


• A particular code value corresponds to different letters in the various language standards.
• The encodings for languages with large character sets have variable [Link] common
characters are encoded as single bytes, other require two or more byte.

Solution
• To solve these problems, a new language standard was developed i.e. Unicode System.
• In unicode, character holds 2 byte, so java also uses 2 byte for characters.
• lowest value:\u0000
• highest value:\uFFFF
Example of Datatype
public class Datatype {
public static void main(String[] args) {
Output:-Integer Value is: 10
int myNum = 10; // integer (whole number) Float value is: 6.99
float myFloatNum = 6.99f; // floating point number
char myLetter = 'G'; // character
Char value is: G
boolean myBool = true; // boolean Boolean value is: true
String myText = "OOPS CLASS"; // String
[Link]("Integer Value is: "+ myNum); String value is: OOPS CLASS
[Link]("Float value is: " + myFloatNum);
[Link]("Char value is: " +myLetter);
[Link]("Boolean value is: " +myBool);
[Link]("String value is: "+ myText);
}
}
Example of float Data types:
A floating point number can also be a scientific number with an "e" to indicate
the power of 10:

public class Main {


public static void main(String[] args) {
float f1 = 35e3f;
double d1 = 12E4d; Output:
[Link](f1); 35000.0
120000.0
[Link](d1);
}
}
Non-Primitive Data Types

• Non-primitive data types are called reference types because they refer to objects.
• The main difference between primitive and non-primitive data types are:

• Primitive types are predefined (already defined) in Java. Non-primitive types are created by the programmer and is
not defined by Java (except for String).
• Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot.
• A primitive type has always a value, while non-primitive types can be null.
• A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase letter.
• The size of a primitive type depends on the data type, while non-primitive types have all the same size.
• Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.
Java Strings

Strings are used for storing text.A String variable contains a collection of
characters surrounded by double quotes:
String a1= “OOPS Java Class”;
Example :
public class Main {
public static void main(String[] args) {
String a1= “OOPS Java Class”;
[Link](g);
}
} Output: OOPS Java Class
String Length

• A String in Java is actually an Example of String Length:-


object, which contain methods public class Main {
that can perform certain public static void main(String[]
operations on strings. args) {
• For example, the length of a String txt = "IIOT and AIML
string can be found with the OOPS class";
length() method: [Link]("The length of
the txt string is: " + [Link]());
}}
Output:The length of the txt string
is: 24
String Concatenation

• The + operator can be used public class stringConcat {


between strings to combine them. public static void main(String
This is called concatenation: args[]) {
String firstName = "Shivam";
• Example String lastName = "roy";
[Link](firstName +
" " + lastName);
}
} Output:Shivam roy
Adding number and String
• Java uses the + operator for both Example of String Concatenation in
addition and concatenation. Number
public class Main {
• Numbers are added. Strings are
concatenated. public static void main(String[] args)
{
If you add two numbers, the result String a = "40";
will be a number:example String b = "30";
int a = 40; String c = a + b;
int b = 30; [Link](c);
int c = a + b; // c will be 70 (an }}
integer/number) Output 4030
Arrays
• An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is
created. After creation, its length is fixed. You have seen an example of arrays already, in the main method of the "Hello World!"
application.

An array of 10 elements.

• Illustration of an array as 10 boxes numbered 0 through 9; an index of 0 indicates the first element in the array.

• Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the preceding illustration,
numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.
Array Example
class ArrayDemo { anArray[9] = 1000;
public static void main(String[] args) { // declares an array of integers [Link]("Element at index 0: " + anArray[0]);
int[] anArray; [Link]("Element at index 1: " + anArray[1]);
anArray = new int[10]; // allocates memory for 10 integers
anArray[0] = 100; // initialize first element [Link]("Element at index 2: " + anArray[2]);
[Link]("Element at index 3: " + anArray[3]);
anArray[1] = 200; // initialize second elementOutput [Link]("Element at index 4: " + anArray[4]);
anArray[2] = 300; Element at index 0: 100 [Link]("Element at index 5: " + anArray[5]);
anArray[3] = 400; // and so forth Element at index 1: 200 [Link]("Element at index 6: " + anArray[6]);
anArray[4] = 500; Element at index 2: 300 [Link]("Element at index 7: " + anArray[7]);
anArray[5] = 600; Element at index 3: 400
[Link]("Element at index 8: "+ anArray[8]);
anArray[6] = 700;
Element at index 4: 500
Element at index 5: 600 [Link]("Element at index 9: "+ anArray[9]); } }
anArray[7] = 800;
Element at index 6: 700
anArray[8] = 900;
Element at index 7: 800
Element at index 8: 900
Element at index 9: 1000
Example :Sum of array N element
package array; Output: -

import [Link]; Enter the size of array :


10
public class Arraysum {
Enter array Elements :
public static void main(String[] args)
2
{ int n,sum=0;
4
Scanner ob=new Scanner([Link]);
6
[Link]("Enter the size of array : ");
8
n=[Link](); 10
int a[]=new int[n]; 12
[Link]("Enter array Elements : "); 14

for(int i=0;i<n;i++) 16

{ 18
20
a[i]=[Link]();
Sum of array N element is : 110
sum=sum+a[i];
}[Link]("Sum of array N element is : "+sum);
}}
Declares an array of integers

// declares an array of integers • Similarly, you can declare arrays of other types:
• byte[] anArrayOfBytes;
• int[] anArray; • short[] anArrayOfShorts;
• long[] anArrayOfLongs;
• Like declarations for variables of • float[] anArrayOfFloats;
other types, an array declaration • double[] anArrayOfDoubles;
has two components: the array's • boolean[] anArrayOfBooleans;

type and the array's name. • char[] anArrayOfChars;


• String[] anArrayOfStrings;
• You can also place the brackets after the array's name:

• // this form is discouraged


• float anArrayOfFloats[];
Creating, Initializing, and Accessing an Array

• One way to create an array is Alternatively, you can use the


with the new operator. The next shortcut syntax to create and
statement in the ArrayDemo initialize an array:
program allocates an array with
enough memory for 10 integer
elements and assigns the array to int[] anArray = {
the anArray variable. 100, 200, 300,
400, 500, 600,
• // create an array of integers 700, 800, 900, 1000
• anArray = new int[10]; };
Course :

Paper Code: IIOT-202,


Faculty : Dr. Shivanka
Assistant Professor
VIPS
Literals in Java

• In Java, literal is a notation that


represents a fixed value in the
source code.
• In Java, literals are the constant
values that appear directly in the
program. It can be assigned
directly to a variable. Java has
various types of literals.
Types of Literals in Java

• There are the majorly four types


of literals in Java:

• Integer Literal
• Character Literal
• Boolean Literal
• String Literal
Integer Literal
• Integer literals are sequences of digits. There are three types of integer literals:
• Decimal Integer: These are the set of numbers that consist of digits from 0 to 9. It may have a
positive (+) or negative (-) Note that between numbers commas and non-digit characters are not
permitted. For example, 5678, +657, -89, etc.
int decVal = 26;
• Octal Integer: It is a combination of number have digits from 0 to 7 with a leading 0. For example,
045, 026, int octVal = 067;
• Hexa-Decimal: The sequence of digits preceded by 0x or 0X is considered as hexadecimal
integers. It may also include a character from a to f or A to F that represents numbers from 10 to 15,
respectively. For example, 0xd, 0xf,
int hexVal = 0x1a;
• Binary Integer: Base 2, whose digits consists of the numbers 0 and 1 (you can create binary
literals in Java SE 7 and later). Prefix 0b represents the Binary system. For example, 0b11010.
• int binVal = 0b11010;
Real Literals and Backslash Literals

• Real Literals: The numbers that contain fractional parts are known as real literals. We can also
represent real literals in exponent form. For example, 879.90, 99E-3, etc.
• Backslash Literals
• Java supports some special backslash character literals known as backslash literals. They are used in
formatted output. For example:
1)\n: It is used for a new line 2) \a: It is used for a small beep
3)\r: It is used for carriage return (It moves cursor to current position to first position of the current line
and it does not read any character in between )
4) \b: It is used for blank space 5) \': It is used for a single quote
6) \t: It is used for horizontal tab 7) \v: It is used for vertical tab
8) \”: It is used for a double quote
Example of Backslash Literals

public class backslashLiterals {


public static void main(String args[]){
[Link]("Hello world"); Output :
Hello world
[Link]("\"IIOT in Java Class\""); "IIOT in Java Class"
IIoT
[Link](" welcome \rIIoT");
Hello world
[Link]("\n Hello world"); Hello world
[Link]("\t Hello world");
}}
Character Literals and String Literals

• Character Literals
A character literal is expressed as a character or an escape sequence,
enclosed in a single quote ('') mark. It is always a type of char. For
example, 'a', '%', '\u000d', etc.

• String Literals
String literal is a sequence of characters that is enclosed between double
quotes ("") marks. It may be alphabet, numbers, special characters,
blank space, etc. For example, "Jack", "12345", "\n", etc.
Character Literals & String Literals

• Character Literals
• A character literal is expressed as a character or an escape sequence, enclosed
in a single quote ('') mark. It is always a type of char. For example, 'a', '%',
'\u000d', etc.

• String Literals
• String literal is a sequence of characters that is enclosed between double quotes
("") marks. It may be alphabet, numbers, special characters, blank space, etc.
For example, "Jack", "12345", "\n", etc.
Floating Point Literals

• Floating Point Literals


• The values that contain decimal are floating literals. In Java, float and double primitive types
fall into floating-point literals. Keep in mind while dealing with floating-point literals.
• Floating-point literals for float type end with F or f. For example, 6f, 8.354F, etc. It is a 32-bit
float literal.
• Floating-point literals for double type end with D or d. It is optional to write D or d. For
example, 6d, 8.354D, etc. It is a 64-bit double literal.
• It can also be represented in the form of the exponent.
• Floating:

• float length = 155.4f;


Decimal & Boolean Literals
Decimal:
double interest = 99658.445;
Decimal in Exponent form:
double val= 1.234e2;
Boolean Literals
Boolean literals are the value that is either true or false. It may also have values 0 and 1. For example, true, 0, etc.
boolean isEven = true;
Null Literals
Null literal is often used in programs as a marker to indicate that reference type object is unavailable. The value
null may be assigned to any variable, except variables of primitive types.
String stuName = null;
Student age = null;
Class Literals & Invalid Literals
Class Literals
Class literal formed by taking a type name and appending .class extension. For example,
[Link]. It refers to the object (of type Class) that represents the type itself.
class classType = [Link];
Invalid Literals
There is some invalid declaration of literals.
float g = 6_.674f;
float g = 6._674F;
long phoneNumber = 99_00_99_00_99_L;
int x = 77_;
int y = 0_x76;
int z = 0X_12;
int z = 0X12_;
Restrictions to Use Underscore (_)
It can be used at the beginning, at the end, and in-between of a number.
It can be adjacent to a decimal point in a floating-point literal.
Also, can be used prior to an F or L suffix.
In positions where a string of digits is expected.
Why use literals?
To avoid defining the constant somewhere and making up a label for it. Instead, to write the value of
a constant operand as a part of the instruction.

How to use literals?


A literal in Java can be identified with the prefix =, followed by a specific value.
Example : using Literals
[Link] • char ch1 = '\u0021';

• char ch2 = 1456;


public class LiteralsExample
• [Link](count); Output : 987
{ • [Link](floatVal); 4534.99
public static void main(String args[]) • [Link](cost); 19765.567
{ • [Link](hexaVal); 2020
• [Link](binary); 26
int count = 987;
• [Link](alpha); p
float floatVal = 4534.99f; • [Link](str); Java
double cost = 19765.567; • [Link](boolVal); true
int hexaVal = 0x7e4; • [Link](octalVal); 55
int binary = 0b11010;
• [Link](stuName);
null
• [Link](ch1);
!
char alpha = 'p'; • [Link]("\t" +"backslash literal");
backslash literal
String str = "Java"; boolean boolVal = true; • [Link](ch2);
?
• } }
int octalVal = 067;
String stuName = null;
Course :
Paper Code:
Faculty : Dr. Shivanka
Assistant Professor
VIPS
Java Arrays
• 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.
• In Java, array is an object of a dynamically generated class. Java array
inherits the Object class, and implements the Serializable as well as
Cloneable interfaces. We can store primitive values or objects in an
array in Java.
Java Arrays

• Similar to C/C++, we can also create single dimentional


or multidimentional arrays in Java.

• Moreover, Java provides the feature of anonymous


arrays which is not available in C/C++
Types of Array in java

There are two types of array.

• Single Dimensional Array


• Multidimensional Array
Single Dimensional Array in Java
/Java Program to illustrate how to declare, instantiate,
Syntax to Declare an Array in Java initialize //and traverse the Java array.
class Testarray{
public static void main(String args[]){
dataType[] arr; (or)
int a[]=new int[5];//declaration and instantiation
dataType []arr; (or)
a[0]=10;//initialization
dataType arr[];
a[1]=20;
Instantiation of an Array in Java output
a[2]=70; 10
a[3]=40; 20
arrayRefVar=new datatype[size]; 70
a[4]=50;
Example of Java Array 40
//traversing array 70
The simple example of java array, where to declare,
instantiate, initialize and traverse an array. for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}}
/
Declaration, Instantiation and
Initialization of Java Array
• We can declare, instantiate and • Java Program to illustrate the use of declaration,
instantiation
initialize the java array together • //and initialization of Java array in a single line
by: • class Testarray1{
• public static void main(String args[]){
• int a[]={33,3,4,5};//declaration, instantiation and
• int a[]={33,3,4,5}; initialization
• //printing array
• //declaration, instantiation and
• for(int i=0;i<[Link];i++)//length is the property of
initialization array
• [Link](a[i]);
• }}
Multidimensional Array in Java
• To create a two-dimensional • Example to initialize Multidimensional Array
in Java
array, add each array within its
• arr[0][0]=1;
own set of curly braces:
• arr[0][1]=2;
• dataType[][] arrayRefVar; (or) • arr[0][2]=3;
• dataType [][]arrayRefVar; (or) • arr[1][0]=4;
• dataType arrayRefVar[][]; (or) • arr[1][1]=5;
• arr[1][2]=6;
• dataType []arrayRefVar[];
• arr[2][0]=7;

int[][] arr=new int[3][3]; • arr[2][1]=8;


//3 row and 3 column • arr[2][2]=9;
Multidimensional Array in Java
• //Java Program to illustrate the use of
multidimensional array
• class Testarray3{
• public static void main(String args[]){
• Output
• //declaring and initializing 2D array
• int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
123
• //To create a two-dimensional array, add each array
within its own set of curly braces: 245
• //printing 2D array
• for(int i=0;i<3;i++){
445
• for(int j=0;j<3;j++){
• [Link](arr[i][j]+" ");
• }
• [Link]();
• }
• }}
Exp3:-Sum of array of N no element
enter by user
Output: -
package array; { Enter the size of array :
a[i]=[Link](); 10
import [Link];
Enter array Elements :
public class Arraysum { sum=sum+a[i]; 2
public static void main(String[] args) } 4
[Link]("Sum6 of array is : "+sum);
{ int n,sum=0; Scanner ob=new 8
} 10
Scanner([Link]);
} 12
[Link]("Enter the size of array : "); 14
n=[Link]();nt a[]=new int[n]; 16
18
[Link]("Enter array Elements : "); 20
for(int i=0;i<n;i++) Sum of array N element is : 110


Declaring an array
int[] myArray;
int[] myArray = new int[5];
String[] stringArray = new String[10];
String[] strings = new String[] {“one”, “two”};

Looping over an array


Checking an arrays length
for(int I=0; I<[Link]; i++)
int arrayLength = [Link];
{
String s = myArray[i];
}
Bounds checking
• Java does this automatically.
• It is impossible to go beyond the end of an array (unlike C/C++)
• Automatically generates an ArrayIndexOutOfBoundsException

{ total += myList[i]; }
public class TestArray { [Link]("Total is " + total);
public static void main(String[] args) // Finding the largest element
{ double max = myList[0];
double[] myList = {1.9, 2.9, 3.4, 3.5}; for (int i = 1; i < [Link];
// Print all the array elements i++)
for (int i = 0; i < [Link]; i++) {
{[Link](myList[i] + " "); } if (myList[i] > max)
// Summing all elements max = myList[i];
}
double total = 0; [Link]("Max is " +
for (int i = 0; i < [Link]; i++) max);
}
}
ü Don’t copy arrays “by hand” by looping over the array
ü The System class has an method to do this efficiently

int array1[] = new int[10];


int array2[] = new int[10];
The System class has an that you can use to efficiently copy data from one array into another:
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
The two Object arguments specify the array to (array1) copy from and the array to copy to (array2). The three int arguments
specify the starting position in the source array, the starting position in the destination array, and the number of array
elements to copy
//assume we add items to array1

//copy array1 into array2


[Link](array1, 0, array2, 0, 10);

//copy last 2 elements to 7 elament in array1 into first 7 of array2


[Link](array1,2 , array2, 0, 7);
Array copy method
The following program, ArrayCopyDemo, declares an array of String elements. It uses the [Link] method to copy a subsequence of
array components into a second array:
class ArrayCopyDemo {
public static void main(String[] args) {
String[] array1 = {
"Vrinda", "Amit", "Chahat", "Simran", "Rohit ", "Deepak", "Angel", " Shagun", "Sheetal", "Srishti", "Mohit", "Rohit", "Aman" };
String[] array2 = new String[7];
[Link](array1, 2, array2, 0, 7);
for (String name : array2) {
[Link](name + " ");
}}}
The output from this program is:

Chahat simran Rohit Deepak Angel Shagun Sheetal


The [Link] class contains a static factory that allows arrays to be viewed as lists.
Following are the important points about Arrays −

•This class contains various methods for manipulating arrays (such as sorting and
searching).

•The methods in this class throw a NullPointerException if the specified array reference is
null.
static int binarySearch(byte[] a, byte key) This method searches the specified array of bytes
for the specified value using the binary search algorithm.
static boolean equals(long[] a, long[] a2) This method returns true if the two specified
arrays of longs are equal to one another.
static int hashCode(byte[] a) This method returns a hash code based on the contents of the
specified array.
static void sort(char[] a) This method sorts the specified array of chars into ascending
numerical order.

Around 105 methods defined in Arrays class to do different operations on arrays.


Course :

Paper Code:
Faculty : Dr. Shivanka
Assistant Professor
VIPS
Anonymous Inner Class
Anonymous Inner Class

• An anonymous inner class is one that has no name and produces only one
object.

• Anonymous classes can be useful for providing quick implementations of


interfaces or abstract classes in situations where creating a named class would
be overly verbose or cumbersome.
• In simple words, a class that has no name is known as an anonymous inner
class in Java. It should be used if you have to override a method of class or
interface. Java Anonymous inner class can be created in two ways:
• [Link] (may be abstract or concrete).
• [Link]
Note:- An anonymous class must be defined inside another class. Hence, it is also known as an
anonymous inner class. Its syntax is:

class outerClass {

// defining anonymous class


object1 = new Type(parameterList) {
// body of the anonymous class
};
}
Anonymous classes usually extend subclasses or implement interfaces.
Here, Type can be a superclass that an anonymous class extends an interface that an anonymous class implements the above code
creates an object, object1, of an anonymous class at runtime.
Types of Anonymous Class in Java

Anonymous classes are typically used to extend subclasses or implement interfaces. So, there can be 2 types of
anonymous classes in Java:

v An anonymous class that extends a superclass.


v An anonymous class that implements an interface.
Example: Anonymous Class Extending a Class
Let's see an example of an anonymous class that extends a class.

In the example below, we have created a class Demo. It has a single method view(). We then created an
anonymous class that extends the class Demo and overrides the view() method.

When we run the program, an object d1 of the anonymous class is created. The object then calls the view()
method of the anonymous class.
Example 1: Anonymous Class
Extending a Class
class Polygon {
public void display() { class Main {
[Link]("Inside the Polygon class"); }} public static void main(String[] args) {
class AnonymousDemo { AnonymousDemo an = new
public void createClass() { AnonymousDemo();
// creation of anonymous class extending class [Link]();
Polygon
}
Polygon p1 = new Polygon() {
public void display() {
}
[Link]("Inside an anonymous Output
class.");
}
Inside an anonymous class.
};
[Link](); }}
Example 2: Anonymous Class
Implementing an Interface
interface Polygon { class Main {
public void display();} public static void main(String[] args) {
AnonymousDemo an = new AnonymousDemo();
class AnonymousDemo {
[Link]();
public void createClass() {
}
// anonymous class implementing interface
}
Polygon p1 = new Polygon() {
public void display() { Output
[Link]("Inside an anonymous
class."); Inside an anonymous class.
}};//anonymous inner claass ends In the above example, we have created an anonymous
[Link](); class that implements the Polygon interface.

}
}
Example: Anonymous Class Extending a
Class
class Demo { [Link]();
public void view() { }
[Link]("Inside the Demo class"); }
}} class Main {
class MyClass { public static void main(String[] args) {
public void myMethod() {// creation of anonymous MyClass cls = new MyClass();
class extending class the class Demo
[Link]();
Demo d1 = new Demo() {//Anonymous Class
}}
public void view() {
Output
[Link]("Inside the Anonymous
Class");
} Inside an anonymous class.
};
Advantages of Anonymous Classes

• In anonymous classes, objects are created Here, an object of the anonymous


whenever they are required. That is,
objects are created to perform some
class is created dynamically when
specific tasks. For example, we need to override the display()
method.
Object = new Example() {
public void display() { • Anonymous classes also help us
[Link]("Anonymous class to make our code concise.
overrides the method display().");
}
};
Course :
Paper Code:
Faculty : Dr. Shivanka
Assistant Professor
VIPS
INHERITANCE

• Inheritance is an OOPS concept by which a class can acquire the


characteristics of another class. i.e it’s a method of creating a new
class based on already existing class.
• The class from which its inheriting is called base class and the class
which is inheriting is called sub class.
• It is the inheriting properties of parent class or base class to sub class
or child class.
• subclass (child) - the class that inherits from another class
• superclass (parent) - the class being inherited from
• To inherit from a class, use the extends keyword.
Why Do We Need Java Inheritance?

• Code Reusability: The code written in the Superclass is common to all


subclasses. Child classes can directly use the parent class code.
• Method Overriding: Method Overriding is achievable only through
Inheritance. It is one of the ways by which Java achieves Run Time
Polymorphism.
• Abstraction: The concept of abstract where we do not have to provide
all details is achieved through inheritance. Abstraction only shows the
functionality to the user.
How to use Syntax of Inheritance in Java?

• To inherit the parent class, a child class must include a keyword called "extends."
The keyword "extends" enables the compiler to understand that the child class
derives the functionalities and members of its parent class.
• To understand this in an easier way, let us verify the syntax for inheritance in Java.
Syntax:
class SubClass extends ParentClass
{
//DataMembers;
//Methods;
}
Types of Inheritance in Java

The different 5 types of Inheritance in java are as follows:

1. Single inheritance.
2. Multi-level inheritance.
3. Multiple inheritance.
4. Hierarchical Inheritance.
5. Hybrid Inheritance.
1. Single Inheritance

• In single inheritance, a single


subclass extends from a single
superclass.
For example :Class A inherits from
class B.
Single Inheritance

class A
{ class SingleInheritance Save this program class
int a, b; { name including main
public static void main(String args[]) function
void display()
[Link]
{
{
[Link]("Inside class A values = "+a+" "+b); Output :-
B obj = new B(); //derived class object
}} Inside class A values = 10
obj.a=10;
class B extends A 20
obj.b=20;
{ Inside Class B values=10
int c;
obj.c=30; 20 30
[Link]();
void show() {
[Link]();
[Link]("Inside Class B values=" +a+ " "+b+" " +c); }
}
}
}
Multi-Level Inheritance in Java

• In Multi-Level Inheritance in
Java, a class extends to another
class that is already extended
from another class.
• For example, if there is a class A
that extends class B and class B
extends from another class C,
then this scenario is known to
follow Multi-level Inheritance.
MULTI LEVEL INHERITANCE

class Electronics { class WetGrinder extends Grinder { Output :-


Electronics
public WetGrinder() { Class Electronics
public Electronics(){
[Link]("Class WetGrinder");
Class Grinder
[Link]("Class Electronics"); Class WetGrinder
}
}
public void grinding_tech() {
public void deviceType() { Grinder Device Type: Electronics
[Link]("Grinding Technology-
Category: Grinder
[Link]("Device Type: Electronics"); WetGrinder"); GrindingTechnology:
}} } WetGrinder
class Grinder extends Electronics { WetGrinder }

public Grinder() { public class Tester {


public static void main(String[] arguments) {
[Link]("Class Grinder");
WetGrinder wt= new WetGrinder();
}
[Link]();
public void category() {
[Link]();
[Link]("Category - Grinder"); wt.grinding_tech();
}} }}
Multiple Inheritance in Java

• Defining derived class from


numerous base classes or
superclass is known as ‘Multiple
Inheritance’. In this case, there is
more than one superclass, and
there can be one or more
subclasses.

• Multiple inheritances are


available in object-oriented
programming with C++, but it is
not available in Java.
Why Multiple Inheritance is not supported in Java?
• Note: Java doesn't support multiple inheritance. However, we can
achieve multiple inheritance using interfaces.
• Let's consider a case in Inheritance. Consider a class A, class B and
class C. Now, let class C extend class A and class B. Now, consider a
method read() in both class A and class B. The method read() in class
A is different from the method read() in class B. But, while inheritance
happens, the compiler has difficulty in deciding on which read() to
inherit. So, in order to avoid such kind of ambiguity, multiple
inheritance is not supported in Java.
Interface in Java

• An interface in Java is a blueprint of a behaviour. A Java interface


contains static constants and abstract methods.

• The interface in Java is a mechanism to achieve abstraction. There can


be only abstract methods in the Java interface, not the method body. It
is used to achieve abstraction and multiple inheritance in Java. In other
words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body. Java Interface also represents
the IS-A relationship.
Characterstics of Interface

Like a class, an interface can have methods and variables, but the A Java library example is Comparator Interface. If a class
methods declared in an interface are by default abstract (only implements this interface, then it can be used to sort a
method signature, no body). collection.
q Interfaces specify what a class must do and not how. It is the
blueprint of the behaviour.
Syntax:

q Interface do not have constructor. interface {


q Represent behaviour as interface unless every sub-type of the
class is guarantee to have that behaviour.
// declare constant fields
q An Interface is about capabilities like a Player may be an
interface and any class implementing Player must be able to // declare methods that abstract
(or must implement) move(). So it specifies a set of methods // by default.
that the class has to implement.
q If a class implements an interface and does not provide
}
method bodies for all functions specified in the interface, then To declare an interface, use the interface keyword. It is
the class must be declared abstract. used to provide total abstraction. That m
vIt is used to achieve total abstraction. // A simple interface
vS i n c e j a v a d o e s n o t s u p p o r t m u l t i p l e
inheritances in the case of class, by using an
interface it can achieve multiple inheritances.
interface Player
vAny class can extend only 1 class but can any
class implement infinite number of interface. {
vIt is also used to achieve loose coupling. final int id = 10;
vInterfaces are used to implement abstraction.
So the question arises why use interfaces
when we have abstract classes? int move();
vThe reason is, abstract classes may contain
non-final variables, whereas variables in the }
interface are final, public and static.
Multiple inheritance is not supported
through class in java, but it is possible by
an interface, why?
Multiple inheritance is not supported in the case of class because of ambiguity. However, it is supported in case of an interface
because there is no ambiguity. It is because its implementation is provided by the implementation class. For example:
Example:-
interface Printable{ //1st Interface
void print(); } Output : Hello
interface Showable{ //2nd interface
void print(); }
class TestInterface3 implements Printable, Showable{
public void print(){[Link]("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
[Link]();
} }
Interface Inheritance

A class implements an interface, but one


interface extends another interface. public static void main(String args[]){

interface Printable{ TestInterface4 obj = new TestInterface4();

void print(); [Link]();

} [Link]();

interface Showable extends Printable{ }

void show(); }

} Output:-

class TestInterface4 implements Showable{ Hello

public void print(){[Link]("Hello");} Welcome

public void show(){[Link]("Welcome");}


Difference Between Class and Interface
[Link] Class Interface
1 In class, you can instantiate variables and create an In an interface, you can’t
object. instantiate variables and create
an object

2 Class can contain concrete(with implementation) The interface cannot contain


methods concrete(with implementation)
methods

3 The access specifiers used with classes are private, In Interface only one specifier is
protected, and public. used- Public
Abstract class in Java

1. Abstraction is a process of hiding the implementation details and showing only functionality to
the use.
2. A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
• Points to Remember
qAn abstract class must be declared with an abstract keyword.
qIt can have abstract and non-abstract methods.
qIt cannot be instantiated.
qIt can have constructors and static methods also.
qIt can have final methods which will force the subclass not to change the body of the method.
Features of Abstract Class
Features of Abstract Class

Template Abstraction
Data abstraction in Java helps the developers hide the code
The abstract class in Java enables the best way to complications from the end-user by reducing the project's complete
execute the process of data abstraction by providing characteristics to only the necessary components.
the developers with the option of hiding the code Dynamic Resolution
implementation. It also presents the end-user with a
template that explains the methods involved. Using the support of dynamic method resolution, developers can
solve multiple problems with the help of one abstract method.
Loose Coupling The Syntax for Abstract Class
Data abstraction in Java enables loose coupling, by To declare an abstract class, use the access modifier first, then the
reducing the dependencies at an exponential level. "abstract" keyword, and the class name shown below.

Code Reusability //Syntax:


<Access_Modifier> abstract class <Class_Name> {
Using an abstract class in the code saves time. We can
call the abstract method wherever the method is //Data_Members;
necessary. Abstract class avoids the process of writing //Statements;
the same code again. //Methods;}
Abstract Class Example
abstract public class AbstractDemoVehicle { public static void main(String[] args) {
int no_of_tyres; // TODO code application logic here
abstract void start();//without defining or body
//AbstractDemoVehicle a=new
} AbstractDemoVehicle();
class car extends AbstractDemoVehicle{ //It will show error because class is abstact
void start()
car c=new car();
{[Link]("Start with key");
[Link](); Output:-
} Start with key
scooter x=new scooter(); Start with kick
class scooter extends AbstractDemoVehicle{
void start(){[Link]("Start with kick");
[Link]();}
}}
}
Difference between abstract class and interface

Abstract class and interface both are used to achieve


abstraction where we can declare the abstract methods.
Abstract class and interface both can't be instantiated.

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves
fully abstraction (100%).
Difference between abstract class and Interface
Abstract Class Interface
1) Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods. Since Java 8, it can
have default and static methods also.
2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and non-static Interface has only static and final variables.
variables.
4) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class.

5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.
6) An abstract class can extend another Java class and An interface can extend another Java interface only.
implement multiple Java interfaces.
7) An abstract class can be extended using keyword "extends". An interface can be implemented using keyword "implements".

8) A Java abstract class can have class members like private, Members of a Java interface are public by default.
protected, etc.
9)Example:-public abstract class Shape{ 9)Example:-public interface Drawable{
public abstract void draw();} void draw();}
Java 8 Default Method in Interface
Since Java 8, we can have method body in interface. class TestInterfaceDefault{
But we need to make it default method Example in
java 8 Default method: public static void main(String args[]){
Save File: [Link] Drawable d=new Rectangle();
interface Drawable{ [Link]();
void draw();
[Link]();
default void msg(){[Link]("default
method");} }}
}
class Rectangle implements Drawable{ Output:

public void draw(){[Link]("drawing


rectangle");} drawing rectangle
} default method
Java 8 Static Method in Interface
Since Java 8, we can have static method in interface. class TestInterfaceStatic{
Let's see an example:
public static void main(String args[]){
Drawable d=new Rectangle();
File: [Link]
[Link]();
[Link]([Link](3));
interface Drawable{
}}
void draw();
static int cube(int x){return x*x*x;}
Output:
}
class Rectangle implements Drawable{
drawing rectangle
public void draw(){[Link]("drawing
27
rectangle");}
}
Hierarchical Inheritance in Java

• In hi e ra rc hi c a l i nhe ri t a n c e ,
multiple subclasses extend from
a single superclass.
• For example, consider a parent
class Car. Now, consider child
classes Audi, BMW and
Mercedes. In Hierarchical
Inheritance in Java, class Audi,
class BMW and class Mercedes,
all these three extend class Car.
Hierarchical Inheritance
public class HierarchicalInheritanceTest
public class ClassH1 { Output:
{ public static void main(String args[]) disp() method of ClassH2
public void dispH1() { //Assigning ClassH2 object to ClassH2 referencedisp() method of ClassH1
{ [Link]("disp() method of ClassH2 h2 = new ClassH2(); disp() method of ClassH3
ClassH1"); }} //call dispH2() method of ClassH2 disp() method of ClassH1
public class ClassH2 extends ClassH1 h2.dispH2(); disp() method of ClassH4
{ public void dispH2() //call dispH1() method of ClassH1 disp() method of ClassH1
{ [Link]("disp() method of h2.dispH1();//Assigning ClassH3 object to ClassH3 reference
ClassH2"); }} ClassH3 h3 = new ClassH3();
public class ClassH3 extends ClassH1 //call dispH3() method of ClassH3
{public void dispH3() h3.dispH3();
{[Link]("disp() method of //call dispH1() method of ClassH1
ClassH3"); }} }} h3.dispH1() //Assigning ClassH4 object to ClassH4 reference
public class ClassH4 extends ClassH1 ClassH4 h4 = new ClassH4();
{public void dispH4() //call dispH4() method of ClassH4
{[Link]("disp() method of h4.dispH4();
ClassH4"); }} //call dispH1() method of ClassH1
}} h4.dispH1(); }}
Example for Super Keyword in Java:
class Superclass
Super keyword usage in inheritance, always { int i =20;
refers to its immediate as an object.
void display()
{ [Link](“Superclass display method”); } }

There are three usages of super keyword in class Subclass extends Superclass

Java: { int i = 100;


void display()
{ [Link]();
1. We can invoke the superclass variables. [Link](“Subclass display method”);
[Link](“ i value =”+i);
[Link](“superclass i value =”+super.i);
2. We can invoke the superclass methods. }}
class SuperUse{ public static void main(String args[])

3. We can invoke the superclass constructor. { Subclass obj = new Subclass();


[Link]();
}}
Course :
Paper Code: IIOT-202,AIML
Faculty : Dr. Shivanka
Assistant Professor
VIPS
What are Java Exception?

• Exception is an unwanted or unexpected event, which occurs during


the execution of a program, i.e. at run time, that disrupts the normal
flow of the program’s instructions. Exceptions can be caught and
handled by the program. When an exception occurs within a method, it
creates an object. This object is called the exception object. It contains
information about the exception, such as the name and description of
the exception and the state of the program when the exception
occurred.
Java Exceptions

What is an Exception?
§ An exception is an event that occurs during the execution of a program
that disrupts the normal flow of instructions.
§ When an error occurs, Java will normally stop and generate an error
message. The technical term for this is: Java will throw an exception
(throw an error).
§ When executing Java code, different errors can occur: coding errors
made by the programmer, errors due to wrong input, or other
unforeseeable things.
Exception Hierarchy

• All exception and error types are subclasses of class Throwable, which
is the base class of the hierarchy. One branch is headed by Exception.
This class is used for exceptional conditions that user programs should
catch. NullPointerException is an example of such an exception
Exception Hierarchy
Types of Exceptions

• Java defines several types of


exceptions that relate to its
various class libraries. Java also
allows users to define their own
exceptions.
Built-in Exceptions:
• Built-in exceptions are the exceptions that are available in Java
libraries. These exceptions are suitable to explain certain error
situations.
• Checked Exceptions: Checked exceptions are called compile-time
exceptions because these exceptions are checked at compile-time by
the compiler.

• Unchecked Exceptions: The unchecked exceptions are just opposite


to the checked exceptions. The compiler will not check these
exceptions at compile time. In simple words, if a program throws an
unchecked exception, and even if we didn’t handle or declare it, the
program would not give a compilation error.
You learned that there are three categories of
errors: Syntax errors, Runtime errors, and Logic
errors.
Syntax errors arise because the rules of the
language have not been followed. They are
detected by the compiler.
Runtime errors occur while the program is running
if the environment detects an operation that is
impossible to carry out.
occur when a program doesn't
perform the way it was intended to.
Ø Gradually, programmers began to realize that the
traditional method of handling errors was too
cumbersome for most error handling situations.
Ø This gave rise to the Exception concept
ü When an error occurs, that represents an Exceptional condition.
ü cause the current program flow to be interrupted and
transferred to a registered exception handling block.
ü This might involve unrolling the method calling stack.

Ø involves a well-structured goto.


Ø When an error is detected, an exception is thrown.
Ø Any exception which is thrown, must be caught by and exception
handler
ü If the programmer hasn't provided one, the exception will be caught by a
catch-all exception handler provided by the system.
ü The default exception handler may terminate the application.

Ø Exceptions can be rethrown if the exception cannot be handled by


the block which caught the exception
Ø Java has 5 keywords for exception handling:
try
catch
finally
throw
throws
ØExceptions break the normal flow of control.
ØWhen an exception occurs, the statement that would
normally execute next is not executed.
ØWhat happens instead depends on:
üwhether the exception is caught,
üwhere it is caught,
üwhat statements are executed in the ‘catch block’,
üand whether you have a ‘finally block’.
Five Key words of Exceptional handling
• Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
Java try and catch
The try statement allows you to define a block of code to be tested for errors while it is being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
The come in pairs:
Syntax
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
Major reasons why an exception Occurs

vInvalid user input


vDevice failure
vLoss of network connection
vPhysical limitations (out of disk memory)
vCode errors
vOpening an unavailable file
• Errors represent irrecoverable conditions such as Java virtual machine (JVM)
running out of memory, memory leaks, stack overflow errors, library
incompatibility, infinite recursion, etc. Errors are usually beyond the control of
the programmer, and we should not try to handle errors.
Example: Array out of bound Exception

Consider the following example:


This will generate an error, because myNumbers[10] does not exist.
If an error occurs, we can use
try...catch to catch the error and
public class Main { execute some code to handle it:
public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
[Link](myNumbers[10]); // error!
}
}
The output will be something like this:

Exception in thread "main"


[Link]: 10
at [Link]([Link])
Example to use try...catch
Example
• The output will be:
public class Main {
public static void main(String[ ] args) {
try { • Something went wrong.
int[] myNumbers = {1, 2, 3};
[Link](myNumbers[10]);
} catch (Exception e) {
[Link]("Something went wrong.");
}
}
}
Finally Keyword

The finally statement lets you execute code, after try...catch,


regardless of the result: • The output will be:
Example
public class Main { • Something went wrong.
public static void main(String[] args) {
try {
• The 'try catch' is finished.
int[] myNumbers = {1, 2, 3};
[Link](myNumbers[10]);
} catch (Exception e) {
[Link]("Something went wrong.");
} finally {
[Link]("The 'try catch' is finished.");
} }}
1 import [Link];
2
3 public class ExceptionDemo {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner([Link]);
6 [Link]("Enter an integer: ");
7 int number = [Link]();
8 If anexceptionoccurs onthis
9 line, therest of the lines inthe // Display the result
methodareskippedandthe [Link](
10
programis terminated.
11 "The number entered is " + number);
12 }
13 }
Terminated.
Example to use try...catch

To illustrate how easily this can be done, the following program includes a try block and a catch clause that processes the ArithmeticException generated by the
division-by-zero error:
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code. Output:
d = 0; This program generates the
a = 42 / d; following output:
[Link]("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
Division by zero.
[Link]("Division by zero.");
After catch statement
}
[Link]("After catch statement.");
}}
1. Prevent the exception from happening.
2. Catch it in the method in which it occurs, and either
a. Fix up the problem and resume normal execution.
b. Rethrow it.
c. Throw a different exception.
3. Declare that the method throws the exception.
4. With 1. and 2.a. the caller never knows there was an
error.
5. With 2.b., 2.c., and 3., if the caller does not handle the
exception, the program will terminate and display a
stack trace.
try
{
// Code which might throw an exception
// ...
}
catch(FileNotFoundException x)
{
// code to handle a FileNotFound exception
}
catch(IOException x)
{
// code to handle any other I/O exceptions
}
catch(Exception x)
{
// Code to catch any other type of exception
}
finally
{
// This code is ALWAYS executed whether an exception was thrown
// or not. A good place to put clean-up code. ie. close
// any open files, etc...
}
Java Catch Multiple Exceptions
Java Multi-catch block
A try block can be followed by one or more catch blocks. Each catch
block must contain a different exception handler. So, if you have to
perform different tasks at the occurrence of different exceptions, use java
multi-catch block.
Points to remember
At a time only one exception occurs and at a time only one catch block is
executed.
All catch blocks must be ordered from most specific to most general, i.e.
catch for ArithmeticException must come before catch for Exception.
Flowchart of Multi-catch Block
Multiple catch statements
/ Demonstrate multiple catch statements. catch(ArithmeticException e) {
class MultiCatch { [Link]("Divide by 0: " + e);
public static void main(String args[]) { } catch(ArrayIndexOutOfBoundsException
try { e) {
int a = [Link]; [Link]("Array index oob: " + e);
[Link]("a = " + a); }
int b = 42 / a;
Output: [Link]("After try/catch blocks.");
int c[] = { 1 }; C:\>java MultiCatch }}
c[42] = 99; a=0
Divide by 0:
} [Link]:
/ by zero
After try/catch blocks.
Java throw keyword
• The flow of execution stops immediately after the throw statement; any subsequent statements are
not executed. The nearest enclosing try block is inspected to see if it has a catch statement that
matches the type of exception. If it does find a match, control is transferred to that statement. If not,
then the next enclosing try statement is inspected, and so on. If no matching catch is found, then
the default exception handler halts the programand prints the stack trace.
• The Java throw keyword is used to throw an exception explicitly.

• We specify the exception object which is to be thrown. The Exception has some message with it
that provides the error description. These exceptions may be related to user inputs, server, etc.

• We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used
to throw a custom exception.
Demonstrate throw Example
This program gets two chances to deal with the same error. First, main( ) sets up an exception
context and then calls demoproc( ). The demoproc( ) method then sets up another exception_x0002_handling
context and immediately throws a new instance of NullPointerException, which is is caught on the next line.
The exception is then rethrown.
class ThrowDemo {
public static void main(String
static void demoproc() {
args[]) {
try {
throw new try {
NullPointerException("demo");
demoproc();
} catch(NullPointerException e) {
[Link]("Caught inside } catch(NullPointerException e) {
demoproc."); [Link]("Recaught: " +
throw e; // rethrow the exception e);
}} Resulting output:
Caught inside demoproc.
}}}
Recaught:
[Link]: demo
Vector Class in Java
·
The Vector class implements a growable array of objects. Vectors fall in legacy classes, but now it is
fully compatible with collections. It is found in [Link] package and implement the List interface, so
we can use all the methods of the List interface as shown below as follows:

 Vector implements a dynamic array which means it can grow or shrink as required. Like an
array, it contains components that can be accessed using an integer index.
 They are very similar to ArrayList, but Vector is synchronized and has some legacy methods
that the collection framework does not contain.
 It also maintains an insertion order like an ArrayList. Still, it is rarely used in a non-thread
environment as it is synchronized, and due to this, it gives a poor performance in adding, searching,
deleting, and updating its elements.
 The Iterators returned by the Vector class are fail-fast. In the case of concurrent modification,
it fails and throws the ConcurrentModificationException.
Syntax:
public class Vector<E> extends AbstractList<E> implements List<E>,
RandomAccess, Cloneable, Serializable
Here, E is the type of element.
 It extends AbstractList and implements List interfaces.
 It implements Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess
interfaces.
 The directly known subclass is Stack.
Important points regarding the Increment of vector capacity are as follows:
If the increment is specified, Vector will expand according to it in each allocation cycle. Still, if the
increment is not specified, then the vector’s capacity gets doubled in each allocation cycle. Vector
defines three protected data members:
 int capacityIncreament: Contains the increment value.
 int elementCount: Number of elements currently in vector stored in it.
 Object elementData[]: Array that holds the vector is stored in it.
Common Errors in the declaration of Vectors are as follows:
 Vector throws an IllegalArgumentException if the InitialSize of the vector defined is
negative.
 If the specified collection is null, It throws NullPointerException.

Constructors

1. Vector(): Creates a default vector of the initial capacity is 10.


Vector<E> v = new Vector<E>();
2. Vector(int size): Creates a vector whose initial capacity is specified by size.
Vector<E> v = new Vector<E>(int size);
3. Vector(int size, int incr): Creates a vector whose initial capacity is specified by size and increment
is specified by incr. It specifies the number of elements to allocate each time a vector is resized upward.
Vector<E> v = new Vector<E>(int size, int incr);
4. Vector(Collection c): Creates a vector that contains the elements of collection c.
vect
Vector<E> v = new Vector<E>(Collection c);

Methods in Vector Class

METHOD DESCRIPTION

Appends the specified element to the end of


add(E e)
this Vector.

Inserts the specified element at the specified


add(int index, E element)
position in this Vector.

Appends all of the elements in the specified


addAll(Collection<? Collection to the end of this Vector, in the
extends E> c) order that they are returned by the specified
Collection’s Iterator.

addAll(int index, Insert all of the elements in the specified


Collection into this Vector at the specified
Collection<? extends E> c)
position.

Adds the specified component to the end of


addElement(E obj)
this vector, increasing its size by one.

capacity() Returns the current capacity of this vector.


METHOD DESCRIPTION

clear() Removes all of the elements from this Vector.

clone() Returns a clone of this vector.

Returns true if this vector contains the


contains(Object o)
specified element.

Returns true if this Vector contains all of the


containsAll(Collection<?> c)
elements in the specified Collection.

Copies the components of this vector into the


copyInto(Object[] anArray)
specified array.

elementAt(int index) Returns the component at the specified index.

Returns an enumeration of the components of


elements()
this vector.

Increases the capacity of this vector, if


ensureCapacity(int necessary, to ensure that it can hold at least the
minCapacity) number of components specified by the
minimum capacity argument.

Compares the specified Object with this


equals(Object o)
Vector for equality.

Returns the first component (the item at index


firstElement()
0) of this vector.

forEach(Consumer<? Performs the given action for each element of


the Iterable until all elements have been
super E> action)
processed or the action throws an exception.

Returns the element at the specified position in


get(int index)
this Vector.

hashCode() Returns the hash code value for this Vector.

Returns the index of the first occurrence of the


indexOf(Object o) specified element in this vector,
or -1 if this vector does not contain the
METHOD DESCRIPTION

element.

Returns the index of the first occurrence of the


specified element in this vector, searching
indexOf(Object o, int index)
forwards from the index, or returns -1 if the
element is not found.

insertElementAt(E obj, int Inserts the specified object as a component in


index) this vector at the specified index.

isEmpty() Tests if this vector has no components.

Returns an iterator over the elements in this


iterator()
list in a proper sequence.

lastElement() Returns the last component of the vector.

Returns the index of the last occurrence of the


specified element in this vector,
lastIndexOf(Object o)
or -1 if this vector does not contain the
element.

Returns the index of the last occurrence of the


specified element in this vector, searching
lastIndexOf(Object o, int index)
backward from the index, or returns -1 if the
element is not found.

Returns a list iterator over the elements in this


listIterator()
list (in proper sequence).

Returns a list iterator over the elements in this


listIterator(int index) list (in proper sequence),
starting at the specified position in the list.

Removes the element at the specified position


remove(int index)
in this Vector.

Removes the first occurrence of the specified


remove(Object o) element in this Vector. If the Vector does not
contain the element, it is unchanged.
METHOD DESCRIPTION

Removes from this Vector all of its elements


removeAll(Collection<?> c)
contained in the specified Collection.

Removes all components from this vector and


removeAllElements()
sets its size to zero.

Removes the first (lowest-indexed) occurrence


removeElement(Object obj)
of the argument from this vector.

removeElementAt(int index) Deletes the component at the specified index.

removeIf(Predicate<? super E> Removes all of the elements of this collection


filter) that satisfy the given predicate.

removeRange(int fromIndex, Removes from this list all of the elements


whose index is between fromIndex, inclusive,
int toIndex)
and toIndex, exclusive.

replaceAll(UnaryOperator<E> Replaces each element of this list with the


operator) result of applying the operator to that element.

Retains only the elements in this Vector


retainAll(Collection<?> c)
contained in the specified Collection.

Replaces the element at the specified position


set(int index, E element)
in this Vector with the specified element.

Sets the component at the specified index of


setElementAt(E obj, int index)
this vector to be the specified object.

setSize(int newSize) Sets the size of this vector.

Returns the number of components in this


size()
vector.

Sorts this list according to the order induced


sort(Comparator<? super E> c)
by the specified Comparator.

Creates a late-binding and fail-fast Spliterator


spliterator()
over the elements in this list.

subList(int fromIndex, int Returns a view of the portion of this List


METHOD DESCRIPTION

toIndex) between fromIndex, inclusive, and toIndex,


exclusive.

Returns an array containing all of the elements


toArray()
in this Vector in the correct order.

Returns an array containing all of the elements


in this Vector in the correct order; the runtime
toArray(T[] a)
type of the returned array is that of the
specified array.

Returns a string representation of this Vector,


toString() containing the String representation of each
element.

Trims the capacity of this vector to be the


trimToSize()
vector’s current size.

Example:

Java
// Java Program to Demonstrate Working of Vector
// Via Creating and Using It

// Importing required classes


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

// Main class
class {

// Main driver method


public static void main(String[] args)
{
// Size of the Vector
int n = 5;

// Declaring the Vector with


// initial size n
Vector<Integer> v = new Vector<Integer>(n);

// Appending new elements at


// the end of the vector
for (int i = 1; i <= n; i++)
[Link](i);
// Printing elements
[Link](v);

// Remove element at index 3


[Link](3);

// Displaying the vector


// after deletion
[Link](v);

// iterating over vector elements


// using for loop
for (int i = 0; i < [Link](); i++)

// Printing elements one by one


[Link]([Link](i) + " ");
}
}
Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1235
Note:
 If the vector increment is not specified then it’s capacity will be doubled in every
increment cycle.
 The capacity of a vector cannot be below the size, it may equal to it.

Performing Various Operations on Vector class in Java

Let us discuss various operations on Vector class that are listed as follows:
1. Adding elements
2. Updating elements
3. Removing elements
4. Iterating over elements
Operation 1: Adding Elements
In order to add the elements to the Vector, we use the add() method. This method is overloaded to
perform multiple operations based on different parameters. They are listed below as follows:
 add(Object): This method is used to add an element at the end of the Vector.
 add(int index, Object): This method is used to add an element at a specific index in the
Vector.
Example:
// Java Program to Add Elements in Vector Class

// Importing required classes


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

// Main class
// AddElementsToVector
class GFG {

// Main driver method


public static void main(String[] arg)
{

// Case 1
// Creating a default vector
Vector v1 = new Vector();

// Adding custom elements


// using add() method
[Link](1);
[Link](2);
[Link]("geeks");
[Link]("forGeeks");
[Link](3);

// Printing the vector elements to the console


[Link]("Vector v1 is " + v1);

// Case 2
// Creating generic vector
Vector<Integer> v2 = new Vector<Integer>();

// Adding custom elements


// using add() method
[Link](1);
[Link](2);
[Link](3);

// Printing the vector elements to the console


[Link]("Vector v2 is " + v2);
}
}
Output:

Vector v1 is [1, 2, geeks, forGeeks, 3]


Vector v2 is [1, 2, 3]
Operation 2: Updating Elements
After adding the elements, if we wish to change the element, it can be done using the set() method.
Since a Vector is indexed, the element which we wish to change is referenced by the index of the
element. Therefore, this method takes an index and the updated element to be inserted at that index.
Example

Java
// Java code to change the
// elements in vector class

import [Link].*;

public class UpdatingVector {

public static void main(String args[])


{
// Creating an empty Vector
Vector<Integer> vec_tor = new Vector<Integer>();

// Use add() method to add elements in the vector


vec_tor.add(12);
vec_tor.add(23);
vec_tor.add(22);
vec_tor.add(10);
vec_tor.add(20);

// Displaying the Vector


[Link]("Vector: " + vec_tor);

// Using set() method to replace 12 with 21


[Link]("The Object that is replaced is: "
+ vec_tor.set(0, 21));

// Using set() method to replace 20 with 50


[Link]("The Object that is replaced is: "
+ vec_tor.set(4, 50));

// Displaying the modified vector


[Link]("The new Vector is:" + vec_tor);
}
}
Output
Vector: [12, 23, 22, 10, 20]
The Object that is replaced is: 12
The Object that is replaced is: 20
The new Vector is:[21, 23, 22, 10, 50]
Operation 3: Removing Elements
In order to remove an element from a Vector, we can use the remove() method. This method is
overloaded to perform multiple operations based on different parameters. They are:
 remove(Object): This method is used to remove an object from the Vector. If there are
multiple such objects, then the first occurrence of the object is removed.
 remove(int index): Since a Vector is indexed, this method takes an integer value which
simply removes the element present at that specific index in the Vector. After removing the element,
all the elements are moved to the left to fill the space and the indices of the objects are updated.
Example

Java
// Java code illustrating the removal
// of elements from vector

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

class RemovingElementsFromVector {

public static void main(String[] arg)


{

// create default vector of capacity 10


Vector v = new Vector();

// Add elements using add() method


[Link](1);
[Link](2);
[Link]("Geeks");
[Link]("forGeeks");
[Link](4);

// removing first occurrence element at 1


[Link](1);
// checking vector
[Link]("after removal: " + v);
}
}

Output:
after removal: [1, Geeks, forGeeks, 4]
Operation 4: Iterating the Vector
There are multiple ways to iterate through the Vector. The most famous ways are by using the basic for
loop in combination with a get() method to get the element at a specific index and the advanced for a
loop.
Example

// Java program to iterate the elements


// in a Vector

import [Link].*;

public class IteratingVector {

public static void main(String args[])


{
// create an instance of vector
Vector<String> v = new Vector<>();

// Add elements using add() method


[Link]("Geeks");
[Link]("Geeks");
[Link](1, "For");

// Using the Get method and the


// for loop
for (int i = 0; i < [Link](); i++) {

[Link]([Link](i) + " ");


}

[Link]();

// Using the for each loop


for (String str : v)
[Link](str + " ");
}
}
Output
Geeks For Geeks
Geeks For Geeks
Note: Do give a read to the ArrayList vs Vector class in Java to grasp it better.
In Java, the Vector class is a part of the Java Collections Framework and provides a dynamic array
implementation of the List interface. It was added in the original release of Java (Java 1.0) and provides
a number of methods for manipulating the elements of a vector, including adding, inserting, and
removing elements.

Here is a simple example that demonstrates how to use a Vector in Java:

Java
import [Link];

public class VectorExample {


public static void main(String[] args) {
// Create a new vector
Vector<Integer> v = new Vector<>(3, 2);

// Add elements to the vector


[Link](1);
[Link](2);
[Link](3);

// Insert an element at index 1


[Link](0, 1);

// Remove the element at index 2


[Link](2);

// Print the elements of the vector


for (int i : v) {
[Link](i);
}
}
}
Output
1
0
3
Note that the Vector class is synchronized, meaning that multiple threads can access the same vector
without causing problems. However, this synchronization comes at the cost of performance, so if you
don’t need to share a vector between multiple threads, it’s generally better to use an alternative class
like ArrayList which is not synchronized.

Advantages of using Vector in Java:

 Synchronization: As mentioned before, Vector is synchronized, making it safe to use in a multi-


threaded environment.
 Dynamic Size: The size of a Vector can grow or shrink dynamically as elements are added or
removed, so you don’t have to worry about setting an initial size that will accommodate all
elements.
 Legacy support: Vector has been part of Java since its inception and is still supported, so it’s a
good option if you need to work with older Java code that uses Vector.
Disadvantages of using Vector in Java:

1. Performance: The synchronization in Vector can lead to slower performance compared to


other collection classes, such as ArrayList.
2. Legacy Code: While Vector is still supported, newer Java code is often written using the
more modern collection classes, so it may be harder to find examples and support for Vector.
3. Unnecessary overhead: If you don’t need the synchronization features of Vector, using it
will add unnecessary overhead to your code.

Reference Book

A good reference book for learning about the Java Collections Framework and Vector is “Java
Collections” by Naftalin and Wadler. This book provides a comprehensive look at the Java collections
framework, including Vector, and includes many examples and exercises to help you understand how
to use these classes effectively.
Th
Course :
Paper Code:
Faculty : Dr. Shivanka
Assistant Professor
VIPS
Multithreaded

• Multithreading is a Process to execute multiple threads at the same time


without dependency of other thread called Mullltithreading .
• Java supports multithreaded programming, which allows you to write
programs that do many things simultaneously.
• A multithreaded program contains two or more parts that can run
concurrently. Each part of such a program is called a thread.
• Thread is a predefined class which is available in [Link] package.
Thread is a basic unit of CPU and is well known as for independent
[Link] enables you to write very efficient programs that
make maximum use of the CPU, because idle time can be kept to a
minimum. This is especially important for the interactive, networked
environment in which Java operates, because idle time is common.
What Kind of Applications Use
Multithreading?
• Any kind of application which has distinct tasks which
can be performed independently.
v Any application with a GUI.
v Threads dedicated to the GUI can delegate the processing of user
requests to other threads.
v The GUI remains responsive to the user even when the user's
requests are being processed.
oAny application which requires asynchronous response
ü Network based applications are ideally suited to multithreading.
Thread Support in Java

• The Java Virtual machine has its own runtime


threads.
• Used for garbage collection.
• Threads are represented by a Thread class.
• A thread object maintains the state of the thread.
• It provides control methods such as interrupt, start, sleep, yield, wait.
• When an application executes, the main method is executed by a single thread.
• If the application requires more threads, the application must
create them.
How does a Thread run?

• The thread class has a run() method.


• run() is executed when the thread's
start() method is invoked.

• The thread terminates if the run method


terminates.
• To prevent a thread from terminating,
the run method must not end.
• run methods often have an endless loop
to prevent thread termination.

• One thread starts another by calling its


start method.
• The sequence of events can be
confusing to those more familiar with a
single threaded model.
Types in Multitasking in Java
It is important to understand the difference between the two. ,It is the way of executing multiple tasks at a time executing
them concurrently over a specified period. Multitasking is done in two [Link] are two distinct types of multitasking:
1. Process-based
2. Thread-based.
Process-based multitasking :It is also called multiprocessing where each process has its address in memory, i.e., each
process allocates separate memory area.A process is, a program that is executing. Thus, process-based multitasking is the
feature that allows your computer to run two or more programs concurrently. For example, process-based multitasking enables
you to run the Java compiler at the same time that you are using a text editor. In process_x0002_based multitasking, a program
is the smallest unit of code that can be dispatched by the [Link]-based multitasking deals with the “big picture”.
Thread-based multitasking:This thread-based multitasking is also termed as multithreading where threads share the same
address [Link] thread is the smallest unit of dispatchable code. This means that a single program can perform two or more
tasks simultaneously. For instance, a text editor can format text at the same time that it is printing, as long as these two actions
are being performed by two separate threads. Thus, thread-based multitasking handles the details.
Life Cycle of a Thread in Java

• A thread goes through various stages of its life cycle. Example, first of all, a
thread is born, started its tasks, run a sequence of tasks concurrently, and then
dies. Here is the diagram of the various stages of a life cycle.
• New Thread: A new thread begins its life cycle in the new state. The process
remains in this condition until the program starts the thread.
• Runnable: As soon as the new thread starts, the thread status becomes
Runnable. At this stage, a thread is considered to execute its function or
working.
• Not Runnable: A Runnable thread when entered the time of waiting for the
state for a specific interval of time. That time, the thread is not in Runnable
condition.
• Dead / Terminated: The Runnable thread enters the end stage when it
completes its tasks.
Life Cycle of a Thread in Java
Life Cycle of a Thread in Java
Life Cycle of a Thread in Java

n New: When instance of thread is created using new operator it is in new state,
but the start() method has not been invoked on the thread yet, thread is not
eligible to run yet.

n Runnable: When start() method is called on thread it enters runnable state.


As soon as Thread enters runnable state it is eligible to run, but not running.
(Thread scheduler has not scheduled the Thread execution yet.)

n Running: Thread scheduler selects thread to go from runnable to running


state. In running state Thread starts executing by entering run() method.
Life Cycle of a Thread in Java

n Waiting/Blocked/sleeping: In this state a thread is not eligible to run.


• By calling wait() method thread go from running to waiting state. In waiting state it will wait for
other threads to release object monitor/lock. Once notify() or notifyAll() method is called object
monitor/lock becomes available and thread can again return to runnable state.
• By calling sleep() method thread go from running to sleeping state. In sleeping state it will wait for
sleep time to get over. Once specified sleep time is up thread can again return to runnable state.
• Suspend() method can be used to put thread in waiting state and resume() method is the only way
which could put thread in runnable state.
o Terminated (Dead): A thread is considered dead when its run() method completes. Once thread is
dead it cannot be started again doing so will throw runtimeException i.e.
IllegalThreadStateException. destroy() method puts thread directly into dead state.
Life Cycle of a Thread in Java
The Thread Class
• The Thread class defines several methods that help manage threads. The ones that will be used in
this chapter are shown here:
Method Meaning
getName () Obtain a thread’s name.

getPriority () Obtain a thread’s priority


isAlive() Determine if a thread is still running.
join() Wait for a thread to terminate.
run() Entry point for the thread.
sleep() Suspend a thread for a period of time.
start() Start a thread by calling its run method.

setPriority(int It changes the priority of the thread.


newpriority)
yield () It causes current thread on halt and other threads to execute.
The Main Thread

• When a Java program starts up, one thread begins running immediately.
This is usually called the main thread of your program, because it is
the one that is executed when your program begins. The main thread is
important for two reasons:
• It is the thread from which other “child” threads will be born.
• Often, it must be the last thread to finish execution because it performs
various shutdown actions.
Although the main thread is created automatically when your program is
started, it can be controlled through a Thread object.
The Main Thread Example

• you must obtain a reference to it // Controlling the main Thread.


class CurrentThreadDemo {
by calling public static void main(String args[]) {
Output:
the method currentThread( ), Thread t = [Link](); Current thread:
[Link]("Current thread: " + t); Thread[main,5,main]
which is a public static member of // change the name of the thread After name change:
Thread. Its general form is shown [Link]("My Thread"); Thread[My
Thread,5,main]
here: [Link]("After name change: " + t);
5
try {
• static Thread currentThread( ) for(int n = 5; n > 0; n--) {
4
3
• This method returns a reference [Link](n);
[Link](1000);
2
1
to the thread in which it is called }} catch (InterruptedException e) {
[Link]("Main thread interrupted");
}}}
The Main Thread Example

• Output :This displays, inorder: Current thread(Thread name,Thread


Prority,Thread Group) display three values
• the name of the thread, its priority, and the name of its group. By
default, the name of the main thread is main. Its priority is by default
is 5, which is the default value, and main is also the name of the group
of threads to which this thread belongs.
• A thread group is a data structure that controls the state of a collection
of threads as a whole. After the name of the thread is changed, t is
again output. This time, the new name of the thread is displayed.
Create a Thread by Two ways
Java defines two ways in which this can be accomplished:
• By implement the Runnable interface.
• By extend the Thread class, itself.
The following two sections look at each method, in turn.
The easiest way to create a thread is to create a class that implements
the Runnable [Link] implement Runnable, a class need only
implement a single method called run( ), which is declared like this:
• public void run( )
Running Threads
Example
Calling [Link]() does not
class Mythread implements Runnable{
public void run(){
start a thread, it is just a
[Link](“Thread Started”);} simple method call.
} Creating an object does not
class mainclass { create a thread, calling
public static void main(String args[]){
start() method creates the
Thread t = new Thread(new mythread( ));
// This is the way to instantiate a
thread
thread implementing runnable interface
[Link](); // starts the thread by running
the run method
}}
Creating a Thread using Runnable
Interface
Create a Thread by Implementing a Runnable Interface
If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface. You will need to follow
three basic steps −
Step 1
As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and
you will put your complete business logic inside this method. Following is a simple syntax of the run() method −
public void run( )
Step 2
As a second step, you will instantiate a Thread object using the following constructor −
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread.
Step 3
Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of
start() method −
void start();
• This will produce the following result −
Creating a Thread using Runnable
Interface
Inside NewThread’s constructor, a new Thread object is created by the
following
statement:
t = new Thread(this, "Demo Thread");
Passing this as the first argument indicates that you want the new thread
to call the run( ) method on this [Link], start( ) is called, which
starts the thread of execution beginning at the run( ) method. This
causes the child thread’s for loop to begin. After calling start( ),
NewThread’s constructor returns to main( ).
Creating a Thread using Runnable
Interface

[Link]("Exiting child thread.");
Create a second thread.
}}
class NewThread implements Runnable {
class ThreadDemo { Output:
Thread t;
public static void main(String args[]) { Child thread:
NewThread() { Thread[Demo
new NewThread(); // create a new thread
// Create a new, second thread Thread,5,main]
try {
t = new Thread(this, "Demo Thread"); Main Thread: 5
for(int i = 5; i > 0; i--) { Child Thread: 5
[Link]("Child thread: " + t);
[Link]("Main Thread: " + i); Child Thread: 4
[Link](); // Start the thread Main Thread: 4
[Link](1000);
} Child Thread: 3
}
// This is the entry point for the second thread. Child Thread: 2
} catch (InterruptedException e) {
Main Thread: 3
public void run() { [Link]("Main thread interrupted."); Child Thread: 1
try {for(int i = 5; i > 0; i--) { } Exiting child thread.
[Link]("Child Thread: " + i); [Link]("Main thread exiting."); Main Thread: 2
[Link](500); Main Thread: 1
}}
Main thread exiting.
}} catch (InterruptedException e) {
[Link]("Child interrupted.");}
Create a Thread by Extending a Thread Class
The second way to create a thread is to create a new class that extends Thread class using the following two
simple steps. This approach provides more flexibility in handling multiple threads created using available
methods in Thread class.
Step 1
You will need to override run( ) method available in Thread class. This method provides an entry point for the
thread and . Following is a simple syntax of run() method −

public void run( )


Step 2
Once Thread object is created, you can start it by calling start() method, which executes a call to run( ) method.
Following is a simple syntax of start() method −

void start( );
Create a Thread by Extending a Thread
Class
// Create a second thread by extending Thread [Link]("Child interrupted.");
class NewThread extends Thread { } OUTPUT:
NewThread() { [Link]("Exiting child thread."); Child thread:
// Create a new, second thread }} Thread[DemoThread,5,main]
Main Thread: 5
super("Demo Thread"); class ExtendThread {
Child Thread: 5
[Link]("Child thread: " + this); public static void main(String args[]) {
Child Thread: 4
start(); // Start the thread new NewThread(); // create a new thread Child Thread: 3
} try { Main Thread: 4
// This is the entry point for the second thread. for(int i = 5; i > 0; i--) { Child Thread: 2
public void run() { [Link]("Main Thread: " + i); Main Thread: 3
Child Thread: 1
try { [Link](1000);
Exiting child thread.
for(int i = 5; i > 0; i--) { }
Main Thread: 2
[Link]("Child Thread: " + i); } catch (InterruptedException e) { Main Thread: 1
[Link](500); [Link]("Main thread interrupted."); Main thread exiting.
} } BUILD SUCCESSFUL (total time: 5
} catch (InterruptedException e) { [Link]("Main thread exiting."); seconds)
}}
Create a Thread by Extending a Thread
Class

Notice the call to super( ) inside NewThread. This invokes the


following form of the

Here, threadName specifies the name of the thread.


Multithreading catch (InterruptedException e) {
/ Create multiple threads. OUTPUT:
[Link](name + "Interrupted");
class NewThread implements Runnable { The output from this program is shown here:
} New thread: Thread[One,5,main]
String name; // name of thread
[Link](name + " exiting."); New thread: Thread[Two,5,main]
Thread t;
}}
New thread: Thread[Three,5,main]
NewThread(String threadname) { One: 5
[Link](name + " exiting.");} } Two: 5
name = threadname; Three: 5
class MultiThreadDemo {
t = new Thread(this, name); One: 4
public static void main(String args[]) {
[Link]("New thread: " + t);
Two: 4
new NewThread("One"); // start threads Three: 4
[Link](); // Start the thread One: 3
new NewThread("Two");
} Three: 3
new NewThread("Three");
Two: 3
// This is the entry point for thread.
try { One: 2
public void run() { Three: 2
// wait for other threads to end
try { Two: 2
[Link](10000); One: 1
for(int i = 5; i > 0; i--) {
} catch (InterruptedException e) { Three: 1
[Link](name + ": " + i);
[Link]("Main thread Interrupted");
Two: 1
[Link](1000); One exiting.
} Two exiting.
} Three exiting.
[Link]("Main thread exiting.");
} Main thread exiting.
}}
Thread Priorities
Java assigns each thread a priority that concludes that how a thread will
be treated concerning others. Thread priorities are integers that specify
the relative priority of one thread with another. Thread priorities are
used for deciding when to switch from one running thread to another. It
is called a context switch.
Thread Priorities

• Every thread is assigned a priority (between 1 and 10).

• The standard mode of operation is that the scheduler executes


threads with higher priorities first.
• This simple scheduling algorithm can cause problems.
Specifically, one high priority thread can become a "CPU hog".
• A thread using vast amounts of CPU can share CPU time with
• other threads by invoking the method on itself.
Thread Priorities

 Most OS do not employ a scheduling algorithm as simple as this


one.
 Most modern OS have thread aging.
ü The more CPU a thread receives, the lower its priority
becomes.
ü The more a thread waits for the CPU, the higher its priority
becomes.
 Because of thread aging, the effect of setting a thread's
priority is dependent on the platform.
Types of Priority

In Java, a thread's priority is an integer in the range 1 to


10. The larger the integer, the higher the priority. The
thread scheduler uses this integer from each thread to
determine which one should be allowed to execute. The The getPriority() instance method
Thread class defines three types of priorities: returns the integer that represents
its priority. The setPriority()
instance method takes an integer
between 1 and 10 for changing the
thread's priority. If we pass a value
The Thread class defines these priority types as constants outside the 1-10 range, the method
with values respectively. will throw an error.
y for a new
Thread.
• class MultithreadDemo extends Thread{
public void run(){
[Link]("Thread ID: " + [Link]().getId());
[Link]("Thread Priority: " + [Link]().getPriority()); Output:
Thread ID: 12
}} Thread ID: 11
public class ThreadPriority { Thread Priority: 10
Thread Priority: 1
public static void main(String[] args){
MultithreadDemo t1=new MultithreadDemo();
MultithreadDemo t2= new MultithreadDemo();
[Link](1);//minimum Priority
[Link](Thread.MAX_PRIORITY);//Maximum priority by default 10
[Link]();
[Link](); }}
How can one thread know when another thread has ended?
Thread provides a means by which you can answer this question.
Two ways exist to determine whether a thread has finished. First, you can call isAlive( ) on the thread.
This method is defined by Thread, and its general form is shown here:
final boolean isAlive( )
The returns true if the thread upon which it is called is still running. It returns false
otherwise.
While isAlive( ) is occasionally useful, the method that you will more commonly use to wait for a
thread to finish is called , shown here:
final void join( ) throws InterruptedException
This method waits until the thread on which it is called terminates. Its name comes from the concept of
the calling thread waiting until the specified thread joins it. Additional forms of join( ) allow you to
specify a maximum amount of time that you want to wait for the specified thread to terminate.
Example Using isAlive() and join() to
wait for threads to finish.
// Using join() to wait for threads to finish. class DemoJoin {
class NewThread implements Runnable { public static void main(String args[]) {
String name; // name of thread NewThread ob1 = new NewThread("One");
Thread t; NewThread ob2 = new NewThread("Two");
NewThread(String threadname) { NewThread ob3 = new NewThread("Three");
name = threadname; [Link]("Thread One is alive: "+ [Link]());
t = new Thread(this, name); [Link]("Thread Two is alive: "+ [Link]());
[Link]("New thread: " + t); [Link]("Thread Three is alive: "+ [Link]());
[Link](); // Start the thread // wait for threads to finish
} try {
// This is the entry point for thread. [Link]("Waiting for threads to finish.");
public void run() { [Link]();
try { [Link]();
for(int i = 5; i > 0; i--) { [Link]();
[Link](name + ": " + i); } catch (InterruptedException e) {
[Link](1000); [Link]("Main thread Interrupted");
} }
} catch (InterruptedException e) { [Link]("Thread One is alive: "+ [Link]());
[Link](name + " interrupted."); [Link]("Thread Two is alive: "+ [Link]());
} [Link]("Thread Three is alive: "+ [Link]());
[Link](name + " exiting."); [Link]("Main thread exiting.");
}} }}
Output from above program is shown here. (Your output may vary One: 3
based on processor speed and task load.) Two: 3
New thread: Thread[One,5,main] Three: 3
New thread: Thread[Two,5,main] One: 2
New thread: Thread[Three,5,main] Two: 2
Thread One is alive: true Three: 2
Thread Two is alive: true One: 1
Thread Three is alive: true Two: 1
Waiting for threads to finish. Three: 1
One: 5 Two exiting.
Two: 5 Three exiting.
Three: 5 One exiting.
One: 4 Thread One is alive: false
Two: 4 Thread Two is alive: false
Three: 4 Thread Three is alive: false
Main thread exiting.
Concurrent Access to Data

 Those familiar with databases will understand that


concurrent access to data can lead to data integrity problems.
 Specifically, if two sources attempt to update the same data at

the same time, the result of the data can be undefined.


 The outcome is determined by how the scheduler
schedules the two sources.
v Since the schedulers activities cannot be predicted, the outcome
cannot be predicted
Concurrent Access to Data

• Databases deal with this mechanism through "locking“.


• If a source is going to update a table or record, it can lock
the table or record until such time that the data has been
successfully updated.
• While locked, all access is blocked except to the
source which holds the lock.
• Java has the equivalent mechanism. It is called
synchronization.
• Java has a keyword called synchronized.
Synchronization
What happen if, the threads wants to access the shared resources ?
There must be an option so that not more one thread will be able to use a
shared resource . This is achieved by a process known as synchronisation.
• Key to synchronization is the concept of the monitor (also called a
semaphore). A monitor is an object that is used as a mutually exclusive
lock or mutex.
• Only one thread can own a monitor at a given time. When one
thread owns a monitor, others have to wait for that resource.
• The simplest way to use synchronization is by declaring one or more
methods to be synchronized.
Synchronization

• Synchronization prevent data corruption.


• Synchronization allows only one thread to perform an operation on a
object at a time.
• If multiple threads require an access to an object, synchronization
helps in maintaining consistency.
Example
public class Counter{ private int count = 0; In this example, the counter tells
how many access has been made.
public int getCount()

{ return count; o If a thread is accessing


setCount and updating count
} and another thread is
accessing getCount at the
public setCount( ) same time, there will be
inconsistency in the
{
value of count.
count++;
}
}
Fixing the example
public class Counter{ private static
int count = 0; • By adding the synchronized keyword we
make sure that when one thread is in the
public synchronized int setCount method the other threads are all
getCount() in waiting state.
{
return count; • The synchronized keyword places a lock
on the object, and hence locks all the
} other methods which have the keyword
public synchoronized synchronized. The lock does not lock
setCount(int count) the methods without the keyword
synchronized and hence they are open to
{ [Link] = count; access by other threads.
}
Synchronization

• Only one thread can own a monitor at a This is the general form of the
given time. When a thread acquires a lock,
it is said to have entered the monitor.
synchronized statement:
• All other threads attempting to enter the synchronized(object) {
locked monitor will be suspended until the // statements to be synchronized
first thread exits the monitor.
• These other threads are said to be waiting }
for the monitor.
• While a thread is inside a synchronized
method, all other threads that try to call it
(or any other synchronized method) on the
same instance have to wait.
Synchronization
This example is not synchronized.
class Callme { public void run() {
void call(String msg) { [Link](msg);
[Link]("[" + msg); }}
OUTPUT:
try {[Link](1000);} catch(InterruptedException e) {
class Synch { [Hello[Sync[World]
[Link]("Interrupted");}
] {
public static void main(String args[])
[Link]("]");} }
Callme target = new Callme(); ]
class Caller implements Runnable {
Caller ob1 = new Caller(target, "Hello");
String msg;
Caller ob2 = new Caller(target, "Synchronized");
Callme target;
Thread t; Caller ob3 = new Caller(target, "World");// wait for threads
to end
public Caller(Callme targ, String s) {
try {[Link]();[Link]();[Link]();
target = targ;
} catch(InterruptedException e) {
msg = s;
t = new Thread(this);
[Link]("Interrupted");

[Link](); }}}
}
Example uses a synchronized block.
// This program uses a synchronized block. // synchronize calls to call()
class Callme { public void run() {
void call(String msg) { synchronized(target) { // synchronized block
[Link]("[" + msg); [Link](msg); Output :
[Hello]
try { }}}
[Synchronized]
[Link](1000); class Synch1 {
[World]
} catch (InterruptedException e) { public static void main(String args[]) {
[Link]("Interrupted"); Callme target = new Callme();
} Caller ob1 = new Caller(target, "Hello");
[Link]("]");} } Caller ob2 = new Caller(target, "Synchronized");
class Caller implements Runnable { Caller ob3 = new Caller(target, "World");
String msg; // wait for threads to end
Callme target; try {[Link](); [Link](); [Link]();}
Thread t; catch(InterruptedException e) {
public Caller(Callme targ, String s) { [Link]("Interrupted");} } }
target = targ;
msg = s; t = new Thread(this);[Link]();}
Interthread Communication

• The wait(), notify(), notifyAll() methods are used for interthread


communication. These are functions of Object class.

• These method are implemented as final in Object. All three method can be called only from
within a synchronized context.

• wait() tells calling thread to give up monitor and go to sleep until some other thread enters
the same monitor and call notify.

• notify() wakes up a thread that called wait() on same object.

• notifyAll() wakes up all the thread that called wait() on same object.
Interthread Communication

wait() sleep()
called from synchronised no such requirement
block
monitor is released monitor is not released
awake when notify() or not awake when notify() or
notifyAll() method is called. notifyAll() method is called
not a static method static method
wait() is generaly used on sleep() method is simply used to
condition put your thread on sleep.
Interthread Communication
The preceding examples unconditionally blocked other threads from asynchronous access
to certain methods. This use of the implicit monitors in Java objects is powerful, but you
can achieve a more subtle level of control through interprocess communication. As you will
see, this is especially easy in Java.
As discussed earlier, multithreading replaces event loop programming by dividing your
tasks into discrete, logical units. Threads also provide a secondary benefit: they do away
with polling. Polling is usually implemented by a loop that is used to check some condition
repeatedly. Once the condition is true, appropriate action is taken. This wastes CPU time.
For example, consider the classic queuing problem, where one thread is producing some
data and another is consuming it. To make the problem more interesting, suppose that the
producer has to wait until the consumer is finished before it generates more data. In a
polling system, the consumer would waste many CPU cycles while it waited for the
producer to produce.
Once the producer was finished, it would start polling, wasting more CPU cycles waiting
for the consumer to finish, and so on. Clearly, this situation is undesirable.
To avoid polling, Java includes an elegant interprocess communication mechanism via
the wait( ), notify( ), and notifyAll( ) methods.
These methods are implemented as final methods in Object, so all classes have them. All
three methods can be called only from within a synchronized context. Although
conceptually advanced from a computer science perspective, the rules for using these
methods are actually quite simple: wait( ) tells the calling thread to give up the monitor
and go to sleep until some other thread enters the same monitor and calls notify( ).
notify( ) wakes up a thread that called wait( ) on the same [Link]( ) wakes up all
the threads that called wait( ) on the same object. One of the threads will be granted access.

These methods are declared within Object, as shown here: final void wait( ) throws
InterruptedException
final void notify( ) final void notifyAll( )
Additional forms of wait( ) exist that allow you to specify a period of time to wait.
Before working through an example that illustrates interthread communication, an
important point needs to be made. Although wait( ) normally waits until notify( ) or
notifyAll( ) is called, there is a possibility that in very rare cases the waiting thread could be
awakened due to a spurious wakeup. In this case, a waiting thread resumes without notify(
) or notifyAll( ) having been called. (In essence, the thread resumes for no apparent reason.)
Because of this remote possibility, Sun recommends that calls to wait( ) should take place
within a loop that checks the condition on which the thread is waiting. The following
example shows this technique.
Let’s now work through an example that uses wait( ) and notify( ). To begin, consider the
following sample program that incorrectly implements a simple form of the producer/
consumer problem. It consists of four classes: Q, the queue that you’re trying to
synchronize; Producer, the threaded object that is producing queue entries; Consumer, the
threaded object that is consuming queue entries; and PC, the tiny class that creates the
single Q, Producer, and Consumer.

// An incorrect implementation of a producer and consumer. class Q {


int n;

synchronized int get() { [Link]("Got: " + n); return n;


}

synchronized void put(int n) { this.n = n; [Link]("Put: " + n);


}
}

class Producer implements Runnable { Q q;

Producer(Q q) { this.q = q;
new Thread(this, "Producer").start();
}

public void run() { int i = 0;

while(true) { [Link](i++);
}
}
}

class Consumer implements Runnable { Q q;

Consumer(Q q) { this.q = q;
new Thread(this, "Consumer").start();
}

public void run() { while(true) {


[Link]();
}
}
}
class PC {
public static void main(String args[]) { Q q = new Q();
new Producer(q); new Consumer(q);

[Link]("Press Control-C to stop.");


}
}
Although the put( ) and get( ) methods on Q are synchronized, nothing stops the producer
from overrunning the consumer, nor will anything stop the consumer from consuming the
same queue value twice. Thus, you get the erroneous output shown here (the exact output
will vary with processor speed and task load):
Put: 1
Got: 1
Got: 1
Got: 1
Got: 1

Got: 1
Put: 2
Put: 3
Put: 4
Put: 5
Put: 6
Put: 7
Got: 7
As you can see, after the producer put 1, the consumer started and got the same 1 five
times in a row. Then, the producer resumed and produced 2 through 7 without letting the
consumer have a chance to consume them.
The proper way to write this program in Java is to use wait( ) and notify( ) to signal in both
directions, as shown here:
// A correct implementation of a producer and consumer. class Q {
int n;
boolean valueSet = false;

synchronized int get() { while(!valueSet)


try { wait();

} catch(InterruptedException e) { [Link]("InterruptedException caught");


}
[Link]("Got: " + n); valueSet = false;
notify(); return n;
}

synchronized void put(int n) { while(valueSet)


try { wait();
} catch(InterruptedException e) { [Link]("InterruptedException caught");
}

this.n = n; valueSet = true;


[Link]("Put: " + n); notify();
}
}

class Producer implements Runnable { Q q;


Producer(Q q) { this.q = q;
new Thread(this, "Producer").start();
}

public void run() { int i = 0;

while(true) { [Link](i++);
}
}
}

class Consumer implements Runnable { Q q;

Consumer(Q q) { this.q = q;
new Thread(this, "Consumer").start();
}

public void run() { while(true) {


[Link]();
}
}
}

class PCFixed {
public static void main(String args[]) { Q q = new Q();
new Producer(q); new Consumer(q);

[Link]("Press Control-C to stop.");


}
}
Inside get( ), wait( ) is called. This causes its execution to suspend until the Producer
notifies you that some data is ready. When this happens, execution inside get( ) resumes.
After the data has been obtained, get( ) calls notify( ). This tells Producer that it is okay to
put more data in the queue. Inside put( ), wait( ) suspends execution until the Consumer
has removed the item from the queue. When execution resumes, the next item of data is
put in the queue, and notify( ) is called. This tells the Consumer that it should now remove
it.
Here is some output from this program, which shows the clean synchronous behavior:
Put: 1
Got: 1
Put: 2
Got: 2
Put: 3
Got: 3
Put: 4
Got: 4
Put: 5
Got: 5

Deadlock
A special type of error that you need to avoid that relates specifically to multitasking is
deadlock, which occurs when two threads have a circular dependency on a pair of
synchronized objects. For example, suppose one thread enters the monitor on object X and
another thread enters the monitor on object Y. If the thread in X tries to call any
synchronized method on Y, it will block as expected. However, if the thread in Y, in turn,
tries to call any synchronized method on X, the thread waits forever, because to access X, it
would have to release its own lock on Y so that the first thread could complete. Deadlock is
a difficult error to debug for two reasons:
In general, it occurs only rarely, when the two threads time-slice in just the right way.
It may involve more than two threads and two synchronized objects. (That is, deadlock can
occur through a more convoluted sequence of events than just described.)
To understand deadlock fully, it is useful to see it in action. The next example creates two
classes, A and B, with methods foo( ) and bar( ), respectively, which pause briefly before
trying to call a method in the other class. The main class, named Deadlock, creates an A
and a B instance, and then starts a second thread to set up the deadlock condition. The foo(
) and bar( ) methods use sleep( ) as a way to force the deadlock condition to occur.

// An example of deadlock. class A {


synchronized void foo(B b) {
String name = [Link]().getName(); [Link](name + " entered
[Link]");
try { [Link](1000);
} catch(Exception e) { [Link]("A Interrupted");
}

[Link](name + " trying to call [Link]()"); [Link]();


}

synchronized void last() { [Link]("Inside [Link]");


}
}
class B {
synchronized void bar(A a) {
String name = [Link]().getName(); [Link](name + " entered
[Link]");

try { [Link](1000);
} catch(Exception e) { [Link]("B Interrupted");
}

[Link](name + " trying to call [Link]()"); [Link]();


}

synchronized void last() { [Link]("Inside [Link]");


}
}

class Deadlock implements Runnable { A a = new A();


B b = new B();

Deadlock() { [Link]().setName("MainThread"); Thread t = new Thread(this,


"RacingThread"); [Link]();

[Link](b); // get lock on a in this thread. [Link]("Back in main thread");


}

public void run() {


[Link](a); // get lock on b in other thread. [Link]("Back in other thread");
}

public static void main(String args[]) { new Deadlock();


}
}
When you run this program, you will see the output shown here:
MainThread entered [Link] RacingThread entered [Link] MainThread trying to call [Link]()
RacingThread trying to call [Link]()
Because the program has deadlocked, you need to press CTRL-C to end the program. You
can see a full thread and monitor cache dump by pressing CTRL-BREAK on a PC . You will
see that RacingThread owns the monitor on b, while it is waiting for the monitor on a. At
The same time, MainThread owns a and is waiting to get b. This program will never
complete. As this example illustrates, if your multithreaded program locks up occasionally,
deadlock is one of the first conditions that you should check for.

Suspending, Resuming, and Stopping Threads


Sometimes, suspending execution of a thread is useful. For example, a separate thread can
be used to display the time of day. If the user doesn’t want a clock, then its thread can be
suspended. Whatever the case, suspending a thread is a simple matter. Once suspended,
restarting the thread is also a simple matter.
The mechanisms to suspend, stop, and resume threads differ between early versions of
Java, such as Java 1.0, and modern versions, beginning with Java 2. Although you should
use the modern approach for all new code, you still need to understand how these
operations were accomplished for earlier Java environments. For example, you may need
to update or maintain older, legacy code. You also need to understand why a change was
made. For these reasons, the next section describes the original way that the execution of a
thread was controlled, followed by a section that describes the modern approach.

Suspending, Resuming, and Stopping Threads Using Java 1.1 and Earlier
Prior to Java 2, a program used suspend( ) and resume( ), which are methods defined by
Thread, to pause and restart the execution of a thread. They have the form shown below:
final void suspend( ) final void resume( )
The following program demonstrates these methods:

// Using suspend() and resume(). class NewThread implements Runnable {


String name; // name of thread Thread t;

NewThread(String threadname) { name = threadname;


t = new Thread(this, name); [Link]("New thread: " + t); [Link](); // Start the
thread
}

// This is the entry point for thread. public void run() {


try {
for(int i = 15; i > 0; i--) { [Link](name + ": " + i); [Link](200);
}
} catch (InterruptedException e) { [Link](name + " interrupted.");
}
[Link](name + " exiting.");
}
}
class SuspendResume {
public static void main(String args[]) { NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");

try { [Link](1000); [Link]();


[Link]("Suspending thread One"); [Link](1000);
[Link](); [Link]("Resuming thread One"); [Link]();
[Link]("Suspending thread Two"); [Link](1000);
[Link](); [Link]("Resuming thread Two");
} catch (InterruptedException e) { [Link]("Main thread Interrupted");
}

// wait for threads to finish try {


[Link]("Waiting for threads to finish."); [Link]();
[Link]();
} catch (InterruptedException e) { [Link]("Main thread Interrupted");
}
[Link]("Main thread exiting.");
}
}
Sample output from this program is shown here. (Your output may differ based on
processor speed and task load.)
New thread: Thread[One,5,main] One: 15
New thread: Thread[Two,5,main]
Suspending thread One Two: 10
Two: 9
Two: 8
Two: 7
Two: 6
Resuming thread One Suspending thread Two One: 10
One: 9
One: 8
One: 7
One: 6
Resuming thread Two
Waiting for threads to finish.
Two exiting.
One exiting.
Main thread exiting.
The Thread class also defines a method called stop( ) that stops a thread. Its
signature is shown here:
final void stop( )
Once a thread has been stopped, it cannot be restarted using resume( ).
Course :
Paper Code:
Faculty : Dr. Shivanka
Assistant Professor
VIPS-TC
Applet
qWhat is Applet?
qAn applet is a Java program that can be embedded into a web page.
q It runs inside the web browser and works at client side.
q An applet is embedded in an HTML page using the APPLET or
OBJECT tag and hosted on a web server.
qApplets are used to make the website more dynamic and entertaining.
qApplets are small applications that are accessed on an Internet server,
transported over the Internet, automatically installed, and run as part
of a webdocument.
Important Funtion of Applet :

1. All applets are sub-classes (either directly or indirectly) of


[Link] class.
2. Applets are not stand-alone programs. Instead, they run within either
a web browser or an applet viewer.
3. JDK provides a standard applet viewer tool called applet viewer.
4. In general, execution of an applet does not begin at main() method.
5. Output of an applet window is not used [Link]().
Rather it is handled with various AW T m e t hods, suc h a s
drawString().
Java Applet class Hierarchy
Class Hierarchy

vimport [Link]
v import [Link]
([Link],[Link]
ainer,[Link])
v import [Link]
v import [Link]
vimport [Link]
• This applet begins with two import statements.
q The first imports the Abstract WindowToolkit (AWT) classes.
qApplets interact with the user (either directly or indirectly)
through the AWT, not through the console-based I/O classes.
qAbstract Windowing Toolkit AWT
ØEarlier versions of Java
class is one of the AWT components
qJava Foundation Classes JFC
ØExtension to Java in 1997
ØHas a collection of for enhanced GUIs
ØSwing component classes begin with
Life Cycle of Applet
Applet method
public void init () Also:
public void start () public void repaint()
public void stop () public void update (Graphics)
public void destroy () public void showStatus(String)
public void paint (Graphics) public String
getParameter(String)
Life Cycle of Applet
Life Cycle of Applet consists of four phases:

1. Applet Initialized:Objects regarding Applet get initialized in this phase. An init() method is called for the
same purpose.

2. Applet Running:Applets are embedded in a webpage. When a part of webpage which consists of applet is
shown on a screen, then applet is in Running phase. A start() method is called, which takes applet to the
Running phase.

3. Applet Stopped:When a webpage in minimized or webpage is scrolled down/up; so that, applet is


disappeared from the screen, then applet is in Stopped phase. Stop() method is called when applet is
disappeared from the screen.

4. Applet Destroyed:When you closed the webpage which consists of applet, applet is get destroyed. A
destroy() method is called when applet is destroyed.
public void init()

qThe init( ) method is the first method to be called.


qThis is where you should initialize variables.
qThis method is called only once during the run time of your applet.
qpublic void init(): is used to initialized the Applet.
qIt is invoked only once.
public void start()
q It is invoked after the init() method or browser is maximized.
q It is used to start the Applet.
qThe start( ) method is called after init( ).
q It is also called to restart an applet after it has been stopped.
qWhereas init( ) is called once—the first time an applet is loaded—
start( ) is called each time an applet’s HTML document is displayed
onscreen.
qSo, if a user leaves a web page and comes back, the applet resumes
execution at start( ).
public void stop()
qThe stop( ) method is called when a web browser leaves the HTML
document.
qWhen stop( ) is called, the applet is probably running.
qYou can use stop( ) method if the applet is doing heavy computation
that you don’t want to continue when the browser is on some other
page.
qYou can restart them when start( ) is called if the user returns to the
page.
qpublic void stop(): is used to stop the Applet. It is invoked when
Applet is stop or browser is minimized.
public void destroy()

qThe destroy( ) method is called when the environment determines that


your applet needs to be removed completely from memory.
qAt this point, you should free up any resources the applet may be
using.
qThe stop( ) method is always called before destroy.
q It is used to destroy the Applet. It is invoked only once.
qUse to explicitly release system resources (like threads).
qSystem resources are usually released automatically.
public void paint(Graphics g)
q It is used to paint the Applet. It provides Graphics class object that can be used for drawing oval, rectangle, arc etc.
q The paint( ) method is called each time your applet’s output must be redrawn. This situation can occur for several
reasons.
q paint( ) is also called when the applet begins execution.
q Whatever the cause, whenever the applet must redraw its output, paint( ) is called.
q The paint( ) method has one parameter of type Graphics. This parameter will contain the graphics context,
q which describes the graphics environment in which the applet is running. This context is used whenever output to
the applet is required.
q Needed if you do any drawing or painting other than just using standard GUI Components.
q Any painting you want to do should be done here, or in a method you call from here.
q Painting that you do in other methods may or may not happen.
q Never call call
public void repaint()
qCall when you have changed something and want your changes to
show up on the screen
is a request--it might not happen
qWhen you call Java schedules a call to
• The repaint( ) method has four forms. repaint( ) is shown here:
• void repaint( )
• This version causes the entire window to be repainted. The following version
specifies a region that will be repainted:
• void repaint(int left, int top, int width, int height)
q [Link] class
The Component class provides 1 life cycle method of applet.

q public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be used for
drawing oval, rectangle, arc etc.
Q Who is responsible to manage the life cycle of an applet?
Java Plug-in software.

Q How to run an Applet?


There are two ways to run an applet
v By html file.
v By appletViewer tool (for testing purpose).
public void paint(Graphics g)
Note: public void init(), public void start(), public void stop(), public
void destroy() methods are given by Applet class. Applet class is given
by package [Link].

One more method, public void paint(Graphics g) , is used in life cycle


of applet. It is used to redraw applet. It is given by Component class.
Component class is given by package [Link].
Simple Applet Display Methods
To output a string to an applet, use drawString( ), which is a member of
the Graphics class. Typically, it is called from within either update( ) or
paint( ).
It has the following general form:
• void drawString(String message, int x, int y)
These methods are defined by Component, and they have the following
general forms:
• void setBackground(Color newColor)
• void setForeground(Color newColor)
Applet Simple Program
Output:
//[Link]
import [Link];
import [Link];
public class Firstapplet extends Applet{

public void paint(Graphics g){


[Link]("welcome to applet",150,150);
} }
/* <applet code="[Link]" width="300"
height="300">
</applet> */
Simple Applet Display Methods
/* A simple applet that sets the foreground and // Initialize the string to be displayed.
background colors and outputs a string. */ public void start() {
import [Link].*; msg += " Inside start( ) --";
import [Link].*; }
/*<applet code="Sample" width=300 height=50> // Display msg in applet window.
</applet>*/ public void paint(Graphics g) {
public class Sample extends Applet{ msg += " Inside paint( ).";
String msg; [Link](msg, 10, 30);
// set the foreground and background colors. }}
public void init() { Output:
setBackground([Link]);
setForeground([Link]);
msg = "Inside init( ) --";
}
The HTML APPLET Tag
Syntax for Applet tag
< APPLET
ØAPPLET tag be used to start an
[CODEBASE = codebaseURL]
applet from both an HTML
document and from an applet viewer. CODE = appletFile
[ALT = alternateText]
ØAn applet viewer will execute each
[NAME = appletInstanceName]
APPLET tag that it finds in a
WIDTH = pixels HEIGHT = pixels
s e p a r a t e w i n d o w, w h i l e w e b
browsers will allow many applets on [ALIGN = alignment]
a single page. [VSPACE = pixels] [HSPACE = pixels] >
[< PARAM NAME = AttributeName VALUE =
ØSo far, we have been using only a AttributeValue>]
simplified form of the APPLET tag. [< PARAM NAME = AttributeName2 VALUE =
AttributeValue>]
. . .[HTML Displayed in the absence of Java]
</APPLET>
The HTML APPLET Tag

• CODEBASE: CODEBASE is an optional • ALT The ALT tag is an optional


attribute that specifies the base URL of the attribute used to specify a short text
applet code, which is the directory that will be message that should be displayed if
searched for the applet’s executable class file the browser recognizes the APPLET
(specified by the CODE tag). The HTML tag but can’t currently run Java
document’s URL directory is used as the applets.
CODEBASE if this attribute is not specified. • NAME:To obtain an applet by name,
• CODE CODE is a required attribute that gives use getApplet( ), which is defined
the name of the file containing your applet’s • by the AppletContext interface.
compiled .class file. This file is relative to the
code base URL of the applet, which is the • WIDTH and HEIGHT: Width and
directory that the HTML file was in or the Height are required attributes that
directory indicated by CODEBASE if set. give the size (in pixels) of the applet
display area.
Course :
Paper Code:
Faculty : Dr. Shivanka
Assistant Professor
VIPS
OBJECTIVE OF AWT
• The objectives of this chapter are:
• To discuss the classes present in the [Link] package To understand
the inheritance hierarchy of the AWT
• To outline the basic structure of GUIs
• To show how to add components to containers
• To understand how to use Layout Managers
• To understand basic graphics processing under the AWT
AWT (Abstract Windowing Toolkit)

• The AWT classes are contained in the [Link] package.


• It is one of Java’s largest packages.
• AWT is heavyweight i.e. its components are using the resources of OS.
AWT Hierarrchy chart:
AWT (Abstract Windowing Toolkit)
Components
• Component is an object having a graphical representation that can be
displayed on the screen and that can interact with the user. For
examples buttons, checkboxes, list and scrollbars of a graphical user
interface.
Container

• The Container is a component in AWT that can contain another


components like buttons, textfields,labels etc.
• The classes that extends Container class are known as container such
as Frame, Dialog and Panel.
• It has additional methods that allow other Component objects to be
nested within it. Other Container objects can be stored inside of a
Container (since they are themselves instances of Component).
• This makes for a multileveled containment system. A container is
responsible for laying out (that is, positioning) any components that it
contains.
Window

• The window is the container that have no borders and menu bars.
• It should use frame, dialog or another window for creating a window.
• The Window class creates a top-level window. A top-level window is
not contained within any other object; it sits directly on the desktop.
• You will use a subclass of Window called Frame.
Frame
• It is a subclass of Window and has a title bar, menu bar, borders, and
resizing corners.
• If you create a Frame object from within an applet, it will contain a
warning message, such as “Java Applet Window,” to the user that an
applet window has been created.
• The Frame is the container that contain title bar and can have menu
bars. It can have other components like button, textfield etc.
• When a Frame window is created by a stand-alone application rather
than an applet, a normal window is created.
Frame
ü Frame defines a top-level Window with Borders and a Menu Bar
ü Frames are more commonly used than Windows

üOnce defined, a Frame is a Container which can contain Components

üSyntax
Frame aFrame = new Frame(“Hello World”);
[Link](100,100);
[Link](10,10);
[Link](true);
Example of Frame
import [Link].*;
class First extends Frame{
First(){
Button b=new Button("click me");
[Link](30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not
visible
}
public static void main(String args[]){
First f=new First();
}}
Note The setBounds(int xaxis, int yaxis, int width, int
height) method is used in the above example that sets the
position of the awt button.
List AWT Component example
import [Link];
import [Link];
import [Link];
public class Demo extends Applet {
public void init() {
List l = new List(8, true);
[Link]("Desktop");
[Link]("Laptop");
[Link]("Tablet");
[Link]("Phone");
[Link]("Kindle");
[Link]("Screen");
[Link]("System");
add(l);
setBackground([Link]); } }
Examples of GUI based Applications

• Following are some of the examples for GUI based applications.


• Automated Teller Machine (ATM)
• Airline Ticketing System
• Information Kiosks at railway stations
• Mobile Applications
• Navigation Systems
Drawing Rectangles
qThe drawRect( ) and fillRect( ) methods display an outlined and filled rectangle, respectively.
q They are shown here:
• void drawRect(int top, int left, int width, int height)
• void fillRect(int top, int left, int width, int height)
• The upper-left corner of the rectangle is at top,left. The dimensions of the rectangle are specified
by width and height.
qTo draw a rounded rectangle, use drawRoundRect( ) or fillRoundRect( ), both shown here:
• void drawRoundRect(int top, int left, int width, int height, int xDiam, int yDiam)

• void fillRoundRect(int top, int left, int width, int height,int xDiam, int yDiam)
Example Drawing Rectangles

// Draw rectangles
import [Link].*;
import [Link].*;
/* <applet code="Rectangles" width=300 height=200> Sample output from this program is shown here:

</applet>
*/

public class Rectangles extends Applet {


public void paint(Graphics g) {
[Link](10, 10, 60, 50);
[Link](100, 10, 60, 50);
[Link](190, 10, 60, 50, 15, 15);
[Link](70, 90, 140, 100, 30, 40);
}
}
Drawing Ellipses and Circles

• To draw an ellipse, use drawOval( ). To fill an ellipse, use fillOval( ). These methods are shown here:
void drawOval(int top, int left, int width, int height)
void fillOval(int top, int left, int width, int height)
/ Draw Ellipses import [Link].*;
import [Link].*;
/*
<applet code="Ellipses" width=300 height=200>
</applet>
*/

public class Ellipses extends Applet {


public void paint(Graphics g) {
[Link](10, 10, 50, 50);
[Link](100, 10, 75, 50);}}
User Interface Elements
• UI elements : Thes are the core visual elements the user eventually
sees and interacts with. GWT provides a huge list of widely used and
common elements varying from basic to complex .
• Layouts: They define how UI elements should be organized on the
screen and provide a final look and feel to the GUI (Graphical User
Interface). This part will be covered in Layout chapter.
• Behavior: These are events which occur when the user interacts with
UI elements. This part will be covered in Event Handling .
How to Use Buttons?
public class TestButton extends Frame
{ public TestButton(String title){
super(title);
Button hw = new Button("Hello World!");
add(hw);
}
….
}

13
UNIT-III Abstract Window Toolkit
[Link]

// Displays a frame containing a single button.


// WARNING: Frame cannot be closed.
import [Link].*;
// Driver class
public class ButtonTest {
public static void main(String[] args) {
Frame f = new ButtonTestFrame("Button Test");
[Link](150, 100);
[Link](true);
}
}
// Frame class
class ButtonTestFrame extends Frame
{ public ButtonTestFrame(String
title) {
super(title);
setLayout(new FlowLayout());
add(b);b = new Button("Testing");
Button 14
}
UNIT-III} Abstract Window Toolkit
Adding Components to a Frame

Frame created by the ButtonTest


program:

Pressing the “Testing” button has no effect.


21
Abstract Window
UNIT-III Toolkit
Adding Components to a Frame
 Instead of calling setSize, the main method in
ButtonTest could have called pack:
[Link]();
 pack makes the frame just large enough to display
the components within it:

 Regardless of whether setSize or pack is called,


the user can manually resize the frame.
22
Abstract Window
UNIT-III Toolkit
Adding Components to a Frame

• It’s not necessary to have two separate classes,


(ButtonTest and ButtonTestFrame).
•  By moving the main method from ButtonTest to
ButtonTestFrame, the program could be condensed to one
class (ButtonTestFrame).

17
Abstract Window Toolkit UNIT-III
How to Use Labels?
public class TestLabel extends Frame {
public TestLabel(String title){
super(title);
Label label1 = new Label();
[Link]("Label1");
Label label2 = new Label("Label2");
[Link]([Link]);
Label label3 = new Label("Label3");

add(label1,"North");
add(label2,"Center");
add(label3,"South");
}
}

Abstract Window Toolkit UNIT-III


How to Use Checkboxes?
public class TestCheckbox extends Frame {
public TestCheckbox(String
title){ super(title);

CheckboxGroup cbg = new CheckboxGroup();


Checkbox cb1 = new Checkbox("American Express",cbg,false);
Checkbox cb2 = new Checkbox("Visa",cbg,false);
Checkbox cb3 = new Checkbox("Mastercard",cbg,true);
add(cb1,"North");
add(cb2,"Center");
add(cb3,"South");
}

}

Abstract Window Toolkit UNIT-III 25


How to Use Choices?
public class TestChoice extends Frame
{ public TestChoice(String title){
super(title);

Choice choice = new Choice();


[Link]("ichi");
[Link]("ni");
[Link]("san");
add(choice);
}

20
Abstract Window Toolkit UNIT-III
How to Use TextField & TextArea
public class TestText extends Frame
{ public TestText(String title){
super(title);

TextField textField = new TextField(20);


TextArea textArea = new TextArea(5, 20);

[Link](false);
[Link]("TextField");
[Link]("TextArea Line1 \n TextArea Line2");

add(textField,"North");
add(textArea,"South");
}

}

Abstract Window Toolkit UNIT-III


How to Use Lists?
public class TestList extends Frame
{ public TestList(String title){
super(title);
List l = new List(2, true); //prefer 2 items visible
[Link]("zero");
[Link]("uno");
[Link]("dos");
[Link]("tres");
[Link]("cuatro");
[Link]("cinco");
[Link]("seis");
[Link]("siete");
[Link]("ocho");
[Link]("nueve");
add(l);
22
}
Abstract Window Toolkit UNIT-III
How to Use Menus?
public class TestMenu extends Frame {
public TestMenu(String title){
super(title);

MenuBar mb = new MenuBar();


setMenuBar(mb);

Menu m1 = new Menu("Menu 1"); [Link](m1);


MenuItem mi1_1 = new MenuItem("Menu Item 1_1"); [Link](mi1_1);
[Link]();
MenuItem mi1_2 = new MenuItem("Menu Item 1_2"); [Link](mi1_2);

Menu m2 = new Menu("Menu 2"); // [Link](m2);


[Link](m2);
MenuItem mi2_1 = new CheckboxMenuItem("Menu Item 2_1");
[Link](mi2_1);
} 23
UNIT-III… Abstract Window Toolkit
How to Use Canvases
and Graphics Primitives?
For drawing geometric shapes, texts, and
images
An abstract class
– the extended class must override paint()
Line Oval

RoundRectangle Rectangle

Polygon Arc

Abstract Window Toolkit UNIT-III 30


drawLine(x1,y1,x2,y2)

class MyCanvas extends Canvas


{ public void paint(Graphics
g){ [Link]([Link]);
int x1 = 161, (x1,y1)
y1 = 186,
x2 = 181,
(x2,y2)
y2 = 206;

[Link](x1,y1,x2,y2);
}

Abstract Window Toolkit UNIT-III 31


fillOval(x,y,w,h) drawOval(x,y,w,h)
[Link]([Link]);
{
int x = 239,
y = 186,
w = 48,
h = 32;
[Link](x,y,w,h);
}

26
Abstract Window Toolkit UNIT-III
fillPolygon(int[] xs, int[] ys)
drawPolygon(int[] xs, int[] ys)
[Link]([Link]);
{
int xs[] = {161,161,185,209,185,161};
int ys[] = {310,334,358,334,310,310};
[Link](xs,ys,6);
}

Abstract Window Toolkit UNIT-III


fillRect(x,y,w,h)
drawRect(x,y,w,
h)
[Link]([Link]);
{
int x = 239,
y = 248,
w = 48,
h = 32;
[Link](x,y,w,h);
}

Abstract Window Toolkit UNIT-III


fillRoundRect(x,y,w,h,rw,rh)
drawRoundRect(x,y,w,h,rw,rh)
[Link]([Link]);
{
int x = 161,
y = 248,
w = 48,
h = 32,
roundW = 25,
roundH = 25;
[Link](x,y,w,h,roundW,roundH);
}

Abstract Window Toolkit UNIT-III


fillArc(x,y,w,h,sa,a)
drawArc(x,y,w,h,sa,
a)
[Link]([Link]);
{
int x = 239,
y = 310,
w = 48,
h = 48,
startAngle = 20,
angle = 90;
[Link](x,y,w,h,startAngle,angle);
}

Abstract Window Toolkit UNIT-III


drawString(s,x,
y) FontMetrics

(x,y)

Abstract Window Toolkit UNIT-III


drawString, Font, &
FontMetrics
class MyCanvas extends Canvas {

public void paint(Graphics


g){ [Link](new
Font("Dialog",0,20)); FontMetrics
fm = [Link](); int x = 100;
int y = 100;
[Link]("Hello",x,y);
y = y+[Link]();
[Link]("World",x,y);
}
}
Abstract Window Toolkit UNIT-III
drawImage(image,x,y,w,h,o
b)
Image im = [Link]().getImage(name);

[Link](im, x, y, w, h, observer);

Abstract Window Toolkit UNIT-III


drawImage
public class TestImage extends Frame {
Image im;

public TestImage(String
title){ super(title);
im = [Link]().getImage("[Link]");
if
(im==null)
{ [Link]("No
image"); [Link](0);
}
}
public void paint(Graphics
g)
{
[Link](im,0,0,[Link](this),[Link](this),this);
} …
UNIT-III}
Abstract Window Toolkit
Layout of Components

•  BorderLayout  GridLayout
– north, south, west, east & center – tabular form (rows &
•  FlowLayout columns)
– left to right & top down  GridBagLayout
•  CardLayout – tabular form(variable
– stack of panels row heights and
column widths)

Abstract Window Toolkit UNIT-III


Use Layout Managers
setLayout(new BorderLayout());
setLayout(new CardLayout(());
setLayout(new FlowLayout());
setLayout(new GridLayout(rows,columns,xgap,ygap));
Default layout managers
– Windows (Frames & Dialogs)
• BorderLayout
– Panels (Applets)
• FlowLayout
Abstract Window Toolkit UNIT-III
Border Layout (cont)
The regions of the BorderLayout are defined as follows:

North

West Center East

South

Abstract Window Toolkit UNIT-III


How to Use BorderLayout?
import [Link].*;
public class TestBorderLayout {
public static void main(String[] args){
Frame f = new Frame("TestBorderLayout");
[Link](200,200);
[Link]("North", new Button("North"));
[Link]("South", new Button("South"));
[Link]("East", new Button("East"));
[Link]("West", new Button("West"));
[Link]("Center", new Button("Center"));
[Link](true);
}
}
Abstract Window Toolkit UNIT-III
How to Use FlowLayout?
import [Link].*;
public class TestFlowLayout {
public static void main(String[]
args){ Frame f = new
Frame("TestFlowLayout");
[Link](200,200);
[Link](new FlowLayout());
[Link](new Button("Button 1"));
[Link](new Button("Button 2"));
[Link](new Button("Button 3"));
[Link](new Button("Button 4"));
[Link](new Button("Button 5"));
[Link](true);
}
Abstract Window Toolkit } UNIT-III
How to Use CardLayout?
import [Link].*;

public class TestCardLayout {


public static void main(String[]
args){ Frame f = new Frame("TestCard
Layout"); [Link](200,200);
[Link](new CardLayout());
[Link]("GraphicsPanel",new GraphicsPanel());
[Link]("LabelPanel",new LabelPanel());
[Link]("ButtonPanel",new ButtonPanel());

[Link](true);
}
Abstract Window Toolkit } UNIT-III
How to Use GridLayout?
import [Link].*;
public class TestGridLayout {
public static void main(String[]
args){ Frame f = new
Frame("TestGridLayout");
[Link](200,200);
[Link](new GridLayout(2,3));
[Link](new Button("Button 1"));
[Link](new Button("Button 2"));
[Link](new Button("Button 3"));
[Link](new Button("Button 4"));
[Link](new Button("Button 5"));
[Link](true);
}
Events
qWhat is an Event?
qAn event is an object that describes a state change in a source.

qChanging the state of an object is known as an event. For example,


click on button, dragging mouse etc. The [Link] package
provides many event classes and Listener interfaces for event handling.
qEvent Sources
qA source is an object that generates an event. This occurs when the
internal state of that object changes in some way. Sources may
generate more than one type of event.
qpublic void addTypeListener(TypeListener el)
Event Sources

public void addTypeListener(TypeListener el)


qType is the name of the event, and
q el is a reference to the event listener.
qWhen such an event occurs, the registered listener is notified.
qThis is known as unicasting the event.
qA source must also provide a method that allows a listener to
unregister an interest in a specific type of event.
qThe general form of such a method is this:
qpublic void removeTypeListener(TypeListener el)
Event Listeners

• A listener is an object that is notified when an event occurs. It has two


major requirements.
• First, it must have been registered with one or more sources to receive
notifications about specific types of event.
• Second, it must implement methods to receive and process these
notifications.
• For example, the MouseMotionListener interface defines two
methods to receive notifications when the mouse is dragged or
moved.
The ActionEvent Class

• An ActionEvent is generated when a button is pressed, a list item is


double-clicked, or a menu item is selected. The ActionEvent class
defines four integer constants that can be used to identify any
m o d i f i e r s a s s o c i a t e d w i t h a n a c t i o n e v e n t : A LT _ M A S K ,
CTRL_MASK, META_MASK, and SHIFT_MASK.
Event Classes
qAt the root of the Java event class hierarchy is EventObject, which is
in [Link]. It is the superclass for all events. Its one constructor is
shown here:
qEventObject(Object src)
qHere, src is the object that generates this event.
qEventObject contains two methods: getSource( ) and toString( ). The
getSource( ) method returns the source of the event. Its general form is
shown here:
qObject getSource( )
q toString( ) returns the string equivalent of the event.
Table:Main Event Classes in
[Link]
The ActionEvent Class

• ActionEvent has these three constructors:


qActionEvent(Object src, int type, String cmd)
qActionEvent(Object src, int type, String cmd, int modifiers)
qActionEvent(Object src, int type, String cmd, long when, int modifiers)
• src is a reference to the object that generated this event.
• The type of the event is specified by type, and its command string is cmd.
• The argument modifiers indicates which modifier keys (ALT, CTRL, META,
and/or SHIFT) were pressed when the event was generated.
• The when parameter specifies when the event occurred.
Button event
• A push button is a component that contains a label and that generates
an event when it is pressed. Push buttons are objects of type Button.
Button defines these two constructors:
• Button( ) throws HeadlessException
• Button(String str) throws HeadlessException
• The first version creates an empty button.
• The second creates a button that contains str as a label.
Example of Creating a Frame
Window in an Applet

qCreate a subclass of Frame.


qOverride any of the standard applet methods, such as init( ),
start( ), and stop( ).
qImplement the windowClosing( ) method of the WindowListener
interface, calling setVisible(false) when the window is closed.
Example of Creating a Frame Window in an Applet
• // Create a child frame window from within an applet. class MyWindowAdapter extends WindowAdapter {
import [Link].*; SampleFrame sampleFrame;
import [Link].*; import [Link].*; /* public MyWindowAdapter(SampleFrame sampleFrame)
<applet code="AppletFrame" width=300 height=50> { [Link] = sampleFrame;}
</applet> */ public void windowClosing(WindowEvent we)
// Create a subclass of Frame. { [Link](false); } }
class SampleFrame extends Frame { // Create frame window.
SampleFrame(String title) { super(title); public class AppletFrame extends Applet {
// create an object to handle window events Frame f;
MyWindowAdapter adapter = new MyWindowAdapter(this); public void init() {
// register it to receive those events f = new SampleFrame("A Frame Window");
addWindowListener(adapter); [Link](250, 250); [Link](true);}
} public void start() { [Link](true); }
public void paint(Graphics g) { public void stop() { [Link](false); }
[Link]("This is in frame window", 10, 40); public void paint(Graphics g) {
}} [Link]("This is in applet window", 10, 20); } }
Creating a Frame Window in an Applet

Output :
The following applet creates a subclass
of Frame called SampleFrame.
A window of this subclass is
instantiated within the init( ) method of
AppletFrame.
Notice that SampleFrame calls
Frame’s constructor. This causes a
standard frame window to be created
with the title passed in title. This
example overrides the applet’s start( )
and stop( ) methods so that they show
a n d h i d e t h e c h i l d w i n d o w,
respectively.
Adapter Anonymous Class
o One most important special feature provided by Java, called an adapter class.
oAdapter classes are useful when you want to receive and process only some of the events not all
that are handled by a particular event listener interface (if you have 5 event method for
particular event e.g MouseEvent but you want to implement only 1 or 2 method only) .
oFor example, the MouseMotionAdapter class has two methods,
v mouseDragged( )
v mouseMoved( )
o These are the methods defined by the MouseMotionListener interface. If you were interested in
only mouse drag events, then you could simply extend MouseMotionAdapter and override
mouseDragged( ). The empty implementation(not implemented) of mouseMoved( ) would handle
the mouse motion events for you.
Adapter Anonymous Class

• Its init( ) method creates an instance of MyMouseAdapter and


registers that object to receive notifications of mouse events. It also
creates an instance of MyMouseMotionAdapter and registers that
object to receive notifications of mouse motion events.
// Demonstrate an adapter. // Handle mouse clicked.
import [Link].*; public void mouseClicked(MouseEvent me) {
import [Link].*; [Link]("Mouse clicked");
import [Link].*; }}
/*applet code="AdapterDemo" width=300 height=100> class MyMouseMotionAdapter extends MouseMotionAdapter {
</applet>*/
AdapterDemo adapterDemo;
public class AdapterDemo extends Applet {
public MyMouseMotionAdapter(AdapterDemo adapterDemo) {
public void init() {
[Link] = adapterDemo;
addMouseListener(new MyMouseAdapter(this));
}
addMouseMotionListener(new MyMouseMotionAdapter(this));
// Handle mouse dragged.
}}
public void mouseDragged(MouseEvent me) {
class MyMouseAdapter extends MouseAdapter {
AdapterDemo adapterDemo; [Link]("Mouse dragged");

public MyMouseAdapter(AdapterDemo adapterDemo) { }}


[Link] = adapterDemo;
}
• Note :In the given example
qOutput: MouseMotionListener
and MouseListener interfaces
saves you a considerable amount
of effort and prevents your code
from becoming cluttered with
empty methods.
Anonymous Inner Classes Example

qAn anonymous inner class is // Anonymous inner class demo.


one that is not assigned a name. import [Link].*;
import [Link].*;
q Consider the applet shown in /*<applet code="AnonymousInnerClassDemo"
the following Example listing. width=200 height=100></applet>*/
Given example goal is to display public class AnonymousInnerClassDemo extends
the string “Mouse Pressed” in Applet { public void init() {
the status bar of the applet addMouseListener(new MouseAdapter() {
viewer or browser when the public void mousePressed(MouseEvent me) {
mouse is pressed. showStatus("Mouse Pressed");}
});}}
FILE HANDLING

1
Unit wise Syllabus
UNIT I:

Introduction of Object-Oriented Programming, Benefits of Object Oriented Development, Classes and


Objects, Inheritance, Polymorphism, Object- Oriented Design. Overview & characteristics of Java, Program
Compilation, Execution Process Organization of the Java Virtual Machine and security aspects, sandbox
model.
UNIT II:

Java Fundamentals, Data Types & Literals Variables, Wrapper Classes, Arrays, Arithmetic Operators, Logical
Operators, Control of Flow, Loops, Classes and Instances, Class Member Modifiers Anonymous Inner Class
Interfaces and Abstract Classes, Inheritance using java, Exception Handling. Collection API Interfaces,
Vector, stack, Hashtable, enumeration, set, List, Map, Iterators.
UNIT III:

Multithreading- Extending Thread Class, Runnable Interface, Starting Threads, Thread Synchronization. GUI
components in Java: AWT Components, Component Class, Container Class, Layout Managers, swing
package. Event Handling: AWT Events, Event, Listeners, Class Listener, Action Event Methods, Focus Event
Key Event, Mouse Event, Window Event Adapters.
UNIT IV:

Java I/O: Input/Output Streams, Readers and Writers. JDBC (Database connectivity
with MS-Access, Oracle, MS-SQL Server), Object serialization, Socket Programming, development of client
Server applications, Design of multithreaded server.
Introduction
n Storage of data in variables and arrays is temporary
n Files used for long-term retention of large amounts of
data, even after the programs that created the data
terminate
n Persistent data – exists beyond the duration of program
execution
n Files stored on secondary storage devices
n Stream – ordered data that is read from or written to a
file

3
Data Hierarchy
n Computers process all data items as combinations of
zeros and ones
n Bit – smallest data item on a computer, can have values
0 or 1
n Byte – 8 bits
n Characters – larger data item
n Consists of decimal digits, letters and special symbols
n Character set – set of all characters used to write programs
and represent data items
n Unicode – characters composed of two bytes
n ASCII

4
5
Files and Streams
n Java views each files as a sequential stream of bytes
n Operating system provides mechanism to determine end
of file
n End-of-file marker
n Count of total bytes in file
n Java program processing a stream of bytes receives an
indication from the operating system when program reaches
end of stream

6
Streams

n All modern I/O is stream-based


n A stream is a connection to a source of data or to a
destination for data (sometimes both)
n An input stream may be associated with the keyboard
n An input stream or an output stream may be
associated with a file
n Different streams have different characteristics:
n A file has a definite length, and therefore an end
n Keyboard input has no specific end

7
Types of Streams
n There are 2 kinds of streams
n character streams
n byte streams

7
Character Streams
n Character streams create text files.
n These are files designed to be read with a text editor.
n Java automatically converts its internal unicode
characters to the local machine representation (ASCII
for example).

8
Byte Streams
n Byte streams create binary files.
n A binary file essentially contains the memory
image of the data. That is, it stores bits as they are
in memory.
n Binary files are faster to read and write because no
translation need take place.
n Binary files, however, cannot be read with a text
editor.

9
Classes
n Java has 6 classes to support stream I/O
n File: An object of this class is either a file or a
directory.

n Writer: base class for character output streams.


n Reader: base class for character input streams.

n OutputStream: base class for byte output streams


n InputStream: base class for byte input streams

10
n RandomAccessFile: provides support for random access
to a file.

n Note that the classes InputStream, OutputStream,


Reader, and Writer are abstract classes.

n Three stream objects are automatically created for every


application: [Link], [Link], and [Link].

11
Many classes and interfaces in [Link] package . These include
byte and character streams and object serialiazation.
Source Code
24
25
26
Using Buffered Streams
n Buffered streams attaches memory buffer to the I /O
stream. This buffer allows java to do I/O operations on
more than a byte at a time thereby improving
performance.

n The buffered Character stream classes are


BufferedReader and BufferedWriter.

27
How to do I/O
import [Link].*;

n Open the stream to read / write to a File


n Use the stream (read, write, or both)
n Close the stream

28
File
n Class File useful for retrieving information about files
and directories from disk.
n A File object is created by passing in a String that
represents the name of a file, or a String or another File
object. For example,
n File a = new File("[Link]");

29
import [Link];

public class FileDemo {

public static void main(String[] args) {


File f = null;
String strs = "[Link]";
try {
// create new file
f = new File(s);
String a = [Link]();

// prints absolute path and length


[Link]("\n"+a);
[Link]("\nLength =" +[Link]());

} catch (Exception e) {
// if any I/O error occurs
[Link]();
}
}
}

30
open
use
Opening a stream close

n There is data external to your program that you want to


get, or you want to put data somewhere outside your
program

n When you open a stream, you are making a connection


to that external place

n Once the connection is made, you forget about the


external place and just use the stream

31
Opening a stream: to Write

FileWriter fout= new FileWriter(“[Link]");


BufferedWriter bfout = new BufferedWriter(fout);

OR
BufferedWriter bout = new BufferedWriter(new
FileWriter(“[Link]")));

32
import [Link].*;
import [Link].*;
class FileDemo {
public static void main(String[] args) {
File f = null;
try { Note:
f = new File(“[Link]"); 1. CTRL+Z to exit
FileWriter fout = new FileWriter(f);
BufferedWriter bout= new
writing to the file
BufferedWriter(fout);
Scanner sc = new Scanner([Link]); 1. Check the file
[Link]("\nEnter a String:"); contents in the
while([Link]()){
[Link]([Link]());
folder where the
[Link](); program is
} executed
[Link]();
}
catch (Exception e) {
// if any I/O error occurs
[Link]();
} } }
33
open
use
Closing close

n A stream is an expensive resource


n There is a limit on the number of streams that you can
have open at one time
n You should not have more than one stream open on
the same file
n You must close a stream before you can open it again
n Always close your streams! Java will normally close
your streams for you when your program ends, but it
isn’t good style to depend on this
[Link]()

34
BufferedWriter Methods

35
Opening a stream: to read

FileReader fin= new FileReader(“[Link]");


BufferedReader bin = new BufferedReader(fin);

OR
BufferedReader bin = new BufferedReader(new
FileReader(“[Link]")));

36
We will focus on: readLine()

37
import [Link].*;
class FileDemo {

public static void main(String[] args) {


File f = null;
try {

File f = new File("[Link]");


FileReader fin = new FileReader(f);
BufferedReader bin= new BufferedReader(fin);
String sr;
[Link]("The contents of the file are: ");
while((sr=[Link]())!=null){
[Link](sr);
}
}
catch (Exception e) {
// if any I/O error occurs
[Link]();
}
} }

38
Programming Exercise
1. Write a program that writes an Serial No.(int), First Name
(String), CGPA (float) and Grade(char) into a text file using
bufferedWriter and displays the contents using bufferedReader.
Note: bufferedWriter can only write character and String values

39
n In such cases where we want enter numeric data into a text file we make use of
wrapper classes with its toString() method. A Wrapper class is a class
whose object wraps or contains a primitive data types.
n E.g.
float f=2.5;
[Link]([Link](f)); // Float wrapper class for [Link]
//toString() methods to convert to String

Hint: Separate data values of one record by space (‘ ’): [Link](‘ ’);
Separate records by newline(): [Link]();
Read a record values in a String array
Use split( ) method of String to find different values

40
Programming Exercise
2. Write a program that finds if a word entered by user is
in the given file
// Code to check if a word “me” is in the file
boolean flag=true;
FileReader fin = new FileReader(f);
BufferedReader bin= new BufferedReader(fin);
while((s=[Link]())!=null && flag){
if([Link]("me")){
[Link]("Present");
flag=false;
}

41

You might also like