Java
Java
tyuiopasdfghjklzxcvbnmqwertyuio
pasdfghjklzxcvbnmqwertyuiopasd
Object Oriented
fghjklzxcvbnmqwertyuiopasdfghjkl
Programing
zxcvbnmqwertyuiopasdfghjklzxcv
T J
HROUGH AVA
bnmqwertyuiopasdfghjklzxcvbnm
qwertyuiopasdfghjklzxcvbnmqwer
UNIT - 1
tyuiopasdfghjklzxcvbnmqwertyuio
pasdfghjklzxcvbnmqwertyuiopasd
fghjklzxcvbnmqwertyuiopasdfghjkl
zxcvbnmqwertyuiopasdfghjklzxcv
bnmqwertyuiopasdfghjklzxcvbnm
qwertyuiopasdfghjklzxcvbnmqwer
tyuiopasdfghjklzxcvbnmqwertyuio
pasdfghjklzxcvbnmqwertyuiopasd
fghjklzxcvbnmrtyuiopasdfghjklzxcv
2 Object Oriented Programing
3. POP doesn’t have any proper hiding of OOP provides data hiding, so OOP having more
data, so it is less secure security
4. In POP importance is not given to data, In OOP importance is given to the data rather
it gives importance to functions than functions.
5. POP doesn’t have any access specifiers OOP has access specifiers like public, private, and
protected.
6. in POP data can move freely from one in OOP objects can move and communicate with
function to another function each other through member function
7. POP is simple to implement OOP is complex to implement
8. In POP most functions uses global data In OOP data cannot move easily from function to
for sharing that can be accessed freely function, it can be kept public, private and
from function to function protected.so we can control access of data.
9. In POP overloading is not possible in OOP overloading is possible
10. To add new data and functions in POP is OOP provides an easy way to add new data and
not so easy functions
11. Modification of a completed program is modification are easy as objects independent to
very difficult and it may affect the whole declare and define
program e.g.:-java, C++, VB.NET and C#.NET
e.g.:- C language, Pascal, Fortran.
Object
*Object is real word entity, runtime entity,
Object is an instance of a class, objects are run-time entity of the object oriented program.
Objects communicate with each other using messages, while communicating with each other it is
2
3 Object Oriented Programing
not necessary to know the details of communicating object. Thus the internal details of each
object can be hidden from another object.
Class
A class can be defined as a template or blue print that describes the behavior of the object
A class is a group of objects which have common properties .it is a logical entity, it cannot be in a
physical existence.
The class is declared using the keyword class.
A class can contain fields, methods, constructors, blocks, nested class and interface
Syntax:-
Class <class_name >
{
Fields
Methods
}
Ex:-
1) class student
{
Public static void main(String[] args)
{
System.out.println(“good student’);
}
}
3
4 Object Oriented Programing
Sending Receiving
Object Object
sending
response
request
Data Abstraction:-
Data abstraction means representing only essential features by hiding all the implementation
details (inner details).In java, class is entity used for data abstraction purpose. The methods are
defined in the class from the main function using objects. Thus only abstract representation of data
is possible by using class
Encapsulation:-
Encapsulation means the detailed implementation of a component which can be hidden from the
rest of the system.
Encapsulation means binding of data and methods together in a single entity called class. The
data inside the class is accessible by the function is the same class .it is normally not accessible
from the outside of the component.
4
5 Object Oriented Programing
HISTORY OF JAVA:-
In 1990, sun microsystem has conceived a project to develop software for consumer electronic
devices that could be controlled by a remote .This project was called stealth project. Later its
name was changed into green project.in 1991 James Gosling, Mike Sheridan, Patrick Naughton, Bill
joy focus on business development and began working on graphic system and was identified the
proper programming language for the project. Gosling thought c and c+ could be system
dependent languages. He introduced a new programming language which was completely
system independent .This language was initially called oak. Later it was changed to java.
1) Simple:-
Java is simple programming language because it follows same syntax, which is in c and c++
It omitted the difficult concept of c and c++, i.e., pointer concept, because pointer crash
programs easily, it leads to confusion for a programmer.
2) Platform Independent:-
5
6 Object Oriented Programing
A platform is a hardware or software environment in which a program runs .there are two types
of platforms software based platform .java code can be run on multiple platforms .e.g.:- windows
,Linux, Mac OS, Solaris .
Java code is compiled and converted into byte code .this byte code is a platform independent
code because it can be run on multiple platforms i.e., write once run anywhere (WORA)
3) Object Oriented:-
Java programming all OOPs features except multiple inheritance .object oriented programming
is a methodology that simplify software development and maintenance by providing some rules.
Basic concept of OOPs are:-
1) object
2) class
3) Messages and methods
4) Inheritance
5) Polymorphism
6) Data abstraction
7) Encapsulation
4) Robust:-
Robust means strong .java programs are strong and they do not crash easily like c and c++
programs .java has excellent in build exception handling features.java is good memory
management feature.
5) Secure:-
Java programs are very secure because it has no explicit pointers, java programs runs inside
virtual machine. In java virus threads can be eliminated or minimized by using java on internet.
6) Portable:-
Java is portable, we may carry the java byte code to any platform.
7) High Performance:-
The problem with interpreter inside the JVM is very slow ,because of this java programs used to
run slow ,to overcome this problem .along with the interpreter , java soft people have introduced
JIT(just in time) which enhances the speed of execution.
8) Distributed:-
We can create distributed application in java RML and URL are used for creating distributed
application .we may access files by calling the methods from any machine on the internet.
9) Multi-Threaded:-
6
7 Object Oriented Programing
A thread represents an individual process to execute a group of process .JVM uses several
threads to execute different blocks of codes, creating multiple threads is called multiple threaded.
10) Interpreted:-
Java programs are compiled to generate the byte code .This byte code can be downloaded
and interpreted in JVM .if we take any other language only an interpreter or a compiler is used to
execute the program .but in java we use both compiler and interpreter for the execution.
11) Architecture Neutral:-
There is no implementation dependent features i.e. size of primitive types is fixed .in c programming
int data type occupies 2 bytes of memory for 32 bit and 4 bytes no of memory for 64 bit. But in java
it occupies 4 bytes of memory for 32 and 64 bit of architecture.
VARIABLES IN JAVA:-
Variable is name reserved area allocated in memory. In other words ,it is a name of memory
location .In other words ,it is a name of memory location it is a combination of ‘vary + able’ that
means its value can be changed. There are three types of variables in java.
Local Variable:-
A variable which is declared inside the method is called local variable
Instance Variable:-
A variable which is declared inside the class, but outside the method is called instance variable
Static Variable:-
A variable that is declare as static variable .it cannot be local variable
E.g.:
Public class variable
{
int x=20; //instance
static int y=30; //static
void main()
{
int a=10;
}
}
Data Types :-
Data types represents the different values to be stored in the variables
In java there are two different types of data. They are
1) Primitive data type
7
8 Object Oriented Programing
. data type
. primitive
non
primitive
string and
. boolean numeric
array
.. numeric
.. integral character
8
9 Object Oriented Programing
LONG 8 BYTES
FLOAT 4 BYTES
DOUBLE 8 BYTES
BYTE 8 BYTE
Comments in Java:-
Java comments are statements that are not executed by the compiler and interpreted
.explanation about the variable, method, and program. There are 3 types of comments in java.
Single line comment - //
Multiple comment- /* */
Documentation comment- /** */
Operators
An operator is a symbol that performs an operation .an operator acts on some variables called
operands to get the desired result. Java language supports a rich set of operators
1) Arithmetic operators( +, - , * , / , % )
2) Unary operators( ++,--)
There is no difference between post increment and pre increment but the difference when we
assign to another variable the values will be changed.
e.g.:-
int a=10;
a++;
b=a++;
System.out.println(+a);
a=11
b=12
Relational operators:-
These are used to specify the relation between two operands .if relation operator is true .it gives
‘1’.if the relation is false it gives ‘0’
Operators:-
>, < , >= , <= , == , !=
Bit wise operator:-
Bit wise operator works on bits and performs, bit by bit operations.
9
10 Object Oriented Programing
Operators (&, \, ~, ^)
Assignment operators
This is used to assign, write side value to left, we cannot assign a variable to constant and constant
to constant.
Logical operator
These are used to perform logical operators to construct compound conditions (multiple
condition)
Operators
(&&,||,!)
Shift operators
Shift operators are used to perform shifting the bits in data .there are three types of shift operators
in java.
1) left shift (<<)
2) right shift (>>)
3) Zero fill right shift operator (>>>)
Left shift
This operator shifts the bits of the number towards left specified no of position. The symbol
for this operator is ‘<< ‘
E.g.;-
Public class shift
{
int x=10;
System.out.println(x<<2);
}
Output:-
40(10*2*2)
10
11 Object Oriented Programing
Ternary Operator:-
This operator is called ternary operator (? :) because it requires or performs three variables .this is
also called conditional operator.
Syntax:-
Exp 1? exp 2: exp 3
New operator:-
New operator is used to create an object to class. We know that objects are created by heap
memory by JVM dynamically.
Syntax:-
Class_name obj=new class_name();
Instance operator:-
This operator is used to test if an object belongs to a class or not. Hence instance means object
.this operator can also be used to check if object belongs to interface or not.
Member operator :-
Member operator is also called as dot operator .this operator tells about the member of a
package or class.
11
12 Object Oriented Programing
Syntax:-
Classname.Variablename;
Object.Variablename;
Package.variablename;
JVM Architecture:-
JVM means Java Virtual Machine, it is a set of software and program components .it is a virtual
computer that resides in the real computer.
Java can achieve its platform independent features using java virtual machine.
Before understanding the concept JVM. The following structure will give explanation of JVM
When we want to write a java program, we write the source code and store it in a file with
extension .java. This .java file is compiled using java compiled and a class file gets created.
This class file is actually a byte code. The name byte code is given because of the instructions of
java program.
The jvm takes byte code as input, reads it, interprets the code and executes the code.
The JVM can generate an output corresponding to the relevant operating system. This allows any
java program to execute on any platform. Hence java is known as platform independent
language.
12
13 Object Oriented Programing
Arrays
An array is indexed collection fixed size of homogenous data elements using a single memory
location. (OR)
An array is a collection of similar data type using array elements, data type of same elements can
be grouped together.
If we use bunch of variables instead of arrays ,then we have to use large no of variables
Declaring and handling of large no of variables is very inconvenient for developers
Note:-
Variable can store only one variable at a time in a single memory location.
Arrays can store multiple values sharing a single memory location.
There are 3 types of arrays in java
1) Single dimensional array
2) Two dimensional array
3) Multi-dimensional array.
13
14 Object Oriented Programing
{
int I;
int a[5]= {10, 20, 30, 40, 50}
For (i=0; i<a.length; i++)
{
System.out.println(a[i]);
}
}
}
14
15 Object Oriented Programing
}
//Addition Of Two Matrices
Public class AdditionOfMatrices
{
Public static void main(String [ ] args)
{
int a[ ][ ]={{1,2,3},{4,5,6},{7,8,9}};
int b[ ] [ ]={{1,5,9},{4,6,7},{7,9,6}};
int c[ ][ ]=new int[3][2];
for(int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
C[i][j]=a[i][j]+b[i][j];
System.out.println(c[i][j]);
}
System.out.println(“ “);
}
}
Disadvantages of Array:-
The memory size will be fixed, we cannot increase or decrease the size of the array.
In array we can store only homogeneous elements.
If you want to insert delete an element from array it is an expensive operation.
Advantages of Arrays:-
Multiple values are stored in a single memory location
Data will be stored sequentially, so that we can retrieve the data directly using array index
numbers or position.
15
16 Object Oriented Programing
Disadvantages of Inheritance
The two classes gets tightly coupled this means that we change code of parent class because
child class cannot be independent of each other.
TYPES OF INHERITANCE:-
SINGLE INHERITANCE
MULTI LEVEL INHERITANCE
MULTIPLE INHERITANCE
HYBRID INHERITANCE
Single Inheritance:-
In single inheritance there is one parent per child class .this is most common form of
inheritance.
16
17 Object Oriented Programing
E.g. program;-
Public class A
{
void m1()
{
System.out.println(“this is super class”);
}
}
Class B extends A
{
Void m2()
{
System.out.println(“this is child class “);
}
}
class mainclass
{
Public static void main(String[] args);
{
A a=new A();
B b= new B();
a.m1();
b.m2();
}
}
17
18 Object Oriented Programing
B is child class of class A as well as it is a base class of class C .This type of inheritance is called
multilevel inheritance.
E.g.:-
Public class A
{
void m1()
{
int a=10;
System.out.println(“grand parent class”);
}
}
Class B extends A
{
Void m2()
{
int b=20;
System.out.println(“parent class”);
}
}
18
19 Object Oriented Programing
Class C extends B
{
Void m3()
{
int c=30;
System.out.println(“child class’’);
}
}
Class main
{
Public static void main(String[ ] args)
{
A a=new A( );
B b=new B( );
C c=new c( );
b.m1( );
b.m2();
c.m1();
c.m2();
}
}
3) Multiple Inheritance:-
Multiple inheritance refers to the concept of one class extending or inherits more than one base
class .the inheritance the concept of one base class, the problem with multiple inheritance is that
the derived class will have to manage the dependency on two base classes
19
20 Object Oriented Programing
Note:-
Multiple inheritance is very rarely used in software projects
Using multiple inheritance leads to problems in the hierarchy .to reduce the complexity and
simplicity of language, multiple inheritance is not supported in java language.
E.g.:-
Public class A
{
void display()
{
System.out.println(“A class”);
}
}
Public class B
{
void display()
{
System.out.println(“class B”);
}
}
Class c extends A,B
{
public static void main(String[] args)
20
21 Object Oriented Programing
{
c obj=new c();
obj.display();
}
}
Hybrid Inheritance:-
Hybrid inheritance is a combination of single and multiple inheritance. A hybrid inheritance can
be achieved in java in same way as multiple inheritance.
Access Modifiers:
There are four types of access modifiers:
i) private (visible to class only).
ii) default (visible to package).
iii) protected (visible to package and subclasses).
iv) public (visible to world).
The access modifiers in Java specifies the accessibility or scope of a data member, method,
constructor, class.
21
22 Object Oriented Programing
Constructors.
Ans. It is a special type of method that is used to initialize the object.
Once we create an object it is mandatory that we should perform initialization then only that
object is in a position to respond properly. Java constructor is invoked at the time of object
creation. It constructs the values that is provides data for the object.
Rules for creating a constructor:
The constructor name and classname should be same and the constructor name should end with
a pair of simple braces. Constructor is executed automatically at the time of object creation so
that no return type is required for constructor even void also. There are two types of constructors:
Default constructor (or) no argument constructor
Parameterized constructor
Default constructor:-If a constructor doesn’t have any parameters it is called default
constructor.The JVM compiler generates a default constructor i.e. no argument
NOTE:-Every no argument constructor is not a default constructor.
Parameterized constructor:-If a constructor has one or more parameters it is called parameterized
constructor.
A constructor doesn’t have any return value.
A constructor is called and executed only once per object. This means that when we create an
object the constructor is called. When we create second object the constructor is again called
second time.
Example of default constructor:
class Student
{
int stuid;
string stuname;
double stufee;
public static void main(String[] args)
{
Student s=new Student();
System.out.println(stuid);
System.out.println(stuname);
System.out.println(stufee);
}
}
22
23 Object Oriented Programing
O/P:
0
Null
0
23
24 Object Oriented Programing
24
25 Object Oriented Programing
Student(intid,String name)
{this.id=id;
this.name=name;
}
void display()
{ System.out.println(id+” “+name);
}
public static void main(String args[])
{Student s1=new Student(10,”Ramu”);
Student s2=new Student(20,”Raju”);
s1.display();
s2.display();
}
}
O/P: 10 Ramu
20 Raju
Super keyword.
Ans.
Super keyword is a reference variable used to refer to immediate parent class object.
If you create an object for superclass we can only access the superclass members but not the
subclass members but if we create subclass object all the members of the super and sub class are
available to it.This is the reason we always create child class object in inheritance.
Sometimes the superclass members and the subclass members may have the same name .In that
case by default only subclass members are accessible.
USES OF SUPER KEYWORD:
Super is used to invoke immediate parent class object.
Super is used to invoke immediate parent class method.
Super is used to invoke immediate parent class variable.
EXAMPLE WITHOUT SUPER KEYWORD:
class Parent
{ int x=20;
void m1()
25
26 Object Oriented Programing
26
27 Object Oriented Programing
27
28 Object Oriented Programing
28
29 Object Oriented Programing
}
}
O/P:child class
NOTE: Definition of method over riding: Method overriding is a mechanism in which a subclass
inherits the methods of a superclass and sometimes the subclass modifies the implementation of
method defined in superclass.
8) JVM decides which method is to be called JVM decides which method is called
depending on the difference in the method depending on the datatype of the
signatures. object used to call the method.
Abstract class: Any class that contains any abstract method is declared as abstract class.An
abstract class is never instantiated. That is we cannot create objects for an abstract class.
Any class that has at least one abstract method has to be compulsorily declared as an abstract
class. Abstract class can contain both abstract and non-abstract methods (concrete methods).
29
30 Object Oriented Programing
Definition of abstract method: An abstract method is a method without method body.The method
will be defined or implemented by its subclass.Abstract method can never be final or static.An
abstract method is written when the same method has to perform different task depending on the
object calling it. The child class needs to override the definition of all abstract methods.
EXAMPLE 1:
abstract class parent
{ abstract void m1();
void m2()
{
System.out.println(“Parent class”);
}
}
class child extends parent
{
void m1()
{System.out.println(“child class”);
}
}
class test
{public static void main(String args[])
{
child c= new child();
c.m1();
c.m2();
}
}
O/P:child class
parent class
EXAMPLE 2:
abstract class parent
{ abstract void speed();
}
class child extends parent
{
30
31 Object Oriented Programing
void speed()
{System.out.println(“speedlimit 40”);
}
public static void main(String args[])
{
child c= new child();
c.speed();
}
}
O/p: speedlimit 40
INTERFACE
Ans. An interface in Java is a blueprint of class. It has only abstract methods. The interface in Java
is a mechanism to achieve full abstraction. By using interface we can achieve multiple inheritance
in Java. Here we use interface keyword. An interface contains only abstract methods which are all
incomplete methods. So it is not possible to create object to an interface. In this case separate
classes are created where we can implement all these methods of the interface. These classes are
known as implementation classes. An interface is a specification of method prototype. All the
methods of interface are public and abstract methods only.
Interface is implicitly abstract. You need not use abstract keyword while declaring an interface.
Interface methods are public because they should be available to third party vendor for providing
implementation. They are abstract because their implementation is left to third party vendors.
EXAMPLE:
interface it
{
void m1();
void m2();
}
class test implements it //here implements is keyword same like extends
{ void m1()
{System.out.println(“1st method class”);
}
void m2()
{System.out.println(“2nd method class”);
}
public static void main(String args[])
{
test t= new test();
31
32 Object Oriented Programing
t.m1();
t.m2();
}
}
O/P:
1st method class
2nd method class
EXAMPLE:
interface it1
{
void m1();
int x=20;
}
interface it2
{ void m1();
int x=30;
}
class test implements it1,it2
{
void m1()
{ System.out.println(“child class”);
System.out.println(it1.x);
System.out.println(it2.x);
}
public static void main(String[] args)
{test t=new test();
t.m1();
}
}
O/P:
child class
20
30
32
33 Object Oriented Programing
NOTE:
1. We cannot implement one interface from another because implementing an interface
means writing body for another methods. This cannot be done again in an interface.
Since one of the methods of the interface can have body.
2. We can write class within an interface because class can have method’s body.
7) An abstract class is written when there are An interface is written when all the features are
some common features shared by all the objects implemented differently in different objects.
8) When an abstract class is written it is the An interface is written when the programmer
responsibility of the programmer to provide its wants to leave the implementation to third
subclass. party vendor.
9) Example: Example:
public interface Drawable{
public abstract class Shape{ void draw();
public abstract void draw(); }
}
CONTROL STATEMENTS:
Control statements are the statements which are the flow of execution and provide better control
to the programmer on the flow of execution. They are useful to write better and complex
programs. The following control statements are available in Java:
33
34 Object Oriented Programing
1. if statement
2. if else statement
3. switch statement
4. while loop
5. do-while loop
6. for loop
7. break statement
8. continue statement
Syntax:
1. if(condition)
statement;
2. if(condition)
{
block of statements;
}
EXAMPLE:int a=10;
if(a<10)
System.out.println(“hello”);
System.out.println(“hai”);
O/P:hai
EXAMPLE:int a=20;
if(a<10)
{System.out.println(“hello”);
System.out.println(“hai”);
}
O/P:no output
EXAMPLE:int a=8;
if(a<10)
{System.out.println(“hello”);
System.out.println(“hai”);
}
34
35 Object Oriented Programing
O/P:hello
hai
SYNTAX:
1. if(condition)
statement;
else
statement 1;
2. if(condition)
{block of statements;
}
else
{ block of statements;
}
EXAMPLE:
i) int a=10;
if(a<10)
System.out.println(“hello”);
else
System.out.println(“hai”);
O/P: hai
ii) int a=10;
if(a<10)
{ System.out.println(“hello”);
System.out.println(“hai”);
}
else
System.out.prinln(“welcome”);
O/P:welcome
iii) int a=7;
if(a%2==0)
System.out.println(“even no.”);
else
System.out.println(“odd no.”);
O/P: odd no.
35
36 Object Oriented Programing
Nested if-else statement: When a program is having multiple if statements and else
statements it is called nested if-else statements.
SYNTAX:
if (condition)
if(condition1)
statement1;
else
statement 2;
EXAMPLE:
if(grade>40&&grade<=50)
System.out.println(“third class”);
if(garde>50&&garde<=70);
System.out.pritnln(“second class”);
if(grade>70)
System.out.println(“first class”);
Switch statement: A switch statement is used instead of nested if-else statement. It is like if-
else-if ladder statement. It is multi-branch decision statement. A switch statement tests a variable
with list of values for equivalent and each value is called a case. The case value must be a
constant. By using switch statement we can create a selection statement in multiple choices. For
this we use switch keyword. The expression of switch statement is an integer type.
SYNTAX:
switch(exp)
{ case lable1: statement;
break;
case label 2: statement ;
break;
:
:
:
36
37 Object Oriented Programing
:
default: statement ;
break;
}
EXAMPLE:
int a=10,b=20,c;
char ch;
switch(ch)
{ case 1: c=a+b;
System.out.println(c);
break;
case 2: c=a-b;
Sytem.out.println(c);
break;
default:System.out.println(“invalid choice”);
}
While loop: When we are working with while loop always prechecking will be occurred i.e. if
the condition is true only the statement block will be executed.If the condition is false it exits the
loop .”while” is a keyword.
EXAMPLE:
class WHILE
{
public static void main(String args[])
{
inti=1;
while(i<5)
{
System.out.print(“ ”+i);
i++;
37
38 Object Oriented Programing
}
}
}
O/P:1 2 3 4
inti=0;
while(i<=10)
{ if(i%2==0)
System.out.print(“ ”+i);
i++;
}
System.out.println(“”);
i=1;
while(i<10)
{ if(i%2!=0)
System.out.print(“ “+i);
i++;
}
O/P:0 2 4 6 8 10
13579
DO-WHILE LOOP: The do-while loop is like while loop but here the condition is tested at the
end of the loop. If the condition is false also at least once the statements will be executed . This is
also called exit conditional loop statement.
SYNTAX:
do
{ statement;
increment/decrement statement;
}while(statement);
EXAMPLE:
intnum=1;
do
{ System.out.println(num);
num++;
38
39 Object Oriented Programing
}while(num<5);
O/P:1 2 3 4
intnum=6;
do
{ System.out.println(num);
num++;
}while(num<5);
O/P:6
FOR LOOP:Java for loop is used to repeat execution of statements until a certain condition is
true.
O/P:2 3 4 5
Strings
String is a class in java.lang package .But In java all classes are also considered as data
types.so,we can take ‘String’ as a data type also string is an object of strig class
In java we got character arrays also,but strings are given a different treatment because of their
extensive use on internet.
Example:
=>String s = “Hello”;
Here s is a variable of the data type string
Creating Strings:
There are 3 ways to create a string in java.
39
40 Object Oriented Programing
1)We can create a string just by assigning a group of chars to a string type variable.
Example:
String s;
S=”Java”;
2)We can create an object to string class by allocating memory using new operator this is just like
creating an object to any class.
Example:
String s=s String(“Java programming”);
Here we are doing 2 things,first we are creating objects using new operator then we are storing the
string into the object.
3)Creating the string is by converting the character arrays into string
Example:
Char arr[]={‘h’,’e’,’l’,’l’,’o’};
String s=new String(arr);
In above statement all characters of an array are copied into string.If we don’t want all the
characters of an array into the string then we can also mention which class we need.
Example:
String s=new String(arr,2,3);
String Methods:
There are different kinds of string class methods used to perform on strings
1)Concat:This method concatenates(joints) two strings and returns a 3rd string as a result.
Example:
String s1=”cse”;
String s2=”2c”;
String s3=s1+s2=”cse2c”;
3)Replace:This method replaces all the occurance of characters c1 by a new char c2.
Example:
40
41 Object Oriented Programing
String s1+”cse”;
S1.replace(‘s’,’y’);
This gives the output as cye
Example:
Int a=10;
String s=String.ValueOf(a);
System.out.println(s+10);
This gives the output as 1010
41
42 Object Oriented Programing
Note:
Java String Buffer class is a thread safe i.e. multiple threads cannot access simultaneously.
1) append(): It is used to append the specified string. The append method is overloaded like
append(char),append (Boolean) etc.
Forms of Inheritance:
3. Java supports different forms of inheritance they are
1) Specialisation
2) Specification
3) Construction
4) Extension
5) Limitation
Example:
Java hierarchy of graphical component in AWT.
->component
*label
*Button
42
43 Object Oriented Programing
*Text component
-Text area
-Text field
*Check box
*Scroll bar
Each child class overrides as method inherited from a parent in order to specialize the class.
3) Construction:If a parent class is used as a source for behavior, but the child has no
“IsARelationship” to the parent then we say the child class is using inheritance for construction
Example: List class
4)Extension:If a child class is generalized or extends parent class by providing more functionality
but dosent override any method , we call it inheritance for generalization.
Example:An existing list data type that allows items to be inserted either the end and you override
the methods allowing insertion at one end inorder to create a stack.
Method description:
1)nextInt():It scans the next token as integer value.
2)nextDopuble():It reads as double value.
3)next():It reads as string value.
4)nextByte():It reads as a byte value.
5)nextLong():It reads a long value.
43
44 Object Oriented Programing
44
45 Object Oriented Programing
Unit 2 - Packages
45
46 Object Oriented Programing
SYNTAX:
package packagename;
1. package mypack;
2. package cse2c;
In above statements mypack and cse2c are package names.
ADVANTAGES OF PACKAGES:
1. The classes defined in the packages of other program can be easily reused.
2. Java package is used to characterize the classes and interfaces so that they can be easily
maintained.
3. Java package provides access protection.
4. Two classes from two different packages can have same name. By using the package
name the particular class can be referred.
5. Packages provide the complete separation between the two phases design and coding.
6. Packages hide the classes and interfaces in a separate sub-directory so that accidental
deletion of classes and interfaces will not take place.
7. A group of packages in called a library. The classes and interfaces of a package are like
books in a library and can be reused several times.
EXAMPLE:
package mypack;
public class pack1
{
int a=10,b=20;
void m1()
{ System.out.println(“sum:”+(a+b));}
}
import mypack.*;
class packtest
{ public static void main(String args[])
{ pack1 p=new pack1();
p.m1();
46
47 Object Oriented Programing
}
}
O/P:
sum:30
NOTE: Java package provide access protection, and removes naming collision.
JAVA API
47
48 Object Oriented Programing
TYPES OF PACKAGES:
Q. Explain different types of packages in Java.
Ans. There are two different types of packages in Java. They are:
I. Built-in packages/predefined packages
II. User defined packages
Built-In packages: These are the packages which are already available in java language. These
packages provide almost all necessary classes, interfaces and methods for the programmer to
perform any task in his program.
ex: java.lang,java.util,java.io,java.awt,java.swing,java.net,java.applet,java.text,java.sql,
java.times.
User-defined packages: It is like built-in packages the users of Java language can also create
their own packages. They are called user-defined packages. User-defined packages can also be
imported into other classes and used exactly in the same way as built-in packages.
ex: package packagename;
import keyword.
Ans. If a class wants to use another class in the same package, the package name need not be
used.
Classes in the same package find each other without any special syntax using import keyword. A
class file can contain any number of import statements. The import statement must appear after
the package statement and before the class declaration.
Import keyword is used to import built-in packages and user-defined packages into your Java
source file.
Explain classpath.
Ans. Class path is a parameter in the JVM or the compiler that specifies the location of
user-defined classes and packages. The parameter may be set either on the
command line or through an environment variable. It is an environment variable which
contains the path for the default working directory. The specific location that Java
compiler will consider, as the route of any package hierarchy is controlled by
classpath.
Stream
Ans. A stream is basically a channel on which the data flows from sender to receiver. Different
streams are needed to send or receive data through different sources such as to receive data
from keyboard we need a stream and to send data to a file we need another stream. Without
streams it is not possible to move data in Java .An input object that reads the stream of data from
48
49 Object Oriented Programing
file is called input stream. The output object that writes the stream of data to a file is called output
stream.
In java, 3 streams are created for us automatically. All these streams are attached with console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Types Of Streams :
I) Byte stream
II) Character stream.
Bytestream: The bytestream is used to input or output the bytes. There are two superclasses in
bytestream. Those are:
i) InputStream
ii) OutputStream
From which most of other classes are derived. There are two important methods such as read() and
write(). There are different input stream classes:
InputStream
Java application uses an input stream to read data from a source, it may be a file, an array,
peripheral device or socket.
InputStream class
InputStream class is an abstract class. It is the super class of all classes representing an input stream
of bytes.
49
50 Object Oriented Programing
Declaration
Let's see the declaration for java.io.FileInputStream class:
public class FileInputStream extends InputStream
Methods
Method Description
int available() It is used to return the estimated number of bytes that can
be read from the input stream.
int read() It is used to read the byte of data from the input stream.
protected void It is used to ensure that the close method is call when there
finalize() is no more reference to the file input stream.
void close() It is used to closes the stream.
50
51 Object Oriented Programing
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Note: Before running the code, a text file named as "testout.txt" is required to be created. In this file,
we are having following content:
Welcome to java.
After executing the above program, you will get a single character from the file which is 87 (in byte
form). To see the text, you need to convert it into character.
Output:
W
Example 2: Reading all characters
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Output:
51
52 Object Oriented Programing
Welcome to java
Declaration
Let's see the declaration for java.io.DataInputStream class:
public class DataInputStream extends FilterInputStream implements DataInput
Methods
Method Description
int read(byte[] b) It is used to read the number of bytes from the input
stream.
int read(byte[] b, int off, int It is used to read len bytes of data from the input
len) stream.
int readInt() It is used to read input bytes and return an int value.
byte readByte() It is used to read and return the one input byte.
char readChar() It is used to read two input bytes and returns a char
value.
double readDouble() It is used to read eight input bytes and returns a
double value.
boolean readBoolean() It is used to read one input byte and return true if
byte is non zero, false if byte is zero.
int skipBytes(int x) It is used to skip over x bytes of data from the input
stream.
String readUTF() It is used to read a string that has been encoded
using the UTF-8 format.
void readFully(byte[] b) It is used to read bytes from the input stream and
store them into the buffer array.
void readFully(byte[] b, int It is used to read len bytes from the input stream.
off, int len)
Example
In this example, we are reading the data from the file testout.txt file.
import java.io.*;
52
53 Object Oriented Programing
inst.read(ary);
for (byte bt : ary) {
System.out.print(k+"-");
}
}
}
Here, we are assuming that you have following data in "testout.txt" file:
JAVA
Output:
J-A-V-A
OutputStream
Java application uses an output stream to write data to a destination, it may be a file, an array,
peripheral device or socket.
53
54 Object Oriented Programing
OutputStream class
OutputStream class is an abstract class. It is the super class of all classes representing an output
stream of bytes. An output stream accepts output bytes and sends them to some sink.
Declaration
Let's see the declaration for Java.io.FileOutputStream class:
1. public class FileOutputStream extends OutputStream
Methods
Method Description
protected void finalize() It is sued to clean up the connection with the file output
stream.
void write(byte[] ary) It is used to write ary.length bytes from the byte array
to the file output stream.
void write(byte[] ary, int It is used to write len bytes from the byte array starting
off, int len) at offset off to the file output stream.
void write(int b) It is used to write the specified byte to the file output
stream.
FileChannel It is used to return the file channel object associated with
getChannel() the file output stream.
FileDescriptor getFD() It is used to return the file descriptor associated with the
stream.
54
55 Object Oriented Programing
try{
testout.txt
A
try{
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
55
56 Object Oriented Programing
}
Output:
Success...
The content of a text file testout.txt is set with the data
Welcome to java.
testout.txt
Welcome to java.
Declaration
Let's see the declaration for java.io.DataOutputStream class:
public class DataOutputStream extends FilterOutputStream implements DataOutput
Methods
Method Description
int size() It is used to return the number of bytes written to the
data output stream.
void write(int b) It is used to write the specified byte to the underlying
output stream.
void write(byte[] b, int off, It is used to write len bytes of data to the output
int len) stream.
void writeBoolean(boolean v) It is used to write Boolean to the output stream as a
1-byte value.
void writeChar(int v) It is used to write char to the output stream as a 2-
byte value.
void writeChars(String s) It is used to write string to the output stream as a
sequence of characters.
void writeByte(int v) It is used to write a byte to the output stream as a 1-
byte value.
void writeBytes(String s) It is used to write string to the output stream as a
sequence of bytes.
void writeInt(int v) It is used to write an int to the output stream
56
57 Object Oriented Programing
void writeUTF(String str) It is used to write a string to the output stream using
UTF-8 encoding in portable manner.
void flush() It is used to flushes the data output stream.
Example
In this example, we are writing the data to a text file testout.txt using DataOutputStream class.
import java.io.*;
57
58 Object Oriented Programing
There are two super classes used in Byte There are two super classes used in
stream those are InputStream and Character Stream those are Reader and
OutputStream. Writer.
Syntax:
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
The InputStreamReader converts bytes into characters.
READING CHARACTERS:
To read a character from BufferedReader use read() method. Each time the read is called it reads
a character from the input stream and returns it as an integer value. It return -1 when the end of
stream is encountered it can throw an IOException .
READING STRING:
The readline() method is used to read strings from BufferedReader class.
file input stream and output stream.
Serialization in Java.
Ans. The process of converting an object from normal Java support form into file supported form or
network supported form is called serialization.
The process of saving state of object into file is called serialization.
58
59 Object Oriented Programing
SERIALIZATION
Java
support File/network
form support form
Deserialization: The process of reading an object from file is called deserialization or the process
of converting file or network support form into Java support form is called deserialization.
For serialization we use FileOutputStream class and ObjectOutputStream class.
For deserialization we use FileInputStream class and ObjectInputStream class.
Create ObjectOutputStream class is used to writeObject method. It takes object and converts it
into binary data.
Create ObjectInputStream is used to readObject method. It takes object from file.
Ex: class Student
{
int i=10;
int j=20;
}
class Serialization
{ public static void main(String args[])
{ Student s=new Student ();
FileOutputStream fos=new FileOutputStream(“abc.txt”);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(s);
FileIntputStream fis=new FileInputStream(“abc.txt”);
ObjectInputStream ois=new ObjectInputStream(fis);
Student s2= ( Student).ois.readObject();
System.out.println(s2.i);
System.out.println(s2.j);
59
60 Object Oriented Programing
}
}
SERIALIZATION
i=10
File/network
j=20 support
form
i=10
j=20 DESERIALIZATION
Q. Explain enum.
Ans. An enumeration is a list of named constants under a singlename. Enumeration defines
classtype. By making enumerations into classes, the capabilities of enumeration are greatly
expanded. An enumeration is created using enum keyword.
NOTE: If you want to represent a group of named constants then we should go for enum, to define
our own datatypes we use enumerated datatypes.
Enum is a part of every programming language but it is in Java programming language because it
allows constants,variables and methods, constructors.
ex:
i)enum Day
{ Sunday,Monday,Tuesday
}
ii) enum color
{ red,white ,blue
}
In above syntax red,white,blue are identifiers which are called enumeration constants. Each one is
declared as public static and final member of color. Once defined enumeration we can create a
variable of that type however eventhough enumerations define a class type , you don’t instantiate
enum using new. Instead we declare and use enum variable in the same way as we do one of the
primitive types
Day d;
color cr;
Here d,cr variables of enumeration type Day,color.
60
61 Object Oriented Programing
example 1:
class Color
{ red,blue, white
}
class EnumDemo
{ public static void main(String args[])
{ Color cr;
cr=Color.blue;
System.out.println(cr);
}
}
O/P: blue
Values() and ValueOf():These two methods are used in enumeration automatically .The Values()
method returns an array that contains a list of enumeration constants.
The ValueOf() method returns the enumeration constant whose value corresponds to the string
passed in str in both cases enum type is the type of enumeration.
Syntax:
public static enum_type[] Values();
public static enum_type ValueOf(String str);
example:
class EnumExample
{ public class enum Day
{ Monday,Tuesday,Wednesday,Sunday
}
public static void main(String args[])
{ for(Day d: Day.values())
System.out.println(d);
}
}
O/P: Monday
Tuesday
Wednesday
61
62 Object Oriented Programing
Sunday
NOTE: enum does not support extended by other parent class and not extends to child class
because multiple inheritance is not possible in Java language and we cannot create an object of
enum. The enum is child class of java.lang.Enum class.
Wrapper class.
Ans. A wrapper class is a class whose objects wraps or contains primitive datatype. When we
create an object to a wrapper class it contains a field. In this field we can store primitive datatype.
The advantage or objective of wrapper class is it convert primitive datatype into objects. The
classes in java.util package handle only objects and hence wrapper classes help in this case.
Generics in Java
Ans. The main objective of generics are to provide type safety and resolve type casting problems.
A generic class represents a class that is typesafe. This means a generic class can act upon any
datatype .when a generic class or generic interface is written the programmer need not rewrite
the same class or interface whenever he wants to use the class within a new datatype. before
generics we can store any type of objects in collection i.e. non-generic.
Now in generics we can store only a specific type of objects. There are three main advantages of
generics:
i) Type safety: We can hold only a single type of objects in generics . It doesn’t allow to
store other objects. ex:arrays.
62
63 Object Oriented Programing
Syntax
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
63
64 Object Oriented Programing
Type Description
Member Inner A class created within class and outside method.
Class
Anonymous Inner A class created for implementing interface or extending class. Its
Class name is decided by the java compiler.
Local Inner Class A class created within method.
Static Nested A static class created within class.
Class
Nested Interface An interface created within class or interface
Syntax:
class Outer{
//code
class Inner{
//code
}
}
Example
In this example, we are creating msg() method in member inner class that is accessing the private
data member of outer class.
class TestMemberOuter1{
64
65 Object Oriented Programing
class Inner{
}
public static void main(String args[]){
Output:
data is 30
}
class TestAnonymousInner{
};
p.eat();
}
65
66 Object Oriented Programing
}
Output:
nice fruits
1. A class is created but its name is decided by the compiler which extends the Person class
and provides the implementation of the eat() method.
66
67 Object Oriented Programing
1. A class is created but its name is decided by the compiler which implements the Eatable
interface and provides the implementation of the eat() method.
Example
1. public class localInner1{
2. private int data=30;//instance variable
3. void display(){
4. class Local{
5. void msg(){System.out.println(data);}
6. }
7. Local l=new Local();
8. l.msg();
9. }
10. public static void main(String args[]){
67
68 Object Oriented Programing
1. import java.io.PrintStream;
2. class localInner1$Local
3. {
4. final localInner1 this$0;
5. localInner1$Local()
6. {
7. super();
8. this$0 = Simple.this;
9. }
10. void msg()
11. {
12. System.out.println(localInner1.access$000(localInner1.this));
13. }
14. }
68
69 Object Oriented Programing
5. class Local{
6. void msg(){System.out.println(value);}
7. }
8. Local l=new Local();
9. l.msg();
10. }
11. public static void main(String args[]){
12. localInner2 obj=new localInner2();
13. obj.display();
14. }
15. }
Output:
50
69
70 Object Oriented Programing
1. class TestOuter2{
2. static int data=30;
3. static class Inner{
4. static void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestOuter2.Inner.msg();//no need to create the instance of static nested class
8. }
9. }
Output:
data is 30
70
71 Object Oriented Programing
71
72 Object Oriented Programing
NOTE: If an exception is raised which has not been handled by the programmer then program
execution gets terminated and system generates a non-user friendly error-message.
ADVANTAGES:
1. Exception handling allows to control the normal flow of program by using exception handling in
program.
2. Exception handling in java is to continue program execution after an exception is caught and
handled.
72
73 Object Oriented Programing
3. It throws an exception whenever a calling method encounters an error providing that the calling
method takes care of that error.
4. It also gives us the scope of organizing and differentiating between different blocks of codes.
5. Propagating errors of the call stack.
i) Checked exception
ii) Unchecked exception
i) Checked exception: the exceptions that are checked at compile-time by java compiler
are called checked exceptions. All exceptions other than runtime exceptions are known
as checked exceptions. These exceptions cannot simply be ignored at the time of
compilation the programmer should take care of handling these exceptions.
Ex: a file that needs to be opened is not found. These type of exceptions must be checked at
compile time.
Ex: import java.io.File;
importjava.io.FileReader;
public class FileNotFoundDemo
{
public static void main(String args[])
{
File f=new File(“abc.txt”);
FileReaderfr=new FileReader(f);
}
}
ii) Unchecked exception: the exceptions that are checked by the JVM are called
unchecked exceptions. Unchecked exceptions and errors are considered to be
unrecoverable and the programmer cannot do anything when the unchecked
exceptions occur in our program. The programmer can write a java program with
unchecked exceptions and compile the program he can see their effect only when he
runs/executes the program. The unchecked exceptions include programming hubs such
as logic errors or improper use of an API finally runtime exceptions are ignored at the
time of compilation.
73
74 Object Oriented Programing
NOTE:
i. Throwable class is a class that represents all errors and exceptions which may occur in java.
ii. The exception is the superclass of Exceptions in java.
iii. An exception is an error which can be handled. It means when an exception happens the
programmer can do something to avoid any harmful data, but an error is an error which
cannot be handled. It happens and programmer cannot do anything
74
75 Object Oriented Programing
Object
Throwable
Exception Error
Virtual
Runtime SQL I/O Machine Assertion
Error
75
76 Object Oriented Programing
Syntax:
try
{//statements may cause exception/risk code
}
catch block:
1. Java catch block is used to handle the exception. It must be used after the try block only. We
can use multiple catch block with a single try block.
2. We can catch different exceptions in different catch blocks when an exception occurs in try
blocks the corresponding catch block that handles that particular exception executes.
Ex:
public class Testrycatch
{
public static void main(String args[])
{
int x=100/0;
System.out.println(“rest of programming code”);
}
}
O/P: exception in thread main java.lang.ArithmeticException: / by zero
Therefore, in the above program the rest of program code not executed.
Solutionof above program:
public class Testtrycatch
{
public static void main(String args[])
{
try
{
int x=100/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
76
77 Object Oriented Programing
}
System.out.println(“rest of code”);
}
}
Exception
Causing •Try Block
Exception
• Catch
handling
statements
Block
Ex:
class Example
{
public static void main(String args[])
{
try
{
intarr[]={10,20};
77
78 Object Oriented Programing
arr[3]=30/0;
}
catch(ArithemticException ar)
{
System.out.println(“division by zero”);
}
catch(ArrayIndexOutOfBOundsException e)
{
System.out.println(“Array Index exception”);
}
}
}
O/P:division by zero
Syntax:
try
{
//risk/exception code
}
catch(exceptiontype e)
{ //exception;
}
catch(exceptiontype e)
{// exception;
}
NOTE:
1. Although both ArrayIndexOutOfBoundsExceptionand ArithemticException occurred, but
since first catch is of ArithmeticException it will be caught there and program control will be
continued after the catch block.
2. At a time, only one exception is processed, and only one respective catch block is
executed.
Ex 2:
classExample
{
78
79 Object Oriented Programing
Ex 3:
class Example
{
public static void main(String args[])
{
try
{
intarr[]={10,20};
arr[3]=30/0;
System.out.println(“first statement”);
}
79
80 Object Oriented Programing
catch(ArithemticException ar)
{
System.out.println(“division by zero”);
}
catch(ArrayIndexOutOfBOundsException e)
{
System.out.println(“Array Index exception”);
}
catch(Exception e)
{
System.out.println(“ some other exception”);
}
System.out.println(“out of try catch block”);
}
}
O/P: first statement
division by zero
out of try catch block
In above program there are multiple catch blocks and these catch blocks executes sequentially
when an exception occurs in try block which means if you put the last catch bock at the first place
just after the try block then in case of any exception this block will execute because it can handle
all exceptions.
Ex:
classExampleNestedtry
{
public static void main(String args[])
{
try
80
81 Object Oriented Programing
{
intarr[]={1,2,3,4,5};
try
{
int x=arr[3]/arr[1];
}
catch(ArithemeticException ar)
{
System.out.println(“division by zero”);
}
arr[5]=3;
}
catch(ArrayIndexOutofBoundsException e)
{
System.out.println(“array index exception”);
}
}
}
O/P: divison by zero
array index exception
Finally block:
1. finally is a block always associated with try catch to maintain clean-up code.
2. Sometimes because of execution try block the execution breakoff and due to
this some important code may not get executed that means sometimes try bloc
may bring some unwanted things to happen.
3. The finally provides the assurance of execution of some important code that
must be executed after try block.
4. Even though there is any exception in try block the statements assured by finally
block are sure to execute.
5. These statements are sometimes called as clean-up code.
Syntax:
finally
{//clean-up code
81
82 Object Oriented Programing
}
6. Java finally block is always executed whether exception is handled/not.
Ex:
classFinallyEx
{
public static void main(String args[])
{ int a=20,b=-1;
try
{ b=a/0;
}
catch(ArithmeticExeption e)
{
System.out.println(e);
}
finally
{
if(b!=1)
{
System.out.println(“without exception”);
}
else
System.out.println(“exception”);
}
}
}
O/P: in catch block: java.lang.ArithmeticException : / by zero
Exception
Throws keyword:
1. We can use to delegate responsibility of exception handling to the caller (it
maybe method or JVM)
82
83 Object Oriented Programing
2. It is required only for checked exception and usage of throws keyword for
unchecked exception there is no use.
3. It is required only for convenience of compiler and usage of throws does not
prevent abnormal termination of program.
83
84 Object Oriented Programing
Throw keyword:
1. Java throw keyword is used to explicitly throw an exception. we can throw
either checked/unchecked exception in java by throw keyword. the throw
keyword is mainly used throw custom exception.
Syntax:
throw exception;
ex: class Throwex
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException (“not valid voter”);
else
System.out.println(“welcome to vote”);
}
public static void main(String args[])
{
validate(13);
System.out.println(“rest of code”);
}
}
O/P: exception in thread main java.lang.ArithmeticException : not valid voter.
NOTE: sometimes we can create exception object explicitly we can handover to
JVM manually, for this we have to use throw keyword.
RETHROWING EXCEPTION
Sometimes the exception which is just caught need to be throw again. Since we
have already the reference to the current exception we can simply re-throw
that reference.
Ex:
class A
{
public static void main(String args[]) throws ArithmeticException
{
try
{
int a=30,b=0;
int c=a/b;
}
catch(ArithmeticException e)
84
85 Object Oriented Programing
{
System.out.println(“Caught exception:”+e);
throw e;// rethrowing of exception
}
}
}
Multi-Threading
What is thread and what is multi-threading?
Multi-Threading: The process of executing multiple threads simultaneously is known as multi-
threading.
Multi-threading is a specialized form of multi-tasking.
Thread: Thread is basically a light weight process (or) thread is a tiny program running continuously.
A thread represents a separate path of execution of a group of statements. These statements are
executed by JVM one by one.
Advantages of multi-threading
It does not block the user because threads are independent and you can perform multiple
operations at the same time.
We can perform many operations together so it saves time.
Threads are independent so it does not affect any other threads if exception occurs in a
single thread.
85
86 Object Oriented Programing
Example: A text editor can format text at the same time that it is printing. These two actions are
being performed by two separate threads.
2. Java uses threads to enable the entire environment to be asynchronous. This helps reduce
inefficiency by preventing the waste of CPU cycles.
4. In this model, a single thread of control runs in an infinite loop, polling a single event queue
to decide what to do next.
86
87 Object Oriented Programing
5. Once this polling mechanism returns with, say a signal that a network file is ready to be
read, then the event loop dispatches the control to the appropriate event handler. Until this
event handler returns, nothing else happens in the program. This wastes CPU’s time.
6. The benefit of java multi-threading is the main loop/ polling mechanism is eliminated. One
thread can pause without stopping other parts of the program.
7. When a thread blocks in a java program, only the single thread that is blocked pauses, all
the other threads continue to run.
Both the Thread class and Runnable interface are found in java.lang package
Extends Thread:
Create a new class that extends Thread, and then create an instance of that class. The extending
class must override the run () method, which is the entry point for the new thread. It should also call
start () to begin execution of the new thread.
Commonly used Constructors of Thread class:
o Thread()
o Thread(String name)
o Thread(Runnable r)
87
88 Object Oriented Programing
System.out.print(“ ” + i);
}
}
}
class Test
{
public static void main(String[] args)
{
MyThreadobj = new MyThread();
Thread t = new Thread(obj);
t.start(); // now this thread will execute the code inside run() method.
}
{
Output:
0123456789
Methods in Thread class:
1. public String getName(): returns the name of the thread
2. public void setName(String name): changes the name of the thread.
3. public int getPriority(): returns the priority of the thread.
4. public int setPriority(int priority): changes the priority of the thread.
5. publicbooleanisAlive(): tests if the thread is alive.
6. public void join(): waits for a thread to die.
7. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
8. public void run(): is used to perform action for a thread.
9. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
10. public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
11. public void suspend(): is used to suspend the thread(depricated).
12. public void resume(): is used to resume the suspended thread(depricated).
13. public void stop(): is used to stop the thread(depricated).
14. public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
88
89 Object Oriented Programing
i. If a class extends a thread class then it can’t extend any other classes which may be
required to extend.
ii. If the class Thread is extended then all of its functionality gets inherited. This is an expensive
operation.
Program:
classThreadDemo implements Runnable
{
Thread t;
String str = “ “;
ThreadDemo(String s)
{
t = new Thread(this);
str = s;
t.start();
}
public void run()
{
System.out.println(str);
{
}
public class RunnableThread
{
public static void main(String[] args)
{
ThreadDemo t = new ThreadDemo(“Thread Created”);
}
}
89
90 Object Oriented Programing
Then the thread goes into runnable state when start() method is applied on it(called).
yield() method may pause a method briefly but the thread will be in runnable state only.
From runnable state a thread may get into non – runnable state when sleep() method or wait()
method act on it.
A thread may be occasionally blocked on some I/O device where it is expecting some input /
output from user.
Thread always exists in any one of the states.
1. New or create state
2. Runnable state
3. Waiting state
4. Timed waiting state
5. Blocked state
6. Terminated state
New
Completion
Waiting Runnable Terminated Exit
Waiting
Interval Request Completed
For
Wait Ends I/O Request
Interval
New State: When a Blocked thread starts its life
cycle it enters into the Timed Waiting new state or a
create state
Runnable State: This is a state in which a thread starts executing.
Waiting State: Sometimes a thread has to go into the waiting state because another thread starts
executing.
Time Waiting State: There is a provision to keep a thread waiting for some time interval. This allows
to execute high prioritized threads first. After the timing gets over the thread in waiting state enters
runnable state.
Blocked State: When a particular thread issues an I/O request then the operating system sends it in
blocked state until the I/O operation gets completed. After the I/O completion the thread is sent
back to the runnable state.
Terminated State: A thread terminates because of either of the following reasons:
Because it exists normally. This happens when the code of thread has entirely executed by
the program.
90
91 Object Oriented Programing
Because there occurred some unusual erroneous event, like segmentation fault or an
unhandled exception.
A thread that lies in terminated state does no longer consumes any cycles of CPU.
Lowest Priority = 1
Highest Priority = 10
Higher priority threads get more CPU time than lower priority threads
These are the commonly used functionalities in thread scheduling
1. setPriority()
2. getPriority()
Program:
class A extends Thread
{
public void run()
91
92 Object Oriented Programing
{
System.out.println(“Thread #1”);
for(int i = 1 ; i<= 5; i++)
{
System.out.print(“\tA: ” + i);
}
System.out.println(“\nEnd of thread #1”);
}
}
classThreadPriority
{
public static void main(String[] args)
{
A obj1 = new A();
B obj2 = new B();
obj1.setPriority(1);
obj2.setPriority(10);
System.out.println(“Starting Thread #1”);
92
93 Object Oriented Programing
obj1.start();
System.out.println(“Starting Thread #2”);
obj2.start();
}
}
Synchronization in Java
Synchronization in java is the capability to control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource. (OR)
When two or more threads need access to a shared resource they need some way to ensure that
the resource will be used by only one thread at a time. This process is called “Synchronization”.
Why use Synchronization
The synchronization is mainly used to
To prevent thread interference.
To prevent consistency problem.
Types of Synchronization
There are two types of synchronization
Process Synchronization
Thread Synchronization
93
94 Object Oriented Programing
voidprintTable(int n)
{
synchronized(this)
{ //synchronized block
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
} //end of for
} //end of synchronized block
} //end of the method
}
94
95 Object Oriented Programing
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
public class TestSynchronizedBlock1
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
95
96 Object Oriented Programing
Deadlock in java
Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is
waiting for an object lock, that is acquired by another thread and second thread is waiting for an
object lock that is acquired by first thread. Since, both threads are waiting for each other to
release the lock, the condition is called deadlock.
Inter-Thread Communication
Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other. (Two or more threads communicate with each other by
exchanging the messages)
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in
its critical section and another thread is allowed to enter (or lock) in the same critical section to be
executed. It is implemented by following methods of Object class:
o wait()
o notify()
o notifyAll()
wait() method
It tells the calling thread to give up the lock and go to sleep until some other thread enters the
same monitor and calls notify().
96
97 Object Oriented Programing
notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on
this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation.
Syntax:
notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
Let's see the important differences between wait and sleep methods.
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
97
98 Object Oriented Programing
At the same time, the consumer is consuming the data (i.e. removing it from the buffer),
one piece at a time.
http://www.geeksforgeeks.org/producer-consumer-solution-using-threads-java/
Consider producer-consumer problem in which producer thread produces and the consumer
thread consumes whatever is produced. Both must work in co-ordination to avoid wastage of CPU
cycles. But there are situations in which producer has to wait for the consumer to finish
consumption of data.
Similarly the consumer may need to wait for the producer to produce the data. In polling system
either consumer will waste many CPU cycles when waiting for producer to produce or the
producer will waste many CPU cycles when waiting for consumer to consume the data.
In order to avoid this we use three inbuilt methods that take part in inter-thread communication.
1. notify()
2. notifyAll()
3. wait()
Program:
class MyClass
{
int n;
boolean flag = false;
synchronized int get()
{
if(!flag)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println(“Interrupted Exception”);
98
99 Object Oriented Programing
}
System.out.println(“Consumer consuming: ” + n);
flag =false;
notify();
return n;
}
synchronized void put(int n)
{
if(flag)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println(“Interrupted Exception”);
}
this.n = n;
flag = true;
System.out.println(“Producer Producing ” + n);
notify();
}
}
99
100 Object Oriented Programing
100
101 Object Oriented Programing
}
Issues:
Issue 1:
wait() method can only be used with in synchronized method or block otherwise it will throw
java.lang.IllegalMonitorStateException exception.
Issue 2:
One of the thread may go into waiting state forever. Take a look at your if condition of thread
waiting logic. In present case if you have created two different item objects for producer as well as
consumer then inter-thread logic will not work so make sure both producer and consumer threads
share same item object so they can share monitor lock.
101
102 Object Oriented Programing
102
103 Object Oriented Programing
(or)
Collection class: Collections is a unity class in java.util package. It consists of any static
methods which are used to operate on objects of type collection.
For example, collections has methods for finding the max element in a collection.
103
104 Object Oriented Programing
2. Algorithm
Here E specifies the type of objects that the collection will hold. Collections extends the Iterable
interface.
This means that all collections can be cycled through by use of the for-each style for loop.
Collection Map
List
•ArrayList
HashMap
•LinkedList
•Vector
•Stack
Set LinkedHashMap
•HashSet
•LinkedHashSet
•SortedSet
•TreeSet
HashTable
Queue
•Priority Queue
•Dequeue
•ArrayDequeue
Properties
104
105 Object Oriented Programing
Characterstics of Array
Resizable Array is the underlying Datasturcture.
Duplicate values are allowed.
Insertion order followed.
Hetrogenous objects accepted.
Null insertion is possible.
Seriolizable and cloneable interface implemented and also randomaccess implemented.
Constructors:-
ArrayList l=new ArrayList(); default size 10
New size=(current size/2)+1
ArrayList l=new ArrayList(int intialcapacity);
ArrayList l=new ArrayList(Collection c);
Note: ArrayList methods are not synchronized method.i.e; when more than one thread acts
simultaneously on the ArrayObject.
105
106 Object Oriented Programing
PROGRAM:
import java.util.*;
class ArrayListDemo
{
public static void main(String [] args)
{
ArrayList l=new ArrayList();
l.add(“A”);
l.add(10);
l.add(“A”);
l.add(null);
System.out.println(l); //[A,10,A,null]
l.remove(2); //[A,10,null]
System.out.println(l);
l.add(2,”m”);
l.add(“N”);
System.out.println(l0;
}
}
output
[A,10,m,null,N]
106
107 Object Oriented Programing
Constructors:
LinkedList l =new LinkedList();
LinkedList l=new LinkedList(collection c);
Methods :
addFirst(): To add elements to the start a list.
addLast(): To add elements to the end of the list.
getFirst()/Peekfirst : obtain the first element.
getLast(): To obtain the last element.
removeFirst():To remove the 1st element .
removeLast(): To remove the last element.
PROGRAM:
Import java .util.*;
Class LinkedListDemo
{
Public static void main(String [] args)
{
LinkedList l = new LinkedList();
l.add(“Java”);
l.add(“30”);
l.add(0,“software”);
l.add(0,“venky”);
l.removeLast();
l.addFirst(“ccc”);
System.out,println(l);
}
}
Output: [Java, venky, software, 30, null]
107
108 Object Oriented Programing
It means even if several threads act on vector on vector on vector objects simultaneously,
the results will be reliable.
Vector is similar to ArrayLIst class which implements the dynamic array.
It implements the list interface.
Constructors:
Vector v =new Vector();
Vector v = new Vector(int size);
Vector v = new Vector(int size; int intialcapacity);
108
109 Object Oriented Programing
for(int i=0;i<=10;i++)
{
v.addElement(i);
}
System.out.println(v.capacity);
v.addElement(“A”);
System.out.println(v.capacity());
System.out.println(v);
}
} Output: [1,2,3,4,5,6,7,8,9,10,A]
ArrayList Vector
2) ArrayList increments 50% of Vector increments 100% means doubles the array
current array size if number of size if total number of element exceeds than its
element exceeds from its capacity.
capacity.
109
110 Object Oriented Programing
Constructors:
Stack s = new Stack();
Methods:
Apart from the methods inherited from its parent class Vector, Stack defines the following methods
1 boolean empty()
Tests if this stack is empty. Returns true if the stack is empty, and returns false if the stack
contains elements.
2 Object peek( )
Returns the element on the top of the stack, but does not remove it.
3 Object pop( )
Returns the element on the top of the stack, removing it in the process.
110
111 Object Oriented Programing
HashSet
Collection Set
LinkedHashSet
HashSet:
HashSet extends AbstractSet and implements the set interface .it creates a collection that uses a
hashtable for storage.
1. The underlying data structure is hashtable.
111
112 Object Oriented Programing
2. Duplicate values are not allowed .if we are trying to insert duplicate values ,we won’t get
any compile time (or) runtime errors .add() method simply returns false.
3. Insertion order is not preserved.
4. Heterogeneous objects are allowed.
5. ‘null’ insertion is possible .
6. Implementing serialization and cloneable interfaces but not random access.
7. HashSet is the best choice, if our operation is “search”.
Constructors:
1) HashSet h=new HashSet();
default size is 16
default fill ratio is 0.75
2) HashSet h=new HashSet(int initialcapacity);
3) HashSet h=new HashSet(collection());
Methods:
Method Description
void clear() remove all elements
Boolean add(object) add object
isEmpty() return true
remove(object o) remove specified object
112
113 Object Oriented Programing
NOTE:
HashSet does not guarantee the order of its elements, because the process of hashing doesn’t
usually lend itself to the creation of sortedset.
113
114 Object Oriented Programing
For-Each:
1. If we won’t be modifying the content s of a collection or obtaining elements in reverse
order, then the for-each version of the for loop is often a more convenient alternative to
cycling through a collection than is using an iterator.
2. Recall that the for can cycle through any collection of objects, that implemented the
Iterable Interface. Because all of the collection classes implement this interface, they
can all be operated upon by the for.
Ex:
Class ForEachDemO
{
public static void main(String [ ] args)
{
ArrayList l = new ArrayList( );
l.add(1);
l.add(2);
l.add(5);
System.ot.println9”contents of list”);
System.out.println(l);
}
}
Queue Interface:-
1. Java queue interface orders the element in FIFO(First in First out)manner. First and last
elements are removed at last.
2. Queue is a generic interface
Constructor:
Interface Queue<E>
114
115 Object Oriented Programing
Here E specifies the type of objects that the queue will hold.
Methods:
Method Description
object element () It is used to retrieves, and but does not
remove the head of this queue.
boolean add(object) It is used to insert the specified element
into this queue and return true upon
success.
object remove() It is used to retrieves and removes the
head of this queue.
object poll() It is used to retrieve and remove the head
of the queue, or return null if the queue is
empty.
object peek() It is used to retrieve, but doesn’t remove
the head of this queue or returns null if the
queue is empty.
Ex:
import java.util.*;
class PriorityQueueDemo
{
Public static void main(String[ ] args)
{
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add(“java”);
queue(“pgm”);
queue.add(“language”);
System.out.println(“head” +queue.element());
System.out.println(“head” +queue.peek());
System.out.println(“queue elements”);
Iterator(itr=queue.iterator());
While(it.hasNext())
115
116 Object Oriented Programing
{
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println(“after removing two elements”);
Iterator<String>itr2=queue.iterator();
While(itr2.hasNext())
{
System.out.println(itr2.next( ));
}
}
}
Output:
Head:Java
Head:Java
Iterting the queue elements
Java
Pgm
language
After removing two elements
language
ArrayDeque Class:
1. Java deque interface is a linear collection that supports element insertuion and removal
at both ends.
2. Dequeue is anj acronym for” double ordered queue”.
3. The Arrayqueue class extends AbstractCollection and implements the dequeue
interface. It adds no methods of its own.
4. ArrayDequeue creates a dynamic array and has no capacity restrictions.
Constructor:
Class ArrayDequeue<E>
Here E specifies the type of object stored in the collection.
116
117 Object Oriented Programing
Methods:
Method Description
boolean add(object) It is used to insert the specified element
into this dequeue and return
true upon success
object remove() It is used to retrieves and remotes the
head of this queue.
Object poll() It is used to retrieves but doesnot remove
the head of this queue.
Object peek() It is used to retrieve but doesnot remove,
the head of this dequeue.
Example:
Import java.util.*;
public class ArrayDequeDemo
{ public static void main(String[] args)
Deque<String> deque =new ArrayDeque<String> (0);
deque.add(“RAVI”);
deque.add(“VIJAY”);
deque.add(“AJAY”);
for( String str:deque)
{ System.out.println(str);
}
}
}
Output:
RAVI
VIJAY
AJAY
117
118 Object Oriented Programing
Constructor Description
Hashtable() It is the default constructor of hash table it instantiates the Hashtable
class.
Hashtable(int size) It is used to accept an integer parameter and creates a hash table that has
an initial size specified by integer value size.
Hashtable(int size, float It is used to create a hash table that has an initial size specified by size
fillRatio) and a fill ratio specified by fillRatio.
Method Description
void clear() It is used to reset the hash table.
boolean contains(Object This method return true if some value equal to the value exist
value) within the hash table, else return false.
boolean containsValue(Object This method return true if some value equal to the value exists
value) within the hash table, else return false.
boolean containsKey(Object This method return true if some key equal to the key exists within
key) the hash table, else return false.
boolean isEmpty() This method return true if the hash table is empty; returns false if it
contains at least one key.
void rehash() It is used to increase the size of the hash table and rehashes all of
its keys.
Object get(Object key) This method return the object that contains the value associated
with the key.
Object remove(Object key) It is used to remove the key and its value. This method return the
value associated with the key.
int size() This method return the number of entries in the hash table.
Program:-
Import java.uti.*;
class HashtableDemo
{ public static void main(String[] args)
{ Hashtable h= new Hashtable();
h.put(new Temp(5),”A”);
h.put(new Temp(2),”B”);
h.put(new Temp(6),”C”);
h.put(new Temp(15),”D”);
h.put(new Temp(23),”E”);
System.out.println(h);
}
}
class temp{
{ int i;
Temp(int i)
118
119 Object Oriented Programing
{ this .i=i;
}
public int hashtable()
{
return i;
}
public String toString()
{ return i+ “ “;
}
}
Output:
{6=c,5=A,15=D,2=B,23=B}
NOTE:
1. from top to bottom it will be printed.
2. If multiple values are there the right to left printed.
It can be represented as
10
9
8
7
6 6=C
5 5=A
4 15=D
3
2 2=B
1 23=E
0
119
120 Object Oriented Programing
Map
Method Description
Object put(Object key, Object It is used to insert an entry in this map.
value)
void putAll(Map map) It is used to insert the specified map in this
map.
Object remove(Object key) It is used to delete an entry for the specified
key.
Object get(Object key) It is used to return the value for the specified
key.
boolean containsKey(Object It is used to search the specified key from this
key) map.
Set keySet() It is used to return the Set view containing all
the keys.
Set entrySet() It is used to return the Set view containing all
the keys and values.
120
121 Object Oriented Programing
HashMap class:
1. Hashmap is a collection that stores elements in the fom of key value pairs.if key is
provided later, its corresponding value can be easily retrieved from the HashMap .
2. Keys should be unique .This means we cannot use duplicate data forkeys in the
HashMap. However ,HashMap is not synchronized and hence while using multiple
threads on HashMap object , we can get unreliable results.
121
122 Object Oriented Programing
Example Program:
import java.util.*;
public class HashMapdemo
{
HashMap m=new HashMap();
m.put(“Mahesh”,700);
m.put(“ramu”,800);
m.put(“raju”,200);
m.put(“problems”,500);
System.out.println(m);
System.out.println(m.put(“Mahesh”,100);
Set s=m.keySet();
System.out.println(s);
Collection c=m.Values();
122
123 Object Oriented Programing
System.out.println(c);
Set s1=m.entrySet();
System.out.println(s1);
Iterator itr=s1.iterator();
While(itr.hasNext())
{
Map.Entry m1=(map.Entry)itr.next();
System.out.println(m1.getkey()+” “ +m1.getValue());
If(m1.getkey().equals(“ramu));
{
M1.setVale(10000);
}
}
System.out.println(m);
}
}
Comparator Interface:
Java comparator interface is used to order the objects of user defined class.
This interface is found in java.util package and contain 2 methods
1) compare
2) equals
Example:
Compare(Object obj1,Object obj2)
equals(Object element)
compare() method
public int compare(Object obj1,Object obj2): compares the first object with second object.
It provides multiple sorting sequence i.e. You can sort the elements on the basis of any data
members, for Example roll, name, age etc.
Example Program:
Student.java
Class student
{
int rollno;
123
124 Object Oriented Programing
String name;
int age;
Student(int rollno,String name,int age)
{
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
Age comparator.java
Class agecomparator implements comparator<student>
{
public int compare (student s1,student s2)
{
if(s1.age==s2.age)
return 0;
else if(s1.age>s2.age)
return 1;
else
return -1;
}
}
124
125 Object Oriented Programing
File: Student.java
1.
compile
rebuilt
Username:”scott”
redeplay
restart
Password:”tiger”
restart server
without properties 2
to 3 hours
125
126 Object Oriented Programing
load
object
Store
3) The properties object contains key and value pair both as a string .the java.util.properties
class is the subclass of hashtable. It can be used to get property value based on the
property key. The property class provides methods to get data from properties file and store
data into properties file.
Method Description
public void load(Reader r) Loads data from the Reader object.
public void load(InputStream is) loads data from the InputStream
object
public String getProperty(String key) Returns value based on the key.
public void setProperty(String Sets the property in the properties
key,String value) object.
public void store(Writer w, String Writes the properties in the writer
comment) object.
public void store(OutputStream os, Writes the properties in the
String comment) OutputStream object.
storeToXML(OutputStream os, String Writes the properties in the writer
comment) object for generating xml document.
public void storeToXML(Writer w, Writes the properties in the writer
String comment, String encoding) object for generating xml document
126
127 Object Oriented Programing
127
128 Object Oriented Programing
Drawbacks:
1) Iterator and enumerator are single directional cursors.they can always move towards
forward direction only.
2) By using iterator we can perform read and remove operation and we cant perform any
replace or addition of new objects.
Example Program:
import java.util.*;
Class iteratoreaxmple
{
Public static void main(String[] args)
{
ArrayList l=new ArrayList();
for(i=0;i<=6;i++)
{
l.add(i);
}
System.out.println(l);
Iterator itr=l.iterator();
While(itr.hasNext())
{
Integer I=(Integer)itr.next();
if(I%2==0)
System.out.println(l);
else
itr.remove();
}
}
}
o/p:
2
4
128
129 Object Oriented Programing
6
8
Dictionary classes:
1. Dictionary is an abstract class that represents a key/value storage repository & operates much
like maps.
2. Given a key and value, you can store the value in dictionary object.
3. Once value is stored, you can retrieve it by using its key.
4. Thus, like a map, a dictionary can be thought of as list of key /value pairs
5. Dictionary is classified as absolute, because use it is fully superseded by map.
Constructor:
Dictionary ( )
Methods:
Method Description
object get( object key) Returns the object that contains the value
associated with the key.
object put(object key, object value) Inserts key and its value into the dictionary.
abstract boolean is empty() This method tests if this dictionary maps no keys
to value.
object remove(object key) This method removes the key (and its
corresponding value) from this dictionary.
abstract int size() This method returns the number of entries
(distinct keys) in this dictionary.
Example:-
import java.util.*;
public class DictionaryDemo
{
public static void main(Stringt[] args)
{
Dictionary d=new Hashtable( );
d.put(“1”,”java”);
d.put(“2”,”MFCS”);
for(Enumeration e=d.key());
e.hasMoreElements();
{
System.out,println(e.nextElement())
129
130 Object Oriented Programing
}
}
}
Output:
2
1
Collection Algorithms:
1. The collection framework defines several algorithms that can be applied to collections
and maps.
2. These algorithms are defined as static methods within the collection class.
3. Several of the methods can throw a ClasscostException,which occurs when an attempt
is made to compare incomplete types, or an unsupported OperationException which
occurs when an attempt is made to modify an unmodifiable collection.
4. The set of methods that begins with unmodifiable returns views of the various collections
that cannot be modified.
5. These will be useful when you want to grant some process read- but not write-
capabilities on a collection.
6. Collections defines three static variables.
EMPTY_SET
EMPTY_LIST
EMPTY_MAP
Methods:
1. static<T> boolean add(Collection<? Super T >c,T---------element)
2. Inserts elements specified by elements into the collection specified by c.
3. static CheckedSet()
4. static comparatror()
5. Static void rotate ()
6. Static void shuffle()
130
131 Object Oriented Programing
abstract void add(int It is used to add or subtract the specified amount of time
field, int amount) to the given calendar field, based on the calendar's
rules.
int get(int field) It is used to return the value of the given calendar field.
static Calendar It is used to get a calendar using the default time zone
getInstance() and locale.
abstract int It is used to return the maximum value for the given
getMaximum(int field) calendar field of this Calendar instance.
abstract int It is used to return the minimum value for the given
getMinimum(int field) calendar field of this Calendar instance.
void set(int field, int value) It is used to set the given calendar field to the given
value.
void setTime(Date date) It is used to set this Calendar's time with the given Date.
1. import java.util.Calendar;
2. public class CalendarExample1 {
3. public static void main(String[] args) {
4. Calendar calendar = Calendar.getInstance();
131
132 Object Oriented Programing
Output:
java.util.Date Class
The java.util.Date class represents date and time in java. It provides constructors and methods to deal
with date and time in java.
After Calendar class, most of the constructors and methods of java.util.Date class has been
deprecated. Here, we are not giving list of any deprecated constructor and method.
java.util.Date Constructors
No. Constructor Description
132
133 Object Oriented Programing
java.util.Date Methods
No. Method Description
1) boolean after(Date date) tests if current date is after the given date.
2) boolean before(Date date) tests if current date is before the given date.
5) boolean equals(Date date) compares current date with given date for
equality.
8) int hashCode() returns the hash code value for this date
object.
9) void setTime(long time) changes the current date and time to given
time.
java.util.Date Example
Let's see the example to print date in java using java.util.Date class.
1st way:
1. java.util.Date date=new java.util.Date();
2. System.out.println(date);
133
134 Object Oriented Programing
Output:
Wed Mar 27 08:22:02 IST 2015
2nd way:
1. long millis=System.currentTimeMillis();
2. java.util.Date date=new java.util.Date(millis);
3. System.out.println(date);
Output:
Wed Mar 27 08:22:02 IST 2015
Constructors:
Random(): Creates a new random number generator
Random(long seed): Creates a new random number generator using a single long seed
Declaration:
public class Random
extends Object
implements Serializable
Methods:
1. java.util.Random.doubles(): Returns an effectively unlimited stream of pseudo random double values,
each between zero (inclusive) and one (exclusive)
Syntax:
public DoubleStream doubles()
Returns: A stream of pseudorandom double values
4. next(int bits): java.util.Random.next(int bits) Generates the next pseudo random number
Syntax:
protected int next(int bits)
Parameters: bits - random bits
134
135 Object Oriented Programing
Returns: the next pseudo random value from this Random number generator's sequence
8. java.util.Random.nextFloat(): Returns the next pseudo random, uniformly distributed float value
between 0.0 and 1.0 from this random number generator’s sequence
Syntax:
public float nextFloat()
Returns: The next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this
random number generator's sequence
10. java.util.Random.nextInt(): Returns the next pseudorandom, uniformly distributed int value from this
random number generator’s sequence
Syntax:
public int nextInt()
Returns: Rhe next pseudorandom, uniformly distributed int value from this random number generator's
sequence
11. java.util.Random.nextInt(int bound): Returns a pseudo random, uniformly distributed int value
between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator’s
sequence
Syntax:
public int nextInt(int bound)
Parameters: bound - the upper bound (exclusive). Must be positive.
135
136 Object Oriented Programing
Returns: The next pseudorandom, uniformly distributed int value between zero (inclusive) and bound
(exclusive) from this random number generator's sequence
Throws: IllegalArgumentException - if bound is not positive
12. java.util.Random.nextLong(): Returns the next pseudorandom, uniformly distributed long value
from this random number generator’s sequence
Syntax:
public long nextLong()
Returns: The next pseudorandom, uniformly distributed long valuefrom this random number generator's
sequence
13. java.util.Random.setSeed(long seed): Sets the seed of this random number generator using a
single long seed
Syntax:
public void setSeed(long seed)
Parameters:seed - the initial seed
136
137 Object Oriented Programing
System.out.println(random.nextLong());
System.out.println(random.nextInt());
*/
}
}
Output:
137
138 Object Oriented Programing
true
0.19674934340402916
0.7372021
1.4877581394085997
158739962004803677
-1344764816
138
139 Object Oriented Programing
139
140 Object Oriented Programing
It is in java.awt package. This package got classes and interfaces to develop GUI and let the users
interact in a more friendly way with the applications.
The AWT contains large number of classes which help to include various graphical components in
the java program.
These graphical components include text box, buttons, labels, radio buttons, list items and so on.
Object Button
Label
Component
Checkbox
Choice
List
Container
Window Panel
Frame Dialog
LIMITATIONS OF AWT:
1. AWT components are platform dependent .
2. The look and feel are different for different OS.
3. AWT is heavyweight i.e. its components are using the resources of operating system.
4. AWT supports limited number of GUI components.
5. The AWT component is converted by the native code of the O.S.
1. Component: This is the superclass of all the graphical classes from which variety of graphical
classes can be derived. It helps in displaying the graphical object in the screen. It handles the
mouse and keyboard events.
140
141 Object Oriented Programing
2. Container: This is a graphical component derived from the component class. It is responsible for
managing the layout and placement of graphical components in the container.
3. Window: The top-level window without border and without the menu bar is created using
window class. It decides the layout of the window.
4. Frame: This is a top-level window with a border and menu bar.
Method Description
public void setLayout(LayoutManager Sets the layout manager for the component.
m)
Example:
import java.awt.*;
class AwtDemo
{
AwtDemo()
{
Frame f=new Frame ();
Button b=new Button(“click me”);
b.setBounds (30, 50, 80, 30);
f.add (b);
f.setSize (300,300);
f.setLayout (null);
f.setVisible (true);
141
142 Object Oriented Programing
}
public static void main(String args[])
{
AwtDemo a=new AwtDemo();
}
}
MVC Architecture.
Ans. MVC means model, view and controller. This pattern is used to separate application concerns.
1. Model: The model represents the state (data) and business logic of the application.
2. View: The view model is responsible to display data i.e. it represents presentation.
3. Controller: The controller module acts as an interface between view and model. It interrupts
all the request i.e. receivers input and commands to model/view to change accordingly.
Controller
Database
Model
View (JSP) (Java Bean)
Container
ADVANTAGES OF MVC:
1. Easy to maintain.
2. Easy to control.
3. Easy to test.
4. Better separation of concerns.
142
143 Object Oriented Programing
an interface that is implemented by all classes of layout managers. These are following classes that
represent the layout managers.
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout
Etc…
JAVA BorderLayout:
The BorderLayout is used to arrange the components in five regions: north, south, east, west and
center. Each region (area) may contain one component only. It is the default layout of frame or
window. The BorderLayout provides five constants for each region:
public static final int NORTH
public static final int SOUTH
public static final int EAST
public static final int WEST
public static final int CENTER
143
144 Object Oriented Programing
NORTH
CENTER EAS
WEST
T
SOUTH
f.add(b1, BorderLayout.NORTH);
f.add(b2, BorderLayout.SOUTH);
f.add(b3, BorderLayout.EAST);
f.add(b4, BorderLayout.WEST);
144
145 Object Oriented Programing
f.add(b5, BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String args[])
{
new Border();
}
}
JAVA GridLayout:
The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.
Constructors of GridLayout Class:
GridLayout(): creates a grid layout with one column per component in a row.
GridLayout(int rows, int columns): creates a grid layout with given rows and columns but no
gaps between the component.
GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given
rows and columns along with given horizontal and vertical gaps.
PROGRAM:
import java.awt.*;
import javax.swing.*;
145
146 Object Oriented Programing
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
146
147 Object Oriented Programing
1 2 3
4 5 6
7 8 9
JAVA FlowLayout:
The FlowLayout is used to arrange the components in a line, one after another (in a flow).It is the
default layout of applet or panel.
PROGRAM:
import java.awt.*;
import javax.swing.*;
147
148 Object Oriented Programing
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
JAVA CardLayout:
The CardLayout class manages the components in such a manner that only one component is
visible at a time. It treats each component as a card that is why it is known as CardLayout.
148
149 Object Oriented Programing
public void last(Container parent): is used to flip to the last card of the
given container.
PROGRAM:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class CardLayoutExample extends JFrame implements ActionListener{
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample(){
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);
b1=new JButton(“Apple”);
b2=new JButton(“Boy”);
b3=new JButton(“Cat”);
b1.add ActionListener(this);
b2.add ActionListener(this);
b3.add ActionListener(this);
149
150 Object Oriented Programing
c.add(“a”,b1);
c.add(“b”,b2);
c.add(“c”,b3);
}
public void actionPerformed(ActionEvent e)
card.next( c );
}
public static void main(String args[])
{
CardLayoutExample cl=new CardLayoutExample;
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Applet
JAVA GridBagLayout:
150
151 Object Oriented Programing
The Java GridBagLayout class is used to align components vertically, horizontally or along their
baseline.
The components may not be of same size . Each GridBagLayout object maintains a
dynamic,rectangular grid of cells. Each component occupies one or more cells known as its
dispkay area. Each component associates as instance of GridBagConstraints .With the help of
constraints object we arrange component’s display area on grid. the GridBagLayout manages
each component’s minimum and preferred sizes in order to determine component’ s size.
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
151
152 Object Oriented Programing
gbc.ipady=20;
gbc.gridx=0;
gbc.gridy=1;
this.add(new Button(“Button Three”),gbc);
gbc.gridx=1;
gbc.gridy=1;
this.add(new Button(“Button Four”),gbc);
gbc.gridx=0;
gbc.gridy=2;
this.add(new Button(“Button Five”),gbc);
setSize(300,300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
OUTPUT:
GridBagLayout Example
Button Five
152
153 Object Oriented Programing
EVENT HANDLING
Change in the state of an object is known as event i.e. event describes the change in state of
source. Events are generated as result of user interaction with graphical user interface
components. For example, clicking on a button, moving the mouse, entering a character through
keyboard, selecting an item from list, scrolling the page are the activities that causes an event to
happen.
Callback Methods:
These are the methods that are provided by API provider and are defined by the application
programmer and invoked by the application developer. Here the callback methods represents an
event method. In response to an event java jre will fire callback method.
153
154 Object Oriented Programing
EventListener interface:
It is a marker interface which every listener interface has to extend . This class is defined in java.util
package.
SYNTAX:
public interface EventListener
AWT Event Listener Interfaces:
154
155 Object Oriented Programing
8. AdjustmentListener:
EVENT CLASSES:
The Event classes represent the event. Java provides us Event classes EventObject class.
It is the root class from which all event state objects shall be derived. All Events are constructed
with a reference to the object, the source, that is logically deemed to be the object upon which
the Event in question initially occurred upon. This class is defined in java.util package.
Constructors:
EventObject(Object source):Constructs a protypical Event.
Class Methods:
1. Object getSource(): The object on which the Event initially occurred.
2. String toString():Returns a string representation of this EventObject.
It is the root event class for all the AWT events.This class and its
subclasses supercede the original java.awt.Event class.
2. ActionEvent
The InputEvent class is root event class for all the component-level
input events.
4. KeyEvent
155
156 Object Oriented Programing
JAVA APPLET
Applet is a special type of program that is embedded in the webpage to generate
the dynamic content. It runs inside the browser and works at client side.
ADVANTAGE OF APPLET
There are many advantages of applet. They are as follows:
It works at client side so less response time.
Secured.
It can be executed by browsers running under many platforms ,including Linux,
Windows, Mac OS etc.
DRAWBACKS OF APPLET
Plugin is required at client browser to execute applet.
Hierarchy of Applet.
156
157 Object Oriented Programing
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods
of applet.
public void init(): is used to initialized the Applet. It is invoked only once.
157
158 Object Oriented Programing
public void start(): is invoked after the init() method or browser is maximized. It is
used to start the Applet.
public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
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.
EXAMPLE:
1.//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g)
{
g.drawString(“welcome”,150,150);
}
}
myapplet.html
<html>
<body>
<applet code = “First.class” width=”300” height=”300”>
</applet>
</body>
</html>
158
159 Object Oriented Programing
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
3) AWT doesn't support pluggable look and Swing supports pluggable look
feel. and feel.
4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.
159
160 Object Oriented Programing
We can write the code of swing inside the main(), constructor or any other method.
160
161 Object Oriented Programing
File: FirstSwingExample.java
1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5.
6. JButton b=new JButton("click");//creating instance of JButton
7. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
8.
9. f.add(b);//adding button in JFrame
10.
11. f.setSize(400,500);//400 width and 500 height
12. f.setLayout(null);//using no layout managers
13. f.setVisible(true);//making the frame visible
14. }
15. }
161
162 Object Oriented Programing
1. import javax.swing.*;
2. public class Simple {
3. JFrame f;
4. Simple(){
5. f=new JFrame();//creating instance of JFrame
6.
7. JButton b=new JButton("click");//creating instance of JButton
8. b.setBounds(130,100,100, 40);
9.
10. f.add(b);//adding button in JFrame
11.
12. f.setSize(400,500);//400 width and 500 height
13. f.setLayout(null);//using no layout managers
14. f.setVisible(true);//making the frame visible
15. }
16.
17. public static void main(String[] args) {
18. new Simple();
19. }
20. }
The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets the
position of the button.
File: Simple2.java
1. import javax.swing.*;
2. public class Simple2 extends JFrame{//inheriting JFrame
3. JFrame f;
4. Simple2(){
162
163 Object Oriented Programing
Java JFrame
The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class. JFrame
works like the main window where components like labels, buttons, textfields are added to create
a GUI.
Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
Nested Class
Modifier and Class Description
Type
protected class JFrame.AccessibleJFrame This class implements accessibility support for the
JFrame class.
Fields
Modifier and Field Description
Type
163
164 Object Oriented Programing
protected boolean rootPaneCheckingEnabled If true then calls to add and setLayout will be
forwarded to the contentPane.
Constructors
Constructor Description
JFrame(String title) It creates a new, initially invisible Frame with the specified
title.
JFrame(String title, It creates a JFrame with the specified title and the specified
GraphicsConfiguration gc) GraphicsConfiguration of a screen device.
Useful Methods
Modifier and Method Description
Type
164
165 Object Oriented Programing
JFrame Example
1. import java.awt.FlowLayout;
2. import javax.swing.JButton;
3. import javax.swing.JFrame;
4. import javax.swing.JLabel;
5. import javax.swing.Jpanel;
6. public class JFrameExample {
7. public static void main(String s[]) {
8. JFrame frame = new JFrame("JFrame Example");
9. JPanel panel = new JPanel();
10. panel.setLayout(new FlowLayout());
11. JLabel label = new JLabel("JFrame By Example");
12. JButton button = new JButton();
165
166 Object Oriented Programing
13. button.setText("Button");
14. panel.add(label);
15. panel.add(button);
16. frame.add(panel);
17. frame.setSize(200, 300);
18. frame.setLocationRelativeTo(null);
19. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
20. frame.setVisible(true);
21. }
22. }
Output
Java JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.
166
167 Object Oriented Programing
Output:
167
168 Object Oriented Programing
Output:
168
169 Object Oriented Programing
Output:
169
170 Object Oriented Programing
Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it
directly. It inherits JComponent class.
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image,
horizontalAlignment) and horizontal alignment.
170
171 Object Oriented Programing
void setText(String text) It defines the single line of text this component will
display.
void setHorizontalAlignment(int It sets the alignment of the label's contents along the X
alignment) axis.
Icon getIcon() It returns the graphic image that the label displays.
int getHorizontalAlignment() It returns the alignment of the label's contents along the
X axis.
Output:
171
172 Object Oriented Programing
Java JTextField
The object of a JTextField class is a text component that allows the editing of a single line text. It
inherits JTextComponent class.
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int Creates a new TextField initialized with the specified text and
columns) columns.
JTextField(int columns) Creates a new empty TextField with the specified number of
columns.
172
173 Object Oriented Programing
Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.
Output:
173
174 Object Oriented Programing
Java JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It inherits
JToggleButton class.
JCheckBox(String text, boolean Creates a check box with text and specifies whether or not it is
selected) initially selected.
JCheckBox(Action a) Creates a check box where properties are taken from the
Action supplied.
174
175 Object Oriented Programing
Output:
175
176 Object Oriented Programing
Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.
It should be added in ButtonGroup to select one radio button only.
JRadioButton(String s, boolean Creates a radio button with the specified text and selected
selected) status.
176
177 Object Oriented Programing
177
178 Object Oriented Programing
19. }
20. }
Output:
Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits JComponent class.
JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified
array.
178
179 Object Oriented Programing
void removeAllItems() It is used to remove all the items from the list.
Output:
179
180 Object Oriented Programing
Java JTable
The JTable class is used to display data in tabular form. It is composed of rows and columns.
JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.
180
181 Object Oriented Programing
9. String column[]={"ID","NAME","SALARY"};
10. JTable jt=new JTable(data,column);
11. jt.setBounds(30,40,200,300);
12. JScrollPane sp=new JScrollPane(jt);
13. f.add(sp);
14. f.setSize(300,400);
15. f.setVisible(true);
16. }
17. public static void main(String[] args) {
18. new TableExample();
19. }
20. }
Output:
Java JList
The object of JList class represents a list of text items. The list of text items can be set up so that the
user can choose either one item or multiple items. It inherits JComponent class.
181
182 Object Oriented Programing
JList(ary[] listData) Creates a JList that displays the elements in the specified array.
JList(ListModel<ary> Creates a JList that displays elements from the specified, non-null,
dataModel) model.
182
183 Object Oriented Programing
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. public static void main(String args[])
19. {
20. new ListExample();
21. }}
Output:
Java JToggleButton
JToggleButton is used to create toggle button, it is two-states button to switch on or off.
Nested Classes
Modifier Class Description
and Type
183
184 Object Oriented Programing
Constructors
Constructor Description
JToggleButton(Icon icon, boolean It creates a toggle button with the specified image and
selected) selection state, but no text.
JToggleButton(String text, boolean It creates a toggle button with the specified text and
selected) selection state.
JToggleButton(String text, Icon icon) It creates a toggle button that has the specified text and
image, and that is initially unselected.
JToggleButton(String text, Icon icon, It creates a toggle button with the specified text, image,
boolean selected) and selection state.
Methods
Modifier and Method Description
Type
String getUIClassID() It returns a string that specifies the name of the l&f
class that renders this component.
184
185 Object Oriented Programing
JToggleButton.
JToggleButton Example
1. import java.awt.FlowLayout;
2. import java.awt.event.ItemEvent;
3. import java.awt.event.ItemListener;
4. import javax.swing.JFrame;
5. import javax.swing.JToggleButton;
6.
7. public class JToggleButtonExample extends JFrame implements ItemListener {
8. public static void main(String[] args) {
9. new JToggleButtonExample();
10. }
11. private JToggleButton button;
12. JToggleButtonExample() {
13. setTitle("JToggleButton with ItemListener Example");
14. setLayout(new FlowLayout());
15. setJToggleButton();
16. setAction();
17. setSize(200, 200);
18. setVisible(true);
19. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
20. }
21. private void setJToggleButton() {
22. button = new JToggleButton("ON");
23. add(button);
24. }
25. private void setAction() {
26. button.addItemListener(this);
27. }
28. public void itemStateChanged(ItemEvent eve) {
29. if (button.isSelected())
30. button.setText("OFF");
185
186 Object Oriented Programing
31. else
32. button.setText("ON");
33. }
34. }
Output
Java JScrollPane
A JscrollPane is used to make scrollable view of a component. When screen size is limited, we use a
scroll pane to display a large component or a component whose size can change dynamically.
Constructors
Constructor Purpose
JScrollPane(Component)
JScrollPane(int, int)
JScrollPane(Component,
int, int)
186
187 Object Oriented Programing
Useful Methods
Modifier Method Description
void setColumnHeaderView(Component) It sets the column header for the scroll
pane.
void setRowHeaderView(Component) It sets the row header for the scroll pane.
void setCorner(String, Component) It sets or gets the specified corner. The int
parameter specifies which corner and must
be one of the following constants defined in
ScrollPaneConstants: UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.
Component getCorner(String) (The same as setCorner)
void setViewportView(Component) Set the scroll pane's client.
JScrollPane Example
1. import java.awt.FlowLayout;
2. import javax.swing.JFrame;
3. import javax.swing.JScrollPane;
4. import javax.swing.JtextArea;
5.
6. public class JScrollPaneExample {
7. private static final long serialVersionUID = 1L;
8.
9. private static void createAndShowGUI() {
10. // Create and set up the window.
11. final JFrame frame = new JFrame("Scroll Pane Example");
12.
13. // Display the window.
14. frame.setSize(500, 500);
15. frame.setVisible(true);
16. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17.
18. // set flow layout for the frame
19. frame.getContentPane().setLayout(new FlowLayout());
20.
21. JTextArea textArea = new JTextArea(20, 20);
187
188 Object Oriented Programing
25. scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
26.
27. frame.getContentPane().add(scrollableTextArea);
28. }
29. public static void main(String[] args) {
30.
31.
32. javax.swing.SwingUtilities.invokeLater(new Runnable() {
33.
34. public void run() {
35. createAndShowGUI();
36. }
37. });
38. }
39. }
Output:
188
189 Object Oriented Programing
Java JTabbedPane
The JTabbedPane class is used to switch between a group of components by clicking on a tab
with a given title or icon. It inherits JComponent class.
189
190 Object Oriented Programing
16. f.add(tp);
17. f.setSize(400,400);
18. f.setLayout(null);
19. f.setVisible(true);
20. }
21. public static void main(String[] args) {
22. new TabbedPaneExample();
23. }}
Output:
190
191 Object Oriented Programing
1. import java.awt.*;
2. import javax.swing.JFrame;
3.
4. public class MyCanvas extends Canvas{
5.
6. public void paint(Graphics g) {
7.
8. Toolkit t=Toolkit.getDefaultToolkit();
9. Image i=t.getImage("p3.gif");
10. g.drawImage(i, 120,100,this);
11.
12. }
13. public static void main(String[] args) {
14. MyCanvas m=new MyCanvas();
15. JFrame f=new JFrame();
16. f.add(m);
17. f.setSize(400,400);
18. f.setVisible(true);
19. }
20.
21. }
191