Object-Oriented Programming in Java
Object-Oriented Programming in Java
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
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
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.
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)
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).
: 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.
Java Source
javadoc HTML Files
Code
javac
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.
•void is the return type of the method, it means it doesn't return any value.
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
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.
• 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
c=a+b; [Link](c);
[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.
• 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
• 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
• 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:
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'
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:
• 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
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: -
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;
• 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
• 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
•
Declaring an array
int[] myArray;
int[] myArray = new int[5];
String[] stringArray = new String[10];
String[] strings = new String[] {“one”, “two”};
{ 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
•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.
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.
class outerClass {
Anonymous classes are typically used to extend subclasses or implement interfaces. So, there can be 2 types of
anonymous classes in Java:
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
• 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
1. Single inheritance.
2. Multi-level inheritance.
3. Multiple inheritance.
4. Hierarchical Inheritance.
5. Hybrid Inheritance.
1. 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
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:
} [Link]();
void show(); }
} Output:-
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.
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:
• 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
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
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
METHOD DESCRIPTION
element.
Example:
Java
// Java Program to Demonstrate Working of Vector
// Via Creating and Using It
// Main class
class {
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
// Main class
// AddElementsToVector
class GFG {
// Case 1
// Creating a default vector
Vector v1 = new Vector();
// Case 2
// Creating generic vector
Vector<Integer> v2 = new Vector<Integer>();
Java
// Java code to change the
// elements in vector class
import [Link].*;
Java
// Java code illustrating the removal
// of elements from vector
import [Link].*;
import [Link].*;
class RemovingElementsFromVector {
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
import [Link].*;
[Link]();
Java
import [Link];
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
• 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.
• 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
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
• 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
• 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.
• 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.
Producer(Q q) { this.q = q;
new Thread(this, "Producer").start();
}
while(true) { [Link](i++);
}
}
}
Consumer(Q q) { this.q = q;
new Thread(this, "Consumer").start();
}
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;
while(true) { [Link](i++);
}
}
}
Consumer(Q q) { this.q = q;
new Thread(this, "Consumer").start();
}
class PCFixed {
public static void main(String args[]) { Q q = new Q();
new Producer(q); new Consumer(q);
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.
try { [Link](1000);
} catch(Exception e) { [Link]("B Interrupted");
}
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:
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.
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()
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.
• 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
ü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
• 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>
*/
• 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>
*/
13
UNIT-III Abstract Window Toolkit
[Link]
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");
}
}
20
Abstract Window Toolkit UNIT-III
How to Use TextField & TextArea
public class TestText extends Frame
{ public TestText(String title){
super(title);
[Link](false);
[Link]("TextField");
[Link]("TextArea Line1 \n TextArea Line2");
add(textField,"North");
add(textArea,"South");
}
…
}
RoundRectangle Rectangle
Polygon Arc
[Link](x1,y1,x2,y2);
}
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);
}
(x,y)
[Link](im, x, y, w, h, observer);
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)
North
South
[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.
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
1
Unit wise Syllabus
UNIT I:
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
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.
10
n RandomAccessFile: provides support for random access
to a file.
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.
27
How to do I/O
import [Link].*;
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];
} catch (Exception e) {
// if any I/O error occurs
[Link]();
}
}
}
30
open
use
Opening a stream close
31
Opening a stream: to Write
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
34
BufferedWriter Methods
35
Opening a stream: to read
OR
BufferedReader bin = new BufferedReader(new
FileReader(“[Link]")));
36
We will focus on: readLine()
37
import [Link].*;
class FileDemo {
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