Handnote On Java
Handnote On Java
Faculty Details
1.1.1
the field of data mining and machine learning. He has participated and presented his papers in international conferences at Malaysia, Portugal, Italy,
and France. He is a member of IEEE and IEEE Computer Society.
1.2
What is Java?
1.2.1
In 1990, Sun Microsystems began a research project named Green to develop the C and C++ based language. James Gosling, a network software
designer was assigned to this project. Goslings solution to the problems of
C++ was a new language called Oak after an oak tree outside his window at
Sun. In May 1995, Sun Microsystems formally announced Java (Oak was renamed Java). Finally, in 1996, Java arrived in the market as a programming
language.
With the advent of Java 2 (released initially as J2SE 1.2 in December
1998), new versions had multiple configurations built for different types
of platforms. For example, J2EE targeted enterprise applications and the
greatly stripped-down version J2ME for mobile applications (Mobile Java).
J2SE designated the Standard Edition. In 2006, for marketing purposes, Sun
renamed new J2 versions as Java EE, Java ME, and Java SE, respectively.
On November 13, 2006, Sun released much of Java as free and open
source software, (FOSS), under the terms of the GNU General Public License
(GPL). On May 8, 2007, Sun finished the process, making all of Javas core
code available under free software/open-source distribution terms.
1.3
Applets are Java programs that reside on web servers, download by a browser
to a clients computer and run by that browser. Applets are usually small
in size to minimize download time and are invoked by a Hypertext Markup
Language (HTML) web page.
1.4
A Java virtual machine is a software that is capable of executing Java bytecode. Code for the JVM is stored in .class or .jar files, each of which
contains code for at most one public class. JVM enables the Java application to be platform independent. JVM is distributed along with a set of
standard class libraries that implement the Java application programming
interface (API). JVM mainly performs three tasks:
Loads Code The class loader loads all classes needed for the execution of
a program.
Verifies Code The byte code verifier tests format of code fragment and
checks code fragments for illegal code, which is code that forges pointers, violates access rights on objects, or attempts to change object
type.
Execute Code Performed by the runtime interpreter.
The Java Runtime Environment(JRE) is an implementation of the Java
Virtual Machine (JVM), which actually executes Java programs. The Java
Development Kit (JDK) is the original Java development environment for
Java programmers. The JDK consists of a library of standard classes and a
collection of utilities for building, testing, and documenting Java programs.
1.5
of programs are said memory leaks. Java overcome this problem by using
garbage collection. It provides a system level thread that tracks each memory allocation. During idle cycles in the JVM, the garbage collection thread
checks for and frees any memory the can be freed in the object lifecycle.
1.6
1.6.1
This short example shows how to write first java application and compile
and run it, which prints a String Welcome in Java World in output.
1 p u b l i c c l a s s Welcome{
2
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3
System . out . p r i n t l n ( Welcome i n Java World ) ;
4
}
5 }
Write this code in Notepad for Windows or Text Editor for Linux and
save the file as: Welcome.java (Source files must be named after the public
class). Now you are ready to compile and run the program. To compile the
program, open a command window or terminal, and change to the directory
where the program is stored and type javac Welcome.java
If the program contains no errors then a new file Welcome.class will
be created in the same directory. Now you can run this bytecodes file Welcome.class by typing the command java Welcome
Line 1 declares the user-defined class named Welcome. Every Java program consists at least one public class. The Welcome.java file creates
a Welcome.class file when the source file is being complied.
Line 2 declares the main method, where the program starts to execute.
The following describes each element of Line 2:
public The access modifier of main() method is public, because the
main() method can be accessed by anything including the Java
technology interpreter.
static The main() is static method because on instance of the class
is needed to execute static methods and static method is a single
copy.
void The return type of the main() method is void, because the main()
method does not return any value.
1.6.2
The name of the source file must be the same as the name of the public
class declaration in that file. A source file can include more then one class
declaration, but only one class can be declared public.
1
2
3
4
5
6
7
8
9
10
11
12
p u b l i c c l a s s Welcome2{
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
H e l l o h e l l o = new H e l l o ( ) ;
hello . display ( ) ;
}
}
c l a s s Hello {
public void display (){
System . out . p r i n t l n ( Welcome t o Java world ) ;
}
}
1.7
A class is a software blueprint. A class defines the set of data elements (called
attributes), as well as the set of behaviors or functions (called methods).
Together, attributes and methods are called members of a class. In Java
technology, class name usually starts with a capital letter, attribute and
method name usually starts with a small letter. The access modifier for the
classes in the Java technology can be public or default. The Java technology
class, attribute, constructor, and method declaration takes the following
forms:
<m o d i f i e r > c l a s s <c l a s s n a m e >{
<m o d i f i e r > <d a t a t y p e > <a t t r i b u t e n a m e >;
<m o d i f i e r > <d a t a t y p e > <a t t r i b u t e n a m e >[=<val ue > ] ;
[< m o d i f i e r >] <c l a s s n a m e >(<argument >){
<statement >
}
<m o d i f i e r > <r e t u r n t y p e > <method name>(<argument >){
<statement >
}
}
A constructor is a set of instructions designed to initialize an instance or
object. The name of the constructor must always be the same as the class
name. Constructor do not return any value. Valid modifiers for constructors
are public, protected, and private.
The Default Constructor: Every Java class has at least one constructor. If you do not write a constructor in a class then Java technology
provides a default constructor for you. This constructor takes no arguments
and has an empty body.
1 p u b l i c c l a s s MyDate{
2
p r i v a t e i n t day ;
3
p r i v a t e i n t month ;
4
pr ivat e i n t year ;
5
6
p u b l i c MyDate ( ) {
7
day = 1 ;
8
month = 6 ;
9
year = 1979;
10
}
11
12
p u b l i c v o i d showDate ( ) {
13
System . out . p r i n t l n ( Day : + day ) ;
14
System . out . p r i n t l n ( Month : + month ) ;
15
System . out . p r i n t l n ( Year : + y e a r ) ;
16
}
17
18
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
1.8
A Java technology source file declares firstly package statement (only one
package), secondly import statements, and finally classes. Which are following bellow:
1. package < topP ackageN ame > .[< subP ackageN ame >];
2. import < packageN ame > .[subP ackageN ame];
3. < classDeclaration >
The package statement is a way to group related classes. The package
statement place at beginning of the source file and only one package statement declaration is permitted. If a Java technology source file does not
contain a package declaration then the classes declared in the file belong to
the default package. The package names are hierarchical and are separated
by dots. The package name to be entirely lower case.
The import statement is used to make classes in other packages accessible
to the current class. Normally, the Java compiler places the .class files in
the same directory as the source file present. We can reroute the class file
to another directory using the -d option of the javac command (javac -d .
ClassName.java).
1 package b a n k i n g P r j ;
2
3 p u b l i c c l a s s Account {
4
p u b l i c S t r i n g accountName = Saving Account ;
5
6
p u b l i c v o i d showAccName ( ) {
7
System . out . p r i n t l n ( accountName ) ;
8
}
9
10
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
11
Account a c c = new Account ( ) ;
12
a c c . showAccName ( ) ;
13
}
14 }
package b a n k i n g P r j ;
import b a n k i n g P r j . Account ;
p u b l i c c l a s s Coustomer {
p u b l i c S t r i n g name = James Bond ;
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
Account a c c = new Account ( ) ;
a c c . showAccName ( ) ;
Coustomer c o u s = new Coustomer ( ) ;
System . out . p r i n t l n ( c o u s . name ) ;
}
}
Similarly, we can compile and run this code.
1.9
1.9.1
In Java Technology, we can add comments to Java source code in three ways
which are given bellow:
1 p u b l i c c l a s s TestComment{
2
// comment on one l i n e
3
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
4
/ comment on one
5
o r more l i n e s
6
/
7
System . out . p r i n t l n ( Comments i n Java ) ;
8
}
9
/ documentation comment
10
can a l s o span one o r more l i n e s
1.9.2
Semicolons
In the Java source code a statement is one or more lines of code terminated
with a semicolons (;).
1
2
3
4
5
6
7
public c l a s s TestSemicolon {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
i n t a =10 , b=20 , c ;
c = a+b ;
System . out . p r i n t l n ( c ) ;
}
}
1.10
Blocks
A block as a group of statements that are collected together called a compound statement. It is bound by opening and closing braces { }. A class
definition is contained in a block. A block statement can be nested withing
another block. In Java source code, block statements are executed first,
then constructor statements are executed, and then method statements are
executed.
1 p u b l i c c l a s s B lockT est {
2
public String info ;
3
4
p u b l i c B lockT est ( ) {
5
i n f o = C o n s t r u c t o r : Executed i n 2nd s t e p ;
6
System . out . p r i n t l n ( i n f o ) ;
7
}
8
9
{
10
i n f o = Block : Executed i n 1 s t s t e p ;
11
System . out . p r i n t l n ( i n f o ) ;
12
}
13
14
p u b l i c v o i d show ( ) {
15
i n f o = Method : Executed i n 3 rd s t e p ;
16
System . out . p r i n t l n ( i n f o ) ;
17
}
18
19
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
1.11
10
Java Identifiers
1.12
abstract
catch
do
finally
import
new
short
this
volatile
1.13
11
1.14
In Java technology, data are divided into two broad categories: primitive
types and class types.
Primitive data are eight types in four categories:
1. Logical: boolean (true or false)
2. Textual: char (16 bits)
3. Integral: byte (8 bits), short (16 bits), int (32 bits), and long (64 bits)
4. Floating point: float (32 bits) and double (64 bits)
Class or reference data used to create objects which are two types:
1. Textual: String
2. All classes that declare by ourself
1.14.1
Variable Initialization
In Java source code, the compiler will assign default value for the class
variables, if the programmer does not initialize the class variables. But local
variables must be initialized manually before use, because Java compiler will
not assign the local variables and local variable does not have any modifier.
12
1.15
The Java programming language operators are similar in style and function
to those of C and C++.
1. Assignment operator (=)
2. Arithmetic operator (+, -, *, /, %, ++, -)
3. Relational operator
4. Logical operator
5. Bitwise operator
6. What operator ((boolean expression)? true exp: false exp;)
7. instanceof operator
1.16
1.17
13
Casting
Chapter 2
Branching Statements
The if-else Statement
2.1.2
15
[ break ; ]
c a s e <c o n s t a n t >: <s t a t e m e n t o r b l o c k >
[ break ; ]
d e f a u l t : <s t a t e m e n t o r b l o c k >
}
1 p u b l i c c l a s s SwitchTest {
2
p u b l i c v o i d mySwitch ( i n t x ) {
3
switch ( x ){
4
c a s e 1 : System . out . p r i n t l n ( RED ) ;
5
break ;
6
c a s e 2 : System . out . p r i n t l n ( GREEN ) ;
7
break ;
8
c a s e 3 : System . out . p r i n t l n ( BLUE ) ;
9
break ;
10
d e f a u l t : System . out . p r i n t l n ( WHITE ) ;
11
}
12
}
13
14
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
15
S w i t c h T e s t s t = new S w i t c h T e s t ( ) ;
16
s t . mySwitch ( 2 ) ;
17
}
18 }
2.1.3
break; Use the break statement to exit from switch, loop, and block.
continue; Use the continue to jump at the end of the loop body, and then
return to the loop control.
2.2
Looping statements
2.2.1
16
}
1 public c l a s s Loop for {
2
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3
f o r ( i n t i =1; i <=50; i ++){
4
System . out . p r i n t l n ( i ) ;
5
}
6
}
7 }
Write a Java program that loops 1-50 and print foo for every multiple
of 3, bar for every multiple of 5 and baz for every multiple of 3 and 5.
1 public class Series {
2
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3
f o r ( i n t i =1; i <=50; i ++){
4
System . out . p r i n t ( i ) ;
5
i f ( i%3==0 && i %5==0)
6
System . out . p r i n t ( baz ) ;
7
e l s e i f ( i %3==0)
8
System . out . p r i n t ( f o o ) ;
9
e l s e i f ( i %5==0)
10
System . out . p r i n t ( bar ) ;
11
System . out . p r i n t l n ( ) ;
12
}
13
}
14 }
Write a Java program that will display the Fibonacci sequence is generated by adding the previous two terms. By starting with 1, 1, and 2, and
continue up to the first 10 terms.
1 public c l a s s Fibonacci {
2
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3
i n t x=1, y=1, z =0;
4
f o r ( i n t i =1; i <=10; i ++){
5
i f ( i ==1){
6
System . out . p r i n t ( x+ +y ) ;
7
}
8
z=x+y ;
9
System . out . p r i n t ( +z ) ;
10
x=y ;
11
y=z ;
12
}
13
}
14 }
1
1 2
1 2 3
1 2 3 4
1
2
3
4
5
1
2
3
4
5
6
1
2
3
4
5
6
7
1
2
3
4
5
6
7
8
1
2
3
4
5
6
7
8
9
1
2
3
4
5
6
7
8
1
2
3
4
5
6
7
1
2
3
4
5
6
1
2
3
4
5
1
2 1
3 2 1
4 3 2 1
1 p u b l i c c l a s s Pyramid {
2
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3
i n t n=9;
4
f o r ( i n t i =1; i<=n ; i ++){
5
f o r ( i n t j=ni ; j >=1; j )
6
System . out . p r i n t ( ) ;
7
f o r ( i n t k=1; k<=i ; k++)
8
System . out . p r i n t ( k+ ) ;
9
f o r ( i n t p=i 1; p>=1; p)
10
System . out . p r i n t ( p+ ) ;
11
System . out . p r i n t l n ( ) ;
12
}
13
}
14 }
2.2.2
17
2.2.3
18
2.3
Array
c l a s s Bird {
public void f l y (){
System . out . p r i n t l n ( Bird can f l y ) ;
}
}
19
7 public c l a s s ClassArray {
8
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
9
Bird [ ] myArray = new Bird [ 3 ] ;
10
f o r ( i n t i =0; i <3; i ++)
11
myArray [ i ] = new Bird ( ) ;
12
f o r ( i n t i =0; i <3; i ++)
13
myArray [ i ] . f l y ( ) ;
14
}
15 }
Write a Java program to create a class named ArrayExample, in this class
declare an array named myArray of Car type. Now initialize the myAarray
and call the display method for each index of myArray in the main method.
In the Car class there are two class variables: carName and carModel, constructor (initialized the variables), and display method ( display the value
of carName and carModel).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
c l a s s Car{
p u b l i c S t r i n g carName ;
p u b l i c S t r i n g carModel ;
p u b l i c Car ( S t r i n g carName , S t r i n g carModel ) {
t h i s . carName = carName ;
t h i s . carModel = carModel ;
}
public void display (){
System . out . p r i n t l n ( Name : +carName+, and Model : +carModel ) ;
}
} // end o f Car c l a s s ;
p u b l i c c l a s s ArrayExample {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
Car [ ] myArray = new Car [ 3 ] ;
myArray [ 0 ] = new Car ( BMW , Road Track 5 0 9 ) ;
myArray [ 1 ] = new Car ( Toyota , X c o r o l a 2 0 1 2 ) ;
myArray [ 2 ] = new Car ( Honda , M 2 0 1 1 ) ;
f o r ( i n t i =0; i <3; i ++)
{
myArray [ i ] . d i s p l a y ( ) ;
} // end o f f o r l o o p ;
} // end o f t h e main ( ) ;
} // end o f t h e c l a s s ;
2.4
20
2.4.1
21
Matrix Multiplication
1 p u b l i c c l a s s Matrix Mult {
2
3
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
4
i n t [ ] [ ] a = new i n t [ 3 ] [ 3 ] ;
5
i n t [ ] [ ] b = new i n t [ 3 ] [ 3 ] ;
6
i n t [ ] [ ] c = new i n t [ 3 ] [ 3 ] ;
7
8
f o r ( i n t i =0; i <=2; i ++)
9
f o r ( i n t j =0; j <=2; j ++)
10
{
11
a [ i ] [ j ] = 10+ i+j ;
12
b [ i ] [ j ] = 20+ i+j ;
13
}
14
System . out . p r i n t l n ( Matrix A : ) ;
15
f o r ( i n t i =0; i <=2; i ++)
16
{
17
f o r ( i n t j =0; j <=2; j ++)
18
System . out . p r i n t ( \ t+a [ i ] [ j ] ) ;
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Matrix M u l t i p l i c a t i o n
f o r ( i n t i =0; i <=2; i ++)
f o r ( i n t j =0; j <=2; j ++)
c [ i ] [ j ]=( a [ i ] [ 0 ] b [ 0 ] [ j ] )
+(a [ i ] [ 1 ] b [ 1 ] [ j ] ) + ( a [ i ] [ 2 ] b [ 2 ] [ j ] ) ;
33
34
35
36
37
38
39
40
41
}
42 }
2.5
22
23
11
12
p u b l i c v o i d arrayCopy ( ) {
13
int [ ] x = {1 ,2 ,3 ,4 ,5 ,6};
14
int [ ] y = {11 ,12 ,13 ,14 ,15 ,16 ,17 ,18 ,19 ,20};
15
System . a r r a y c o p y ( x , 0 , y , 0 , x . l e n g t h ) ;
16
}
17 }
2.6
The Java 2 Platform Standard Edition (J2SE) version 5.0 added enhanced
for loop.
1 p u b l i c c l a s s EnhanFor{
2
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3
i n t [ ] myArray = new i n t [ 5 ] ;
4
f o r ( i n t i =0; i <5; i ++)
5
myArray [ i ]= i +11;
6
// Enhanced f o r l o o p
7
f o r ( i n t e l e m e n t : myArray ) {
8
System . out . p r i n t l n ( e l e m e n t ) ;
9
}
10
}
11 }
Chapter 3
Object Oriented
Programming
3.1
Access Control
3.2
Wrapper Classes
p u b l i c c l a s s BoxingTest {
p u b l i c v o i d boxing ( ) {
i n t pInt = 420;
I n t e g e r wInt = new I n t e g e r ( p I n t ) ; // boxing
i n t p2 = wInt . i n t V a l u e ( ) ; // unboxing
}
p ubl ic void autoboxing (){
Modifier
private
default
protected
public
24
Universe
Yes
25
3.3
i n t pInt = 420;
I n t e g e r wInt = p I n t ; // a u t o b o x i n g
i n t p2 = wInt ; // autounboxing
3.3.1
Encapsulation
26
11 }
12
13 p u b l i c c l a s s EncapTest {
14
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
15
MyNumber my = new MyNumber ( ) ;
16
my . setNumber ( 4 5 ) ;
17
System . out . p r i n t l n (my . getNumber ( ) ) ;
18
}
19 }
At line 2, attribute number is a private member of MyNumber class,
so this attribute will not be accessible form other classes. But from the
EncapTest class we are accessing the number variable of MyNumber class
using set and get methods of MyNumber class.
3.3.2
Inheritance
c l a s s Cat{
public int x = 10;
public int y = 20;
p u b l i c v o i d show ( ) {
System . out . p r i n t l n ( x+ +y ) ;
}
}
p u b l i c c l a s s Rat e x t e n d s Cat{
public int z = 30;
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
Rat r = new Rat ( ) ;
r . show ( ) ;
System . out . p r i n t l n ( r . x+ +r . y+ +r . z ) ;
}
}
In the above code, Rat class extends Cat class, so Rat class become child
class of Cat class.
27
Overriding Methods
If a method is defined in a sub-class so that the name, return type, and
argument list must exactly those of a method in the parent class, then the
new method is said to override the old one. The overriding method can not
be less accessible than the method it overrides.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
c l a s s A{
p u b l i c v o i d show ( ) {
System . out . p r i n t l n ( Bird can f l y ) ;
}
}
p u b l i c c l a s s B e x t e n d s A{
p u b l i c v o i d show ( ) {
System . out . p r i n t l n ( Bird f l y i n t h e sky ) ;
}
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
B b = new B ( ) ;
b . show ( ) ;
}
}
In line 8 declare the method show(), which override the parent class
show() method of line 2.
Invoking Overriding Methods
A sub-class method can invoke a super-class method using the super keyword. In the following code, line 14 invokes the parent class method showDetails().
1 c l a s s Employee {
2
p u b l i c S t r i n g name = Mahmud ;
3
public f l o a t salary = 50000;
4
5
public void showDetails (){
6
System . out . p r i n t l n ( name+ + s a l a r y ) ;
7
}
8 }
9
10 p u b l i c c l a s s Manager e x t e n d s Employee {
11
p u b l i c S t r i n g department = E n g i n e e r i n g ;
12
13
public void showDetails (){
28
super . showDetails ( ) ;
System . out . p r i n t l n ( +department ) ;
}
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
Manager m = new Manager ( ) ;
m. s h o w D e t a i l s ( ) ;
}
29
m. s h o w D e t a i l s ( ) ;
Overloading Methods
We can declare several methods of same name in a class, which is known
as methods overloading. For overloading methods argument lists must be
different and return type can be different. In the following code, there are
four methods of same name with different argument, which is an example
of overloading methods.
1 p u b l i c c l a s s ABC{
2
int a , b , c ;
3
4
public void setValue (){
5
a =2;
6
b=4;
7
c =6;
8
}
9
10
public void setValue ( i n t a ){
11
t h i s . a=a ;
12
b=4;
13
c =6;
14
}
15
16
public void setValue ( i n t a , i n t b){
17
t h i s . a=a ;
18
t h i s . b=b ;
19
c =6;
20
}
21
22
public i n t setValue ( i n t a , i n t b , i n t c ){
23
t h i s . a=a ;
24
t h i s . b=b ;
25
t h i s . c=c ;
26
i n t z = a+b+c ;
27
return z ;
28
}
29 }
30
Overloading Constructors
We can declare several constructors with different arguments in a class,
which is overloading constructors.
1 public c l a s s Light {
2
int a , b , c ;
3
4
public Light (){
5
a =2;
6
b=4;
7
c =6;
8
}
9
10
public Light ( i n t a ){
11
t h i s . a=a ;
12
b=4;
13
c =6;
14
}
15
16
public Light ( i n t a , i n t b){
17
t h i s . a=a ;
18
t h i s . b=b ;
19
c =6;
20
}
21
22
public Light ( i n t a , i n t b , i n t c ){
23
t h i s . a=a ;
24
t h i s . b=b ;
25
t h i s . c=c ;
26
}
27 }
Example of Encapsulation, and Inheritance
Example with overriding, overloading, and Invoking
1
2
3
4
5
6
7
8
c l a s s Man{
p r i v a t e i n t weight ;
p u b l i c Man( i n t w e i g h t ) {
t h i s . w e i g h t=w e i g h t ;
}
p u b l i c v o i d setWeight ( i n t w e i g h t ) { // s e t e r method
31
9
i f ( weight >=50 && weight <=100){
10
t h i s . w e i g h t=w e i g h t ;
11
}
12
}
13
14
p u b l i c i n t getWeight ( ) { // g e t e r method
15
return weight ;
16
}
17
18
p u b l i c v o i d show ( ) {
19
System . out . p r i n t l n ( w e i g h t ) ;
20
}
21 }
22
23 p u b l i c c l a s s SuperMan e x t e n d s Man{
24
p u b l i c i n t power ;
25
26
p u b l i c SuperMan ( i n t power ) {
27
s u p e r ( 5 5 ) ; // i n v o k i n g p a r e n t c l a s s c o n s t r u c t o r
28
t h i s . power=power ;
29
}
30
31
p u b l i c SuperMan ( i n t weight , i n t power ) { // O v e r l o a d i n g
32
s u p e r ( w e i g h t ) ; // i n v o k i n g p a r e n t c l a s s c o n s t r u c t o r
33
t h i s . power=power ;
34
}
35
36
p u b l i c v o i d show ( ) { // o v e r r i d i n g method
37
s u p e r . show ( ) ; // i n v o k i n g p a r e n t c l a s s method
38
System . out . p r i n t l n ( power ) ;
39
}
40
41
p u b l i c v o i d show ( S t r i n g abc ) { // o v e r l o a d i n g method
42
System . out . p r i n t l n ( abc ) ;
43
}
44
45
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
46
SuperMan s = new SuperMan ( 1 0 ) ;
47
s . show ( ) ;
48
SuperMan s 1 = new SuperMan ( 5 0 , 1 0 0 ) ;
49
s 1 . show ( T i g e r ) ;
50
}
51 }
3.4
32
Polymorphism
c l a s s Man{
public void f l y (){
System . out . p r i n t l n ( Man can not f l y ) ;
}
}
c l a s s SuperMan e x t e n d s Man{
public void f l y (){
System . out . p r i n t l n ( Superman can f l y ) ;
}
}
p u b l i c c l a s s TestMan{
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
Man m = new SuperMan ( ) ; // polymorphism
m. f l y ( ) ;
}
}
3.5
Homogeneous Collection
3.6
Heterogeneous Collection
c l a s s Man{
33
3.7
In the Java technology, the Object class is the root of all classes. If a class
in Java programming does not extends any class then this class extends the
Object class by default.
1
2
3
5
6
7
p u b l i c c l a s s Car{
}
// o r we can d e c l a r e t h e Car c l a s s by
// e x t e n d i n g Object c l a s s . Both have same mining .
p u b l i c c l a s s Car e x t e n d s Object {
}
3.8
Using the instanceof operator, we can know the actual object of a class.
At line 22, we are passing object through argument list of test(Object x)
34
method but we do not know this x object is from which class. Then we use
instanceof operator to know object x is from which class by the conditions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
c l a s s Car{
p u b l i c v o i d abc ( ) {
System . out . p r i n t l n ( Car ) ;
}
}
c l a s s Bus{
p u b l i c v o i d xyz ( ) {
System . out . p r i n t l n ( Bus ) ;
}
}
public class Testinstanceof {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
Car c = new Car ( ) ;
Bus b = new Bus ( ) ;
T e s t i n s t a n c e o f t = new T e s t i n s t a n c e o f ( ) ;
t . test (c );
t . test (b ) ;
}
p u b l i c v o i d t e s t ( Object o b j ) {
i f ( o b j i n s t a n c e o f Car ) {
System . out . p r i n t l n ( Object i s o f Car c l a s s ) ;
} e l s e i f ( o b j i n s t a n c e o f Bus ) {
System . out . p r i n t l n ( Object i s o f Bus c l a s s ) ;
} else {
System . out . p r i n t l n ( Object i s not o f Car/Bus c l a s s ) ;
}
}
}
3.9
The method public boolean equals(Object obj) of Object class in the java.lang
package compares two objcets for equality. This method returns true, only
if the two objects being compared refer to the same object. On the other
hand, == operator performs an equivalent comparison. If x==y returns
true, that means x and y refer to the same object. We should override
the public int hashCode() method of Object class whenever we override the
35
equals method. A simple implementation could use a bit wise XOR on the
hash codes of the elements tested for equality.
1 p u b l i c c l a s s TestEquals {
2
public int x ;
3
public int y ;
4
5
p u b l i c TestEquals ( i n t x , i n t y ){
6
t h i s . x=x ;
7
t h i s . y=y ;
8
}
9
10
p u b l i c b o o l e a n e q u a l s ( Object o b j ) {
11
boolean r e s u l t = f a l s e ;
12
i f ( ( o b j != n u l l )&&( o b j i n s t a n c e o f T e s t E q u a l s ) ) {
13
TestEquals t = ( TestEquals ) obj ;
14
i f ( ( x==t . x)&&(y==t . y ) ) {
15
r e s u l t = true ;
16
}
17
}
18
return r e s u l t ;
19
}
20
21
p u b l i c i n t hashCode ( ) {
22
r e t u r n ( xy ) ;
23
}
24
25
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
26
T e s t E q u a l s t 1 = new T e s t E q u a l s ( 5 , 1 0 ) ;
27
T e s t E q u a l s t 2 = new T e s t E q u a l s ( 5 , 1 0 ) ;
28
i f ( t 1==t 2 ) {
29
System . out . p r i n t l n ( t 1 i s i d e n t i c a l t o t 2 ) ;
30
} else {
31
System . out . p r i n t l n ( t 1 i s not i d e n t i c a l t o t 2 ) ;
32
}
33
i f ( t1 . equals ( t2 )){
34
System . out . p r i n t l n ( t 1 i s e q u a l t o t 2 ) ;
35
} else {
36
System . out . p r i n t l n ( t 1 i s not e q u a l t o t 2 ) ;
37
}
38
System . out . p r i n t l n ( S e t t 2=t 1 ) ;
39
t 2=t 1 ;
40
i f ( t 1==t 2 ) {
41
System . out . p r i n t l n ( t 1 i s i d e n t i c a l t o t 2 ) ;
3.10
36
} else {
System . out . p r i n t l n ( t 1 i s not i d e n t i c a l t o t 2 ) ;
}
The toString() method of Object class convert an object to a String representation, which returns the class name and its reference address. Many
classes override toString to provide more useful information.
1 public class TesttoString {
2
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3
T e s t t o S t r i n g now = new T e s t t o S t r i n g ( ) ;
4
System . out . p r i n t l n ( now ) ;
5
// i s e q u i v a l e n t t o :
6
System . out . p r i n t l n ( now . t o S t r i n g ( ) ) ;
7
}
8 }
3.11
37
8
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
9
f o r ( i n t i =0; i <3; i ++){
10
System . out . p r i n t l n ( Count i s : + T e s t S t a t i c . count ) ;
11
T e s t S t a t i c . incrementCount ( ) ;
12
}
13
}
14 }
3.12
In the Java technology, the final keyword can be apply to the classes, methods, and variables. In Java, final classes can not be inherited, final methods
can not be override, and final variables are constant. Any attempt to change
the value of a final variable causes a complier error. A blank final variable
is a final variable that is not initialized in its declaration, but it can be
initialized later once only.
1 public f i n a l c l a s s TestFinal {
2
p u b l i c f i n a l i n t s tudent ID = 1 0 ;
3
4
public f i n a l void diplay (){
5
System . out . p r i n t l n ( F i n a l method can not be o v e r r i d e ) ;
6
}
7 }
3.13
abstract c l a s s Vehicle {
p u b l i c S t r i n g model = E c l a s s ;
public String year = 2008;
p u b l i c a b s t r a c t v o i d goFast ( ) ;
p u b l i c v o i d show ( ) {
System . out . p r i n t l n ( Model : +model+ Year : +y e a r ) ;
}
38
10 }
11
12 p u b l i c c l a s s Car e x t e n d s V e h i c l e {
13
p u b l i c v o i d goFast ( ) {
14
System . out . p r i n t l n ( Car can go f a s t ) ;
15
}
16
17
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
18
// Vehcle v = new V e h i c l e ( ) ; // c o m p i l e r e r r o r
19
Car c = new Car ( ) ;
20
c . show ( ) ;
21
c . goFast ( ) ;
22
}
23 }
3.14
Declaring Interface
3.14.1
39
t . bounce ( ) ;
t . setBounce ( 1 5 ) ;
}
In Java technology, a java class can only extend another one class, but can
implements one or more interfaces.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
a b s t r a c t c l a s s Animal {
p u b l i c v o i d type ( ) {
System . out . p r i n t l n ( Animal ) ;
}
p u b l i c a b s t r a c t v o i d name ( ) ;
}
i n t e r f a c e Cat{
p u b l i c a b s t r a c t v o i d jump ( ) ;
v o i d run ( ) ; // i t w i l l be a u t o m a t i c l y p u b l i c and a b s t r a c t
}
i n t e r f a c e Bird {
void f l y ( ) ;
}
p u b l i c c l a s s T i g e r e x t e n d s Animal implements Cat , Bird {
public void f l y (){
System . out . p r i n t l n ( T i g e r can t f l y ) ;
}
p u b l i c v o i d jump ( ) {
System . out . p r i n t l n ( T i g e r can jump ) ;
}
p u b l i c v o i d run ( ) {
System . out . p r i n t l n ( T i g e r can run ) ;
}
p u b l i c v o i d name ( ) {
3.15
40
System . out . p r i n t l n ( T i g e r ) ;
}
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
T i g e r t = new T i g e r ( ) ;
t . name ( ) ;
t . jump ( ) ;
t . run ( ) ;
t . fly ();
}
Exceptions
Exceptions are a mechanism used by many programming languages to describe what to do when errors happens. There are two types of exceptions in
Java programming, known as checked and unchecked exceptions. Checked
exceptions are those that the programmer can easily handle this type of exceptions like: file not found, and network failure etc. Unchecked exceptions
are arises from the conditions that are difficult for programmers to handle.
Unchecked exceptions are called runtime exceptions. In Java, Exception
class is the base class that represents checked and unchecked exceptions
and RuntimeException class is the base class that is used for the unchecked
exceptions.
1 p u b l i c c l a s s TestExceptionA {
2
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3
i n t sum = 0 ;
4
f o r ( i n t i =0; i <a r g s . l e n g t h ; i ++){
5
sum += I n t e g e r . p a r s e I n t ( a r g s [ i ] ) ;
6
}
7
System . out . p r i n t l n ( Sum : + sum ) ;
8
}
9 }
This program works if all of the command-line arguments are integers.
Compile : j a v a c TestExceptionA . j a v a
Run : j a v a TestExceptionA 2 4 6 8
Output : 20
But this program fails if any of the arguments are not integers;
Run : j a v a TestExceptionA 2 4 s i x 8
Output : Runtime E x c e p t i o n
3.15.1
41
To avoid the problem of code 3-20, we can use the try-catch statement. If
any exception or error occurred in the try block then the catch block will
execute. If try block execute without any error, then catch block will not
execute.
1 p u b l i c c l a s s TestExceptionB {
2
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3
i n t sum = 0 ;
4
f o r ( i n t i =0; i <a r g s . l e n g t h ; i ++){
5
try {
6
sum += I n t e g e r . p a r s e I n t ( a r g s [ i ] ) ;
7
} c a t c h ( NumberFormatException e ) {
8
System . out . p r i n t l n ( Index : + i+ i s not i n t e g e r . +e ) ;
9
}
10
}
11
System . out . p r i n t l n ( Sum : + sum ) ;
12
}
13 }
This program works if all or any of the command-line arguments are not
integers.
Compile : j a v a c TestExceptionB . j a v a
Run : j a v a TestExceptionA 2 4 s i x 8
Output: Index value of array 2 is not integer. java.lang.NumberFormatException:
invalid character at position 1 in six, Sum: 14
3.15.2
In Java , there can be multiple catch blocks after a try block, and each catch
block handing a different exception type.
1 public c l a s s Multi catch {
2
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3
try {
4
int i = 9/0;
5
System . out . p r i n t l n ( i ) ;
6
} c a t c h ( A r i t h m e t i c E x c e p t i o n e1 ) {
7
System . out . p r i n t l n ( A r i t h m e t i c E x c e p t i o n . + e1 ) ;
8
} c a t c h ( E x c e p t i o n e2 ) {
9
System . out . p r i n t l n ( E x c e p t i o n . + e2 ) ;
10
}
11
}
12 }
3.15.3
42
3.15.4
The finally clause defines a block of code that always executes. If try block
executes properly then catch block will not execute, and if try block will not
execute properly then catch block will execute, but the finally block must
executes.
1 public class Test finally {
2
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3
try {
4
int i = 9/0;
5
System . out . p r i n t l n ( i ) ;
6
} c a t c h ( A r i t h m e t i c E x c e p t i o n e1 ) {
7
System . out . p r i n t l n ( A r i t h m e t i c E x c e p t i o n . + e1 ) ;
8
}finally{
9
System . out . p r i n t l n ( f i n a l l y b l o c k must e x e c u t e s ) ;
10
}
11
}
12 }
The E x c e p t i o n D e c l a r e Rules
In Java , we can d e c l a r e e x c e p t i o n s by f o l l o w i n g :
1 . try catch f i n a l l y
2 . v o i d methodA ( ) throws IOException {}
3 . v o i d methodB ( ) throws IOException , OtherException {}
1 public c l a s s DeclareException {
2
p u b l i c v o i d methodA ( ) {
3
try {
4
} catch ( Exception e ){
5
System . out . p r i n t l n ( I f e r r o r i n t r y then c a t c h e x e c u t e ) ;
6
}finally{
7
System . out . p r i n t l n ( f i n a l l y must e x e c u t e s ) ;
8
}
9
}
10
p u b l i c v o i d methodB ( ) throws S e c u r i t y E x c e p t i o n {
}
43
11
p u b l i c v o i d methodC ( ) throws S e c u r i t y E x c e p t i o n , E x c e p t i o n {
}
12 }
3.15.5
The overriding method can declare only exceptions that are either the same
class or a subclass of the exception. For example, if the superclass method
throws an IOException, then the overriding method of superclass method
can throw an IOException, a FileNotFoundException, which is the subclass
of IOException, but not Exception, which is the superclass of IOException.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
p u b l i c c l a s s A{
p u b l i c v o i d methodA ( ) throws IOException {
}
c l a s s B e x t e n d s A{
p u b l i c v o i d methodA ( ) throws EOFException {
// Legal , b e c a u s e EOFException i s t h e s u b c l a s s o f IOException ;
}
}
c l a s s C e x t e n d s A{
p u b l i c v o i d methodA ( ) throws E x c e p t i o n {
// I l l e g a l , b e c a u s e E x c e p t i o n i s t h e s u p e r c l a s s o f IOException ;
}
}
3.15.6
Chapter 4
Command-Line Arguments
4.2
MyJavaBook ] \ $ j a v a c CommandLine . j a v a
MyJavaBook ] \ $ j a v a CommandLine 13 15 17
0 i n d e x i s : 13
1 i n d e x i s : 15
2 i n d e x i s : 17
Console Input/Output
Java 2 SDK support console I/O with three public variables in the java.lang.System
class:
1. System.out (System.out is a PrintStream object)
2. System.in (System.in is a InputStream object)
44
45
4.3
Scanner
46
12
}
13 }
4.4
File in Java
To access a physical file we have to create a File object, which contains the
address and name of the file. The FileReader class uses to read characters
from a file and the FileWriter class uses to write characters to a file. The
PrintWriter class is used the print() and println() methods.
4.4.1
1 import j a v a . i o . ;
2
3 public c l a s s WriteFile {
4
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
5
F i l e f i l e = new F i l e ( / home/ f a r i d /MyJavaBook , MyText . t x t ) ;
6
try {
7
InputStreamReader i s r = new InputStreamReader ( System . i n ) ;
8
B u f f e r e d R e a d e r i n = new B u f f e r e d R e a d e r ( i s r ) ;
9
P r i n t W r i t e r out = new P r i n t W r i t e r ( new F i l e W r i t e r ( f i l e ) ) ;
10
System . out . p r i n t l n ( Write S t r i n g : ) ;
11
String s t r = in . readLine ( ) ;
12
out . p r i n t l n ( s t r ) ;
13
in . close ( ) ;
14
out . c l o s e ( ) ;
15
} c a t c h ( IOException e ) {
16
e . printStackTrace ( ) ;
17
}
18
}
19 }
4.4.2
1
2
3
4
5
6
7
8
9
import j a v a . i o . ;
p u b l i c c l a s s ReadFile {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
F i l e f i l e = new F i l e ( / home/ f a r i d /MyJavaBook , MyText . t x t ) ;
try {
B u f f e r e d R e a d e r i n = new B u f f e r e d R e a d e r ( new F i l e R e a d e r ( f i l e ) ) ;
String s t r = in . readLine ( ) ;
w h i l e ( s t r != n u l l ) {
4.5
47
AWT is the basic GUI (Graphics User Interface) used for Java applications
and applets. Every GUI component that appears on the screen is a subclass
of the abstract class Component or MenuComponent. The class Container is
an abstract subclass of Component class, which permits other components
to be nested inside it. There are two types of containers: Window and
Panel. A Window is a free-standing native window on the display that is
independent of other containers. There are two important types of Window
containers: Frame and Dialog. A Frame is a window with a title and corners
that you can resize. A Dialog is a simple window and cannot have a menu
bar, you cannot resize it, but you can move it. A Panel must be contained
within another Container, or inside a web browsers window.
1 import j a v a . awt . ;
2 import j a v a . awt . e v e n t . ;
3
4 p u b l i c c l a s s FrameWithPanel implements WindowListener {
5
p r i v a t e Frame f ;
6
p r i v a t e Panel p ;
7
8
p u b l i c FrameWithPanel ( ) {
9
f = new Frame ( Frame T i t l e ) ;
10
p = new Panel ( ) ;
11
}
12
13
p u b l i c v o i d launchFrame ( ) {
14
f . addWindowListener ( t h i s ) ;
15
f . setSize (400 ,400);
16
f . setBackground ( C o l o r . r e d ) ;
17
f . setLayout ( n u l l ) ;
18
19
p . setSize (150 ,150);
48
p . setBackground ( C o l o r . g r e e n ) ;
f . add ( p ) ;
f . s e t V i s i b l e ( true ) ;
}
p u b l i c v o i d windowClosing ( WindowEvent e ) {
System . e x i t ( 0 ) ;
}
public
public
public
public
public
public
void
void
void
void
void
void
windowOpened ( WindowEvent e ) { }
w i n d o w I c o n i f i e d ( WindowEvent e ) { }
w i n d o w D e i c o n i f i e d ( WindowEvent e ) { }
windowClosed ( WindowEvent e ) { }
windowActivated ( WindowEvent e ) { }
windowDeactivated ( WindowEvent e ) { }
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
FrameWithPanel f p = new FrameWithPanel ( ) ;
f p . launchFrame ( ) ;
}
1 import j a v a . awt . ;
2 import j a v a . awt . e v e n t . ;
3
4 p u b l i c c l a s s TestMenuBar implements WindowListener , A c t i o n L i s t e n e r {
5
p r i v a t e Frame f ;
6
p r i v a t e MenuBar mb;
7
p r i v a t e Menu m1, m2, m3 ;
8
p r i v a t e MenuItem mi1 , mi2 , mi3 , mi4 ;
9
10
p u b l i c TestMenuBar ( ) {
11
f = new Frame ( MenuBar Example ) ;
12
mb = new MenuBar ( ) ;
13
m1 = new Menu( F i l e ) ;
14
m2 = new Menu( E di t ) ;
15
m3 = new Menu( Help ) ;
16
mi1 = new MenuItem ( New ) ;
17
mi2 = new MenuItem ( Save ) ;
18
mi3 = new MenuItem ( Load ) ;
19
mi4 = new MenuItem ( Quit ) ;
20
}
21
22
p u b l i c v o i d launchFrame ( ) {
mi4 . a d d A c t i o n L i s t e n e r ( t h i s ) ;
m1 . add ( mi1 ) ;
m1 . add ( mi2 ) ;
m1 . add ( mi3 ) ;
m1 . a d d S e p a r a t o r ( ) ;
m1 . add ( mi4 ) ;
mb. add (m1 ) ;
mb. add (m2 ) ;
mb. setHelpMenu (m3 ) ;
f . setMenuBar (mb ) ;
f
f
f
f
f
. addWindowListener ( t h i s ) ;
. setSize (400 ,400);
. setBackground ( C o l o r . r e d ) ;
. setLayout ( n u l l ) ;
. s e t V i s i b l e ( true ) ;
}
p u b l i c v o i d a c t i o n P e r f o r m e d ( ActionEvent e ) {
System . e x i t ( 0 ) ;
}
p u b l i c v o i d windowClosing ( WindowEvent e ) {
System . e x i t ( 0 ) ;
}
public
public
public
public
public
public
void
void
void
void
void
void
windowOpened ( WindowEvent e ) { }
w i n d o w I c o n i f i e d ( WindowEvent e ) { }
w i n d o w D e i c o n i f i e d ( WindowEvent e ) { }
windowClosed ( WindowEvent e ) { }
windowActivated ( WindowEvent e ) { }
windowDeactivated ( WindowEvent e ) { }
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
TestMenuBar tmb = new TestMenuBar ( ) ;
tmb . launchFrame ( ) ;
}
49
4.6
50
An event is issued, when the user performs and action at the user interface
level like: clicks a mouse or presses a key.
1 import j a v a . awt . ;
2 import j a v a . awt . e v e n t . ;
3
4 p u b l i c c l a s s EventHandle implements WindowListener , A c t i o n L i s t e n e r {
5
p r i v a t e Frame f ;
6
p r i v a t e Button b1 , b2 , b3 ;
7
private TextField t f ;
8
9
p u b l i c EventHandle ( ) {
10
f = new Frame ( Button Handling ) ;
11
b1 = new Button ( YES ) ;
12
b1 . setActionCommand ( y e s button ) ;
13
b2 = new Button ( NO ) ;
14
b2 . setActionCommand ( no button ) ;
15
b3 = new Button ( C l e a r ) ;
16
b3 . setActionCommand ( c l e a r button ) ;
17
t f = new T e x t F i e l d ( 3 0 ) ;
18
}
19
20
p u b l i c v o i d launchFrame ( ) {
21
b1 . a d d A c t i o n L i s t e n e r ( t h i s ) ;
22
b1 . s e t F o r e g r o u n d ( C o l o r . w h i t e ) ;
23
b1 . setBackground ( C o l o r . b l u e ) ;
24
25
b2 . a d d A c t i o n L i s t e n e r ( t h i s ) ;
26
b2 . s e t F o r e g r o u n d ( C o l o r . r e d ) ;
27
b2 . setBackground ( C o l o r . g r e e n ) ;
28
29
b3 . a d d A c t i o n L i s t e n e r ( t h i s ) ;
30
b3 . s e t F o r e g r o u n d ( C o l o r . b l u e ) ;
31
b3 . setBackground ( C o l o r . y e l l o w ) ;
32
33
t f . setForeground ( Color . blue ) ;
34
t f . setBackground ( C o l o r . w h i t e ) ;
35
36
f . s e t L a y o u t ( new FlowLayout ( ) ) ;
37
f . add ( b1 ) ;
38
f . add ( b2 ) ;
39
f . add ( b3 ) ;
4.6.1
1
f
f
f
f
f
. add ( t f ) ;
. addWindowListener ( t h i s ) ;
. setSize (250 ,150);
. setBackground ( C o l o r . r e d ) ;
. s e t V i s i b l e ( true ) ;
}
p u b l i c v o i d a c t i o n P e r f o r m e d ( ActionEvent e ) {
String str ;
i f ( e . getActionCommand()== y e s button ) {
s t r = You p r e s s YES button ;
t f . setText ( s t r ) ;
}
i f ( e . getActionCommand()==no button ) {
s t r = You p r e s s NO button ;
t f . setText ( s t r ) ;
}
i f ( e . getActionCommand()== c l e a r button ) {
str = ;
t f . setText ( s t r ) ;
}
}
p u b l i c v o i d windowClosing ( WindowEvent e ) {
System . e x i t ( 0 ) ;
}
public
public
public
public
public
public
void
void
void
void
void
void
windowOpened ( WindowEvent e ) { }
w i n d o w I c o n i f i e d ( WindowEvent e ) { }
w i n d o w D e i c o n i f i e d ( WindowEvent e ) { }
windowClosed ( WindowEvent e ) { }
windowActivated ( WindowEvent e ) { }
windowDeactivated ( WindowEvent e ) { }
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
EventHandle eh = new EventHandle ( ) ;
eh . launchFrame ( ) ;
}
Mouse Example
import j a v a . awt . ;
51
52
2 import j a v a . awt . e v e n t . ;
3
4 p u b l i c c l a s s MouseExample implements WindowListener , MouseMotionListen
5
p r i v a t e Frame f ;
6
private TextField t f ;
7
8
p u b l i c MouseExample ( ) {
9
f = new Frame ( Mouse Example ) ;
10
t f = new T e x t F i e l d ( 3 0 ) ;
11
}
12
13
p u b l i c v o i d launchFrame ( ) {
14
L ab el l a b e l = new La be l ( C l i c k and drag t h e mouse ) ;
15
f . add ( l a b e l , BorderLayout .NORTH) ;
16
f . add ( t f , BorderLayout .SOUTH) ;
17
f . addMouseMotionListener ( t h i s ) ;
18
f . addMouseListener ( t h i s ) ;
19
f . addWindowListener ( t h i s ) ;
20
f . setSize (300 ,200);
21
f . s e t V i s i b l e ( true ) ;
22
}
23
24
p u b l i c v o i d mouseDragged ( MouseEvent e ) {
25
S t r i n g s = Mouse dragged : X= +e . getX ()+ Y=+e . getY ( ) ;
26
t f . setText ( s ) ;
27
}
28
29
p u b l i c v o i d mouseEntered ( MouseEvent e ) {
30
S t r i n g s = The mouse e n t e r e d ;
31
t f . setText ( s ) ;
32
}
33
34
p u b l i c v o i d mouseExited ( MouseEvent e ) {
35
S t r i n g s = The mouse has l e f t t h e b u i l d i n g ;
36
t f . setText ( s ) ;
37
}
38
39
p u b l i c v o i d mousePressed ( MouseEvent e ) { }
40
p u b l i c v o i d mouseReleased ( MouseEvent e ) { }
41
p u b l i c v o i d mouseMoved ( MouseEvent e ) { }
42
p u b l i c v o i d mouseClicked ( MouseEvent e ) { }
43
44
p u b l i c v o i d windowClosing ( WindowEvent e ) {
45
System . e x i t ( 0 ) ;
53
Table 4.1: Table Color class static constants and RGB values.
Color Constant
Color
RGB value
public final static Color orange
Orange
255, 200, 0
public final static Color pink
Pink
255, 175, 175
public final static Color cyan
Cyan
0, 255, 255
public final static Color magenta
Magenta
255, 0, 255
public final static Color yellow
Yellow
255, 255, 0
public final static Color black
Black
0, 0, 0
public final static Color white
White
255, 255, 255
public final static Color gray
Gray
128, 128, 128
public final static Color lightGray Light Gray 192, 192, 192
public final static Color darkGray Dark Gray
64, 64, 64
public final static Color red
Red
255, 0, 0
public final static Color green
Green
0, 255, 0
public final static Color blue
Blue
0, 0, 255
46
47
48
49
50
51
52
53
54
55
56
57
58
59 }
4.7
}
public
public
public
public
public
public
void
void
void
void
void
void
windowOpened ( WindowEvent e ) { }
w i n d o w I c o n i f i e d ( WindowEvent e ) { }
w i n d o w D e i c o n i f i e d ( WindowEvent e ) { }
windowClosed ( WindowEvent e ) { }
windowActivated ( WindowEvent e ) { }
windowDeactivated ( WindowEvent e ) { }
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
MouseExample me = new MouseExample ( ) ;
me . launchFrame ( ) ;
}
Colors in Java
In Java, we can control the colors used for the foreground using setForeground() method and the background using setBackground() method of
AWT components. The setForeground() and setBackground() methods take
an arguments that is an instance of of java.awt.Color class. We can use the
constant colors referred to as Color.red, Color.blue, Color.green, Color.yellow,
and so on. We can also construct a specific Color object by specifying the
color by a combination of three byte-sized integers (0-255), one for each
primary color: red, green, and blue.
1
2
import j a v a . awt . ;
import j a v a . awt . e v e n t . ;
54
3
4 p u b l i c c l a s s T e s t C o l o r s implements WindowListener , A c t i o n L i s t e n e r {
5
p r i v a t e Frame f ;
6
p r i v a t e Button b ;
7
8
public TestColors (){
9
f = new Frame ( Frame T i t l e ) ;
10
b = new Button ( Change C o l o r ) ;
11
b . setActionCommand ( button p r e s s ) ;
12
}
13
14
p u b l i c v o i d launchFrame ( ) {
15
b . addActionListener ( t h i s ) ;
16
b . setForeground ( Color . red ) ;
17
b . setBackground ( C o l o r . y e l l o w ) ;
18
f . add ( b ) ;
19
f . addWindowListener ( t h i s ) ;
20
f . setSize (300 ,300);
21
f . setBackground ( C o l o r . g r e e n ) ;
22
f . s e t L a y o u t ( new FlowLayout ( ) ) ;
23
f . s e t V i s i b l e ( true ) ;
24
}
25
26
p u b l i c v o i d a c t i o n P e r f o r m e d ( ActionEvent e ) {
27
int x , y , z ;
28
i f ( e . getActionCommand()== button p r e s s ) {
29
x = ( i n t ) ( Math . random ( ) 1 0 0 ) ;
30
y = ( i n t ) ( Math . random ( ) 1 0 0 ) ;
31
z = ( i n t ) ( Math . random ( ) 1 0 0 ) ;
32
C o l o r c = new C o l o r ( x , y , z ) ;
33
f . setBackground ( c ) ;
34
}
35
}
36
37
p u b l i c v o i d windowClosing ( WindowEvent e ) {
38
System . e x i t ( 0 ) ;
39
}
40
41
p u b l i c v o i d windowOpened ( WindowEvent e ) { }
42
p u b l i c v o i d w i n d o w I c o n i f i e d ( WindowEvent e ) { }
43
p u b l i c v o i d w i n d o w D e i c o n i f i e d ( WindowEvent e ) { }
44
p u b l i c v o i d windowClosed ( WindowEvent e ) { }
45
p u b l i c v o i d windowActivated ( WindowEvent e ) { }
46
p u b l i c v o i d windowDeactivated ( WindowEvent e ) { }
55
47
48
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
49
T e s t C o l o r s t c = new T e s t C o l o r s ( ) ;
50
t c . launchFrame ( ) ;
51
}
52 }
4.8
Layout Managers
In Java programming, the layout manager manages the layout of components in a container, which we can change by calling setLayout() method.
The layout manage is responsible for deciding the layout policy and size of
each of its containers child components. The following layout managers are
included with the Java programming language:
1. FlowLayout The FlowLayout is the default layout manager of Panel
and Applet.
2. BorderLayout The BorderLayout is the default layout manager of
Window, Dialog, and Frame.
3. Layout The GridLayout provides flexibility for placing components.
4. CardLayout The CardLayout provides functionality comparable to a
primitive tabbed panel.
5. GridBagLayout FlowLayout manager uses line-by-line technique to place the components
in a container. Each time a line is filled, a new line is started. It does not
consider the size of components.
1 import j a v a . awt . ;
2 import j a v a . awt . e v e n t . ;
3
4 p u b l i c c l a s s FlowExample implements WindowListener {
5
p r i v a t e Frame f ;
6
p r i v a t e Button b1 , b2 , b3 ;
7
8
p u b l i c FlowExample ( ) {
9
f = new Frame ( FlowLayout ) ;
10
b1 = new Button ( Button 1 ) ;
11
b2 = new Button ( Button 2 ) ;
12
b3 = new Button ( Button 3 ) ;
13
}
56
p u b l i c v o i d launchFrame ( ) {
f . s e t L a y o u t ( new FlowLayout ( ) ) ;
// f . s e t L a y o u t ( new FlowLayout ( FlowLayout . LEFT ) ) ;
// f . s e t L a y o u t ( new FlowLayout ( FlowLayout . RIGHT ) ) ;
// f . s e t L a y o u t ( new FlowLayout ( FlowLayout .CENTER) ) ;
// f . s e t L a y o u t ( new FlowLayout ( FlowLayout . RIGHT, 2 0 , 3 0 ) ) ;
f . add ( b1 ) ;
f . add ( b2 ) ;
f . add ( b3 ) ;
f . addWindowListener ( t h i s ) ;
f . setSize (250 ,150);
f . setBackground ( C o l o r . r e d ) ;
f . s e t V i s i b l e ( true ) ;
}
p u b l i c v o i d windowClosing ( WindowEvent e ) {
System . e x i t ( 0 ) ;
}
public
public
public
public
public
public
void
void
void
void
void
void
windowOpened ( WindowEvent e ) { }
w i n d o w I c o n i f i e d ( WindowEvent e ) { }
w i n d o w D e i c o n i f i e d ( WindowEvent e ) { }
windowClosed ( WindowEvent e ) { }
windowActivated ( WindowEvent e ) { }
windowDeactivated ( WindowEvent e ) { }
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
FlowExample f e = new FlowExample ( ) ;
f e . launchFrame ( ) ;
}
import j a v a . awt . ;
import j a v a . awt . e v e n t . ;
p u b l i c c l a s s BorderExample implements WindowListener {
p r i v a t e Frame f ;
p r i v a t e Button b1 , b2 , b3 , b4 , b5 ;
p u b l i c BorderExample ( ) {
57
void
void
void
void
void
void
windowOpened ( WindowEvent e ) { }
w i n d o w I c o n i f i e d ( WindowEvent e ) { }
w i n d o w D e i c o n i f i e d ( WindowEvent e ) { }
windowClosed ( WindowEvent e ) { }
windowActivated ( WindowEvent e ) { }
windowDeactivated ( WindowEvent e ) { }
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
BorderExample be = new BorderExample ( ) ;
be . launchFrame ( ) ;
}
import j a v a . awt . ;
import j a v a . awt . e v e n t . ;
p u b l i c c l a s s GridExample implements WindowListener {
p r i v a t e Frame f ;
p r i v a t e Button b1 , b2 , b3 , b4 , b5 , b6 ;
p u b l i c GridExample ( ) {
f = new Frame ( FlowLayout ) ;
b1 = new Button ( Button 1 ) ;
b2 = new Button ( Button 2 ) ;
b3 = new Button ( Button 3 ) ;
b4 = new Button ( Button 4 ) ;
b5 = new Button ( Button 5 ) ;
b6 = new Button ( Button 6 ) ;
}
p u b l i c v o i d launchFrame ( ) {
f . s e t L a y o u t ( new GridLayout ( 3 , 2 ) ) ;
f . add ( b1 ) ;
f . add ( b2 ) ;
f . add ( b3 ) ;
f . add ( b4 ) ;
f . add ( b5 ) ;
f . add ( b6 ) ;
f . addWindowListener ( t h i s ) ;
f . setSize (300 ,300);
f . setBackground ( C o l o r . r e d ) ;
f . s e t V i s i b l e ( true ) ;
}
p u b l i c v o i d windowClosing ( WindowEvent e ) {
System . e x i t ( 0 ) ;
}
public
public
public
public
public
public
void
void
void
void
void
void
windowOpened ( WindowEvent e ) { }
w i n d o w I c o n i f i e d ( WindowEvent e ) { }
w i n d o w D e i c o n i f i e d ( WindowEvent e ) { }
windowClosed ( WindowEvent e ) { }
windowActivated ( WindowEvent e ) { }
windowDeactivated ( WindowEvent e ) { }
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
GridExample ge = new GridExample ( ) ;
ge . launchFrame ( ) ;
}
58
4.9
59
4.9.1
Fonts in Java
In Java, Font class manages the font of Strings. The constructor of Font
class takes three arguments: the font name, font style, and font size. The
font name is any font currently supported by the system where the program
is running such as standard Java fonts Monospaced, SansSerif, and Serif.
The font style is Font.PLAIN, Font.ITALIC, or Font.BOLD. Font styles can
be used in combination such as: Font.ITALIC + Font.BOLD.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import j a v a . awt . ;
import j a v a . awt . e v e n t . ;
import j a v a x . swing . ;
p u b l i c c l a s s TestFonts e x t e n d s JFrame{
p r i v a t e s t a t i c f i n a l l o n g s e r i a l V e r s i o n U I D =0;
p u b l i c TestFonts ( ) {
s u p e r ( Font Examples ) ;
s e t S i z e (300 , 150);
show ( ) ;
}
p u b l i c v o i d p a i n t ( G ra ph ic s g ) {
g . d r a w S t r i n g ( Welcome t o Java . , 2 0 , 5 0 ) ;
g . setC olor ( Color . red ) ;
g . s e t F o n t ( new Font ( Monospaced , Font .BOLD, 1 4 ) ) ;
g . d r a w S t r i n g ( Welcome t o Java . , 2 0 , 7 0 ) ;
g . setC olor ( Color . blue ) ;
g . s e t F o n t ( new Font ( S a n s S e r i f , Font .BOLD + Font . ITALIC , 1 6 ) ) ;
g . d r a w S t r i n g ( Welcome t o Java . , 2 0 , 9 0 ) ;
}
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
TestFonts t f = new TestFonts ( ) ;
t f . addWindowListener (
new WindowAdapter ( ) {
p u b l i c v o i d windowClosing ( WindowEvent e ) {
System . e x i t ( 0 ) ;
60
30
}
31
}
32
);
33
}
34 }
4.9.2
Code 4-15 presents a variety if Graphics methods for drawing lines, rectangles, and ovals.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import j a v a . awt . ;
import j a v a . awt . e v e n t . ;
import j a v a x . swing . ;
p u b l i c c l a s s TestLineRectOval e x t e n d s JFrame{
p r i v a t e s t a t i c f i n a l l o n g s e r i a l V e r s i o n U I D =0;
p u b l i c TestLineRectOval ( ) {
s u p e r ( L i n e s R a c t a n g l e s Ovals ) ;
s e t S i z e (360 , 450);
show ( ) ;
}
p u b l i c v o i d p a i n t ( G ra ph ic s g ) {
g . setC olor ( Color . red ) ;
g . drawLine ( 5 0 , 4 0 , 3 0 0 , 4 0 ) ;
g . setC olor ( Color . blue ) ;
g . drawRect ( 5 0 , 6 0 , 1 0 0 , 6 0 ) ;
g . f i l l R e c t (200 ,60 , 100 , 6 0 ) ;
g . s e t C o l o r ( C o l o r . cyan ) ;
g . drawRoundRect ( 5 0 , 1 5 0 , 1 0 0 , 6 0 , 5 0 , 5 0 ) ;
g . fillRoundRect (200 ,150 , 100 , 60 , 50 , 5 0 ) ;
g . setC olor ( Color . yellow ) ;
g . draw3DRect ( 5 0 , 2 5 0 , 1 0 0 , 6 0 , t r u e ) ;
g . f i l l 3 D R e c t (200 ,250 , 100 , 60 , true ) ;
g . s e t C o l o r ( C o l o r . magenta ) ;
g . drawOval ( 5 0 , 3 5 0 , 1 0 0 , 6 0 ) ;
g . f i l l O v a l (200 ,350 , 100 , 6 0 ) ;
}
61
34
35
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
36
TestLineRectOval t l r o = new TestLineRectOval ( ) ;
37
t l r o . addWindowListener (
38
new WindowAdapter ( ) {
39
p u b l i c v o i d windowClosing ( WindowEvent e ) {
40
System . e x i t ( 0 ) ;
41
}
42
}
43
);
44
}
45 }
Code 4-16 provides an password example using Jlabel, JtextField, JpasswordField, and Jbutton.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import j a v a . awt . ;
import j a v a . awt . e v e n t . ;
import j a v a x . swing . ;
p u b l i c c l a s s Password e x t e n d s JFrame{
p r i v a t e s t a t i c f i n a l l o n g s e r i a l V e r s i o n U I D =0;
private
private
private
private
JLabel l 1 , l 2 ;
JTextField t1 ;
J P a s s w o r d F i e l d pw ;
JButton b1 , b2 ;
p u b l i c Password ( ) {
s u p e r ( Password Example ) ;
C o n t a i n e r c = getContentPane ( ) ;
c . s e t L a y o u t ( new FlowLayout ( ) ) ;
l 1 = new JLabel ( Enter User Name
c . add ( l 1 ) ;
);
t 1 = new J T e x t F i e l d ( 1 5 ) ;
c . add ( t 1 ) ;
l 2 = new JLabel ( Enter Password
c . add ( l 2 ) ;
pw = new J P a s s w o r d F i e l d ( 1 0 ) ;
c . add (pw ) ;
);
62
30
b1 = new JButton ( Enter ) ;
31
b1 . a d d A c t i o n L i s t e n e r (
32
new A c t i o n L i s t e n e r ( ) {
33
p u b l i c v o i d a c t i o n P e r f o r m e d ( ActionEvent e ) {
34
i f ( t 1 . getText ( ) . e q u a l s ( f a r i d ) && pw . getText ( ) . e q u a l s ( 1 2 3 4
35
JOptionPane . showMessageDialog ( n u l l , Welcome t o Java ) ;
36
} else {
37
JOptionPane . showMessageDialog ( n u l l , I n c o r r e c t u s e r name
38
}
39
}
40
}
41
);
42
c . add ( b1 ) ;
43
44
b2 = new JButton ( Cancel ) ;
45
b2 . a d d A c t i o n L i s t e n e r (
46
new A c t i o n L i s t e n e r ( ) {
47
p u b l i c v o i d a c t i o n P e r f o r m e d ( ActionEvent e ) {
48
String s = ;
49
t1 . setText ( s ) ;
50
pw . s e t T e x t ( s ) ;
51
}
52
}
53
);
54
c . add ( b2 ) ;
55
56
s e t S i z e (300 , 125);
57
show ( ) ;
58
}
59
60
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
61
Password PW = new Password ( ) ;
62
PW. addWindowListener (
63
new WindowAdapter ( ) {
64
p u b l i c v o i d windowClosing ( WindowEvent e ) {
65
System . e x i t ( 0 ) ;
66
}
67
}
68
);
69
}
70 }
Example of Jcomponents such as: JcheckBox, JradioButton, JcomboBox,
Jlist, and JTextArea provided in code 4-17.
63
import j a v a . awt . ;
import j a v a . awt . e v e n t . ;
import j a v a x . swing . ;
p u b l i c c l a s s TestJComt e x t e n d s JFrame{
p r i v a t e s t a t i c f i n a l l o n g s e r i a l V e r s i o n U I D =0;
private
private
private
private
private
private
private
JCheckBox bold , i t a l i c ;
JRadioButton male , f e m a l e ;
ButtonGroup radioGroup ;
JComboBox cBox ;
S t r i n g [ ] s t r 1 = { s p r i n g , summer , f a l l } ;
JList colorList ;
S t r i n g [ ] s t r 2 = {Red , Green , Blue , Black , White ,
Orange , Pink , Magenta , Sky , Cya
p r i v a t e JTextArea t a 1 ;
p u b l i c TestJComt ( ) {
s u p e r ( Test JComponents ) ;
C o n t a i n e r c = getContentPane ( ) ;
c . s e t L a y o u t ( new FlowLayout ( ) ) ;
b o l d = new JCheckBox ( Bold ) ;
c . add ( b o l d ) ;
i t a l i c = new JCheckBox ( I t a l i c ) ;
c . add ( i t a l i c ) ;
male = new JRadioButton ( Male ) ;
c . add ( male ) ;
f e m a l e = new JRadioButton ( Female ) ;
c . add ( f e m a l e ) ;
radioGroup = new ButtonGroup ( ) ;
radioGroup . add ( male ) ;
radioGroup . add ( f e m a l e ) ;
cBox = new JComboBox ( s t r 1 ) ;
c . add ( cBox ) ;
c o l o r L i s t = new J L i s t ( s t r 2 ) ;
c o l o r L i s t . setVisibleRowCount ( 5 ) ;
c . add ( new J S c r o l l P a n e ( c o l o r L i s t ) ) ;
S t r i n g s = Java i s a o b j e c t o r i e n t e d programming l a n g u a g e ;
t a 1 = new JTextArea ( s , 1 0 , 1 5 ) ;
64
45
c . add ( new J S c r o l l P a n e ( t a 1 ) ) ;
46
47
s e t S i z e (200 , 350);
48
show ( ) ;
49
}
50
51
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
52
TestJComt j c = new TestJComt ( ) ;
53
j c . addWindowListener (
54
new WindowAdapter ( ) {
55
p u b l i c v o i d windowClosing ( WindowEvent e ) {
56
System . e x i t ( 0 ) ;
57
}
58
}
59
);
60
}
61 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import j a v a . awt . ;
import j a v a . awt . e v e n t . ;
import j a v a x . swing . ;
p u b l i c c l a s s OpenFile e x t e n d s JFrame{
p r i v a t e s t a t i c f i n a l l o n g s e r i a l V e r s i o n U I D =0;
p r i v a t e JButton b1 ;
private JFileChooser j f c ;
p u b l i c OpenFile ( ) {
s u p e r ( F i l e Opener ) ;
b1 = new JButton ( Open F i l e Chooser ) ;
b1 . a d d A c t i o n L i s t e n e r (
new A c t i o n L i s t e n e r ( ) {
p u b l i c v o i d a c t i o n P e r f o r m e d ( ActionEvent e ) {
abc ( ) ;
}
}
);
getContentPane ( ) . add ( b1 , BorderLayout .NORTH) ;
s e t S i z e (300 , 200);
show ( ) ;
}
p r i v a t e v o i d abc ( ) {
j f c = new J F i l e C h o o s e r ( ) ;
65
27
j f c . showOpenDialog ( t h i s ) ;
28
}
29
30
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
31
OpenFile o f = new OpenFile ( ) ;
32
o f . addWindowListener (
33
new WindowAdapter ( ) {
34
p u b l i c v o i d windowClosing ( WindowEvent e ) {
35
System . e x i t ( 0 ) ;
36
}
37
}
38
);
39
}
40 }
Chapter 5
Java Threads
Modern computer performs multiple jobs at the same time. Thread is the
process of multi-tasking using CPU, which performs computations. A thread
or execution context is composed of three main parts:
1. A virtual CPU.
2. The code that the CPU executes.
3. The data on which the code work.
The class java.lang.Thread enables us to create and control threads. A
process is a program in execution. One or more threads a process. A thread
is composed of CPU, code, and data. Code can share multiple threads, two
threads can share the same code. We can create thread by implementing
Runnable interface (Code 5-1) or by extending Thread class (Code 5-2).
Thread class implements the Runnable interface itself. The Runnable interface provides the public void run() method. We override the run() method,
which contain the code for CPU execution.
A newly created thread does not start running automatically, we must
call its start() method.
1
2
3
4
5
6
7
67
8
}
9
10
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
11
ThreadTest t = new ThreadTest ( ) ;
12
Thread t h r e a d 1 = new Thread ( t ) ;
13
Thread t h r e a d 2 = new Thread ( t ) ;
14
Thread t h r e a d 3 = new Thread ( t ) ;
15
thread1 . s t a r t ( ) ;
16
thread2 . s t a r t ( ) ;
17
thread3 . s t a r t ( ) ;
18
}
19 }
1 p u b l i c c l a s s MyThread e x t e n d s Thread {
2
p u b l i c v o i d run ( ) {
3
i n t i =1;
4
w h i l e ( i <=100){
5
System . out . p r i n t l n ( i : + i ) ;
6
i ++;
7
}
8
}
9
10
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
11
Thread t h r e a d 1 = new MyThread ( ) ;
12
Thread t h r e a d 2 = new MyThread ( ) ;
13
Thread t h r e a d 3 = new MyThread ( ) ;
14
thread1 . s t a r t ( ) ;
15
thread2 . s t a r t ( ) ;
16
thread3 . s t a r t ( ) ;
17
}
18 }
The sleep() is a static method in the Thread class, it operates on the
current thread and is referred to as Thread.sleep(x); where x is the minimum
number of millisecond.
1
2
3
4
5
6
7
8
9
68
p u b l i c Producer ( MyStack s ) {
stack = s ;
}
p u b l i c v o i d run ( ) {
char c ;
f o r ( i n t i =0; i <50; i ++){
c = ( c h a r ) ( Math . random ()26+ A ) ;
s t a c k . push ( c ) ;
System . out . p r i n t l n ( Producer : +c ) ;
try {
Thread . s l e e p ( ( i n t ) ( Math . random ( ) 3 0 0 ) ) ;
} catch ( InterruptedException e ){
System . out . p r i n t l n ( e ) ;
}
}
}
}
c l a s s Consumer implements Runnable {
p r i v a t e MyStack s t a c k ;
p u b l i c Consumer ( MyStack s ) {
stack = s ;
}
p u b l i c v o i d run ( ) {
char c ;
f o r ( i n t i =0; i <50; i ++){
c = s t a c k . pop ( ) ;
System . out . p r i n t l n ( Consumer : +c ) ;
try {
Thread . s l e e p ( ( i n t ) ( Math . random ( ) 3 0 0 ) ) ;
} catch ( InterruptedException e ){
System . out . p r i n t l n ( e ) ;
}
}
}
}
pub lic c l a s s StackTest {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
MyStack s = new MyStack ( ) ;
69
5.2
70
import j a v a . u t i l . ;
p u b l i c c l a s s ListExample {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a g r s ) {
L i s t l i s t = new A r r a y L i s t ( ) ;
l i s t . add ( One ) ;
l i s t . add ( 2 nd ) ;
l i s t . add ( 3 rd ) ;
l i s t . add ( new I n t e g e r ( 6 ) ) ;
71
10
l i s t . add ( new F l o a t ( 7 . 7 F ) ) ;
11
l i s t . add ( 2 nd ) ; // d u p l i c a t e i s added
12
System . out . p r i n t l n ( l i s t ) ;
13
}
14 }
5.3
import j a v a . n e t . ;
import j a v a . i o . ;
public class ClientServer {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
try {
S o c k e t s 1 = new S o c k e t ( 1 2 7 . 0 . 0 . 1 , 5 4 3 2 ) ;
InputStream i s = s 1 . g e t I n p u t S t r e a m ( ) ;
72
9
DataInputStream d i s = new DataInputStream ( i s ) ;
10
System . out . p r i n t l n ( d i s . readUTF ( ) ) ;
11
dis . close ( ) ;
12
s1 . c l o s e ( ) ;
13
} c a t c h ( ConnectException e1 ) {
14
System . out . p r i n t l n ( e1 ) ;
15
} c a t c h ( IOException e2 ) {
16
e2 . p r i n t S t a c k T r a c e ( ) ;
17
}
18
}
19 }