Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
35 views

Java Basics

This document discusses object oriented programming in Java. It provides details about the professor teaching the course, an overview of what Java is and its brief history. It also describes Java applets, the Java Virtual Machine, automatic memory management, and includes simple Java programs as examples. Key concepts covered include classes, attributes, constructors, methods, and the structure of a basic Java program.

Uploaded by

Nafis Hossain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Java Basics

This document discusses object oriented programming in Java. It provides details about the professor teaching the course, an overview of what Java is and its brief history. It also describes Java applets, the Java Virtual Machine, automatic memory management, and includes simple Java programs as examples. Key concepts covered include classes, attributes, constructors, methods, and the structure of a basic Java program.

Uploaded by

Nafis Hossain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Chapter 1

Object Oriented
Programming (Java)

1.1 Faculty Details


Prof. Dr. Dewan Md. Farid
Department of Computer Science and Engineering
United International University
Room: 533(B) at UIU Bhaban
Cell: 01715-833499 and Email: dewanfarid@cse.uiu.ac.bd
http://cse.uiu.ac.bd/profiles/dewanfarid/

1.2 What is Java?


Java is a computer programming language that is used to build softwares.
It is also an application, development, and deployment environment. Java
is object oriented programming language to help us visualize the program in
real-life terms. The syntax of Java is similar to C and C++ based language.
Java applications are typically compiled to bytecode (class file) that can run
on any Java Virtual Machine (JVM) regardless of computer architecture.

1.2.1 Brief History of Java


In 1990, Sun Microsystems began a research project named Green to de-
velop the C and C++ based language. James Gosling, a network software
designer was assigned to this project. Gosling’s 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 re-
named Java). Finally, in 1996, Java arrived in the market as a programming
language.

1
CHAPTER 1. OBJECT ORIENTED PROGRAMMING (JAVA) 2

Table 1.1: Major release versions of Java.


Version Date
JDK 1.0 January 23, 1996
JDK 1.1 February 19, 1997
J2SE 1.2 December 8, 1998
J2SE 1.3 May 8, 2000
J2SE 1.4 February 6, 2002
J2SE 5.0 September 30, 2004
Java SE 6 December 11, 2006
Java SE 7 July 28, 2011

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 Java’s core
code available under free software/open-source distribution terms.

1.3 What is Java Applets?


Applets are Java programs that reside on web servers, download by a browser
to a client’s 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 Java Virtual Machine (JVM)


A Java virtual machine is a software that is capable of executing Java byte-
code. 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 applica-
tion 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 point-
CHAPTER 1. OBJECT ORIENTED PROGRAMMING (JAVA) 3

ers, 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 Automatic Memory Management


Many programming languages like C and C++ permit the memory to be
allocated dynamically at runtime. After the allocated memory is no longer
required, the program or runtime environment should de-allocated the mem-
ory. If the program does not de-allocate the memory that can crash even-
tually when there is no memory left for the system to allocate. These types
of programs are said memory leaks. Java overcome this problem by using
garbage collection. It provides a system level thread that tracks each mem-
ory 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 A Simple Java Application


Java is powerful programming language and it is used to develop robust
applications.

1.6.1 Simple Java Program for beginners


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
CHAPTER 1. OBJECT ORIENTED PROGRAMMING (JAVA) 4

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 Wel-
come.class by typing the command java Welcome

Line 1 declares the user-defined class named Welcome. Every Java pro-
gram 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.
String[] args The main() method declares the single parameter of
String array named args. If the program is given any arguments
on its command line, these are passed into the main() method
through this args array of String type.

Line 3 displays or prints a line of text in the command window. System.out


is known as the standard output object.

Line 4 end of the main() method.

Line 5 end of the Welcome class.

1.6.2 Another Java Program for beginners


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 p u b l i c c l a s s Welcome2{
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 H e l l o h e l l o = new H e l l o ( ) ;
4 hello . display ( ) ;
5 }
6 }
7
8 c l a s s Hello {
9 public void display (){
CHAPTER 1. OBJECT ORIENTED PROGRAMMING (JAVA) 5

10 System . out . p r i n t l n ( ” Welcome t o Java world ” ) ;


11 }
12 }

Line 3 creates an object of Hello class named hello


Line 4 call the display() method of Hello class using the hello object
with the dot notation.
Line 8 declares a user-defined class Hello with default access control.
Line 9 declares a user-defined method named display().

1.7 Declaring Classes, Attributes, Constructors,


and Methods
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 con-
structor. 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.
CHAPTER 1. OBJECT ORIENTED PROGRAMMING (JAVA) 6

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 ) {
19 MyDate d a t e = new MyDate ( ) ;
20 d a t e . showDate ( ) ;
21 }
22 }

1.8 Source File Layout


A Java technology source file declares firstly package statement (only one
package), secondly import statements, and finally classes. Which are follow-
ing 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 state-
ment 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
CHAPTER 1. OBJECT ORIENTED PROGRAMMING (JAVA) 7

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 }
To compile this code, open a command window or terminal and change to
the directory where the program is saved and type javac -d . Account.java
then a package or folder will be create in the same directory named bank-
ingPrj. Now you can run this Account.class file in bankingPrj package
by typing the command java bankingPrj.Account
1 package b a n k i n g P r j ;
2
3 import b a n k i n g P r j . Account ;
4
5 p u b l i c c l a s s Coustomer {
6 p u b l i c S t r i n g name = ” James Bond ” ;
7
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 Account a c c = new Account ( ) ;
10 a c c . showAccName ( ) ;
11 Coustomer c o u s = new Coustomer ( ) ;
12 System . out . p r i n t l n ( c o u s . name ) ;
13 }
14 }
Similarly, we can compile and run this code.

Line 3 we import the Account class from bankingPrj package.

Line 9 we create object of Account class.

Line 10 we call the method of Account class.


CHAPTER 1. OBJECT ORIENTED PROGRAMMING (JAVA) 8

1.9 Comments and Semicolons


1.9.1 Java Comments
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
11 ∗/
12 }

1.9.2 Semicolons
In the Java source code a statement is one or more lines of code terminated
with a semicolons (;).
1 public c l a s s TestSemicolon {
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 a =10 , b=20 , c ;
4 c = a+b ;
5 System . out . p r i n t l n ( c ) ;
6 }
7 }

1.10 Blocks
A block as a group of statements that are collected together called a com-
pound 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
CHAPTER 1. OBJECT ORIENTED PROGRAMMING (JAVA) 9

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 ) {
20 BlockT est bt = new Blo ckTes t ( ) ;
21 bt . show ( ) ;
22 }
23 }

1.11 Java Identifiers


In Java technology, identifier is a name given to a variable, class, or method.
Java identifier start with a letter, underscore ( ), or dollar sign ($). Subse-
quence characters can be digits. Identifiers are case sensitive and have no
maximum length. An identifier cannot be a keyword, but it can contain a
keyword as part of its name.
Examples of some legal identifiers: identifier, userName, a, $b,
u i u, $, user789, new java class, this is a large identifier
Examples of some illegal identifiers: :a, -b, uiu#, 7ok, new, class

1.12 The this Reference


In Java technology, this keyword is used to resolved ambiguity between
instance variables and parameters. It is also used to pass the current object
as a parameter to another method.
1 p u b l i c c l a s s AddNumbers{
2 p r i v a t e i n t num1 , num2 , r e s u l t ;
3
4 p u b l i c AddNumbers ( i n t num1 , i n t num2) {
5 t h i s . num1 = num1 ;
CHAPTER 1. OBJECT ORIENTED PROGRAMMING (JAVA) 10

Table 1.2: Java Programming Language Keywords.


abstract assert boolean break byte case
catch char class const continue default
do double else enum extends final
finally float for goto if implements
import instanceof int interface long native
new package private protected public return
short static strictfp super switch synchronized
this throw throws transient try void
volatile while

6 t h i s . num2 = num2 ;
7 }
8
9 p u b l i c v o i d add ( ) {
10 r e s u l t = num1 + num2 ;
11 System . out . p r i n t l n ( ” R e s u l t i s : ” + r e s u l t ) ;
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 AddNumbers addnum = new AddNumbers ( 1 0 , 2 0 ) ;
16 addnum . add ( ) ;
17 }
18 }

1.13 Java Programming Language Keywords


Keywords have special meaning to the Java technology compiler. They
identify a data type name or program construct name. Lists of keywords
that are used in Java programming language shown in tabel 1.2.

1.14 Data Types in Java


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)
CHAPTER 1. OBJECT ORIENTED PROGRAMMING (JAVA) 11

Table 1.3: Default value of class variables.


Class Variable Types Value
boolean false
char ’0̆000’
byte 0
short 0
int 0
long 0L
float 0.0F
double 0.0D
all class types null

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.

1.15 Operators in Java Programming


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
CHAPTER 1. OBJECT ORIENTED PROGRAMMING (JAVA) 12

1.16 String Concatenation with +


The + operator performs a concatenation of String objects, producing a new
String.
1 p u b l i c c l a s s StringConTest {
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 S t r i n g s a l u t a t i o n = ”Mr . ” ;
4 S t r i n g name = ”Dewan ” + ” Md. ” + ” F a r i d ” ;
5 S t r i n g t i t l e = s a l u t a t i o n + name ;
6 System . out . p r i n t l n ( t i t l e ) ;
7 }
8 }

1.17 Casting
Casting means assigning a value of one type to a variable of another type.
1 p u b l i c c l a s s CastTest {
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 l o n g b i g V a l u e = 99L ;
4 i n t s m a l l V a l u e = ( i n t ) b i g V a l u e ; // C a s t i n g
5 System . out . p r i n t l n ( s m a l l V a l u e ) ;
6 smallValue = 50;
7 b i g V a l u e = s m a l l V a l u e ; // Auto C a s t i n g
8 System . out . p r i n t l n ( b i g V a l u e ) ;
9 }
10 }
Chapter 2

Flow Controls, and Arrays

2.1 Branching Statements


2.1.1 The if-else Statement
The general form of the if-else statement is:
i f (< b o o l e a n e x p r e s s i o n >)
<s t a t e m e n t o r b l o c k >
else
<s t a t e m e n t o r b l o c k >

1 public class IfTest {


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 = ( i n t ) ( Math . random ( ) ∗ 1 0 0 ) ;
4 System . out . p r i n t l n ( x ) ;
5 i f ( x >100){
6 System . out . p r i n t l n ( ”WHITE” ) ;
7 }
8 else {
9 System . out . p r i n t l n ( ”BLACK” ) ;
10 }
11 }
12 }

2.1.2 The switch Statement


The switch statement syntax is:
s w i t c h (< e x p r e s s i o n >){
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 ; ]
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 >∗

13
CHAPTER 2. FLOW CONTROLS, AND ARRAYS 14

[ 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 Loop Flow Control


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


Looping statements enable us to execute blocks of statements repeatedly.
Java supports three of loop constructs: for, while, and do-while loops. The
for and while loops test the loop condition before execution of loop body.
And do-while loops check the loop condition after executing the loop body.

2.2.1 The for Loop


The for loop syntax is:
f o r ( i n i t i a l i z a t i o n ; c o n d i t i o n ; i n c r e m e n t / decrement ) {
statements ;
CHAPTER 2. FLOW CONTROLS, AND ARRAYS 15

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 gener-
ated 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 }
CHAPTER 2. FLOW CONTROLS, AND ARRAYS 16

Write a Java program to show the following output:


1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 8 7 6 5 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=n−i ; 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 The while Loop


The while loop syntax is:
initialization ;
while ( c on di ti on ){
statements ;
i n c r e m e n t / decrement ;
}

1 public c l a s s Loop while {


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 i =1;
4 w h i l e ( i <=50){
5 System . out . p r i n t l n ( i ) ;
6 i ++;
7 }
8 }
9 }
CHAPTER 2. FLOW CONTROLS, AND ARRAYS 17

2.2.3 The do-while Loop


The do-while loop syntax is:
initialization ;
do{
statements ;
i n c r e m e n t / decrement ;
} while ( condition ) ;

1 p u b l i c c l a s s Loop do {
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 i =1;
4 do{
5 System . out . p r i n t l n ( i ) ;
6 i ++;
7 } w h i l e ( i <=50);
8 }
9 }

2.3 Array
An array is a group of variables of the same data type referable by a common
name. The data type can be either a primitive data type or an class or
reference type.
1 p u b l i c c l a s s ArrayTest {
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 ; // d e c l a r i n g an a r r a y
4 myArray = new i n t [ 5 ] ; // c r e a t i n g a r r a y
5 // i n t [ ] myArray = new i n t [ 5 ] ;
6 f o r ( i n t i =0; i <5; i ++)
7 myArray [ i ]= 100+ i ; // i n i t i a l i z i n g a r r a y
8
9 f o r ( i n t i =0; i <=4; i ++)
10 System . out . p r i n t l n ( myArray [ i ] ) ;
11 }
12 }

1 c l a s s Bird {
2 public void f l y (){
3 System . out . p r i n t l n ( ” Bird can f l y ” ) ;
4 }
5 }
6
CHAPTER 2. FLOW CONTROLS, AND ARRAYS 18

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, con-
structor (initialized the variables), and display method ( display the value
of carName and carModel).
1 c l a s s Car{
2 p u b l i c S t r i n g carName ;
3 p u b l i c S t r i n g carModel ;
4
5 p u b l i c Car ( S t r i n g carName , S t r i n g carModel ) {
6 t h i s . carName = carName ;
7 t h i s . carModel = carModel ;
8 }
9
10 public void display (){
11 System . out . p r i n t l n ( ”Name : ”+carName+”, and Model : ”+carModel ) ;
12 }
13 } // end o f Car c l a s s ;
14
15 p u b l i c c l a s s ArrayExample {
16 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 ) {
17 Car [ ] myArray = new Car [ 3 ] ;
18 myArray [ 0 ] = new Car ( ”BMW” , ”Road Track 5 0 9 ” ) ;
19 myArray [ 1 ] = new Car ( ” Toyota ” , ”X c o r o l a 2 0 1 2 ” ) ;
20 myArray [ 2 ] = new Car ( ” Honda ” , ”M 2 0 1 1 ” ) ;
21
22 f o r ( i n t i =0; i <3; i ++)
23 {
24 myArray [ i ] . d i s p l a y ( ) ;
25 } // end o f f o r l o o p ;
26 } // end o f t h e main ( ) ;
27 } // end o f t h e c l a s s ;
CHAPTER 2. FLOW CONTROLS, AND ARRAYS 19

2.4 Multidimensional Arrays in Java


The Java programming language provide multidimensional arrays, which is
arrays of arrays. Line 4 and line 16 of code 2-9 show the example of two-
dimensional or multidimensional array. Line 17 to 20 show the creation of
non-rectangular arrays of arrays.
1 c l a s s MultiDim {
2 p u b l i c v o i d matrix ( ) {
3 // d e c l a r a t i o n and c r e a t i o n o f Array
4 i n t [ ] [ ] twoDim = new i n t [ 3 ] [ 3 ] ;
5 // i n i t i a l i z i n g a r r a y u s i n g f o r l o o p
6 f o r ( i n t row =0; row <3; row++)
7 f o r ( i n t c o l =0; c o l <3; c o l ++)
8 twoDim [ row ] [ c o l ]= row+c o l +10;
9 // u s e o f a r r a y
10 f o r ( i n t row =0; row<=2; row++)
11 f o r ( i n t c o l =0; c o l <=2; c o l ++)
12 System . out . p r i n t l n ( twoDim [ row ] [ c o l ] ) ;
13 }
14
15 p u b l i c v o i d mulArray ( ) {
16 i n t [ ] [ ] myArray = new i n t [ 4 ] [ ] ;
17 myArray [ 0 ] = new i n t [ 2 ] ;
18 myArray [ 1 ] = new i n t [ 4 ] ;
19 myArray [ 2 ] = new i n t [ 6 ] ;
20 myArray [ 3 ] = new i n t [ 8 ] ;
21 }
22 }

1 p u b l i c c l a s s Magic {
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 [ ] [ ] r a t = new i n t [ 3 ] [ ] ;
4 r a t [ 0 ] = new i n t [ 2 ] ;
5 r a t [ 1 ] = new i n t [ 5 ] ;
6 r a t [ 2 ] = new i n t [ 3 ] ;
7
8 f o r ( i n t row =0; row<=2; row++){
9 s w i t c h ( row ) {
10 c a s e 0 : f o r ( i n t j =0; j <=1; j ++)
11 r a t [ row ] [ j ] = 5+ j ;
12 break ;
13 c a s e 1 : f o r ( i n t j =0; j <=4; j ++)
14 r a t [ row ] [ j ] = 50+ j ;
15 break ;
CHAPTER 2. FLOW CONTROLS, AND ARRAYS 20

16 c a s e 2 : f o r ( i n t j =0; j <=2; j ++)


17 r a t [ row ] [ j ] = 100+ j ;
18 }
19 }
20
21 f o r ( i n t row =0; row<=2; row++){
22 s w i t c h ( row ) {
23 c a s e 0 : f o r ( i n t j =0; j <=1; j ++)
24 System . out . p r i n t ( r a t [ row ] [ j ]+”\ t ” ) ;
25 System . out . p r i n t ( ” \ n ” ) ;
26 break ;
27 c a s e 1 : f o r ( i n t j =0; j <=4; j ++)
28 System . out . p r i n t ( r a t [ row ] [ j ]+”\ t ” ) ;
29 System . out . p r i n t ( ” \ n ” ) ;
30 break ;
31 c a s e 2 : f o r ( i n t j =0; j <=2; j ++)
32 System . out . p r i n t ( r a t [ row ] [ j ]+”\ t ” ) ;
33 System . out . p r i n t ( ” \ n ” ) ;
34 }
35 }
36 }
37 }

2.4.1 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 ] ) ;
CHAPTER 2. FLOW CONTROLS, AND ARRAYS 21

19 System . out . p r i n t ( ” \ n ” ) ;
20 }
21 System . out . p r i n t l n ( ” Matrix B : ” ) ;
22 f o r ( i n t i =0; i <=2; i ++)
23 {
24 f o r ( i n t j =0; j <=2; j ++)
25 System . out . p r i n t ( ” \ t”+b [ i ] [ j ] ) ;
26 System . out . p r i n t ( ” \ n ” ) ;
27 }
28
29 // Matrix M u l t i p l i c a t i o n
30 f o r ( i n t i =0; i <=2; i ++)
31 f o r ( i n t j =0; j <=2; j ++)
32 c [ i ] [ j ]=( a [ i ] [ 0 ] ∗ b [ 0 ] [ j ] )
+(a [ i ] [ 1 ] ∗ b [ 1 ] [ j ] ) + ( a [ i ] [ 2 ] ∗ b [ 2 ] [ j ] ) ;
33
34 System . out . p r i n t l n ( ” Matrix C : ” ) ;
35 f o r ( i n t i =0; i <=2; i ++)
36 {
37 f o r ( i n t j =0; j <=2; j ++)
38 System . out . p r i n t ( ” \ t”+c [ i ] [ j ] ) ;
39 System . out . p r i n t ( ” \ n ” ) ;
40 }
41 }
42 }

2.5 Array Bounds, Resizing, and Copy in Java


In Java technology, all array indexes begin at 0. The number of elements in
an array is stored as part of the array object in the length attribute. If an
out-of-bounds runtime access occurs, then a runtime exception is thrown.
After array id created, you cannot resize an array. However, you can use
the same reference variable to refer to an entirely new array. Java provides
a special method in the System class, arraycopy() to copy arrays.
1 p u b l i c c l a s s ArrayExample {
2 p u b l i c v o i d arrayElement ( i n t [ ] myArray ) {
3 f o r ( i n t i =0; i <myArray . l e n g t h ; i ++)
4 System . out . p r i n t l n ( myArray [ i ] ) ;
5 }
6
7 public void arrayResizing (){
8 i n t [ ] a r r = new i n t [ 1 0 ] ;
9 a r r = new i n t [ 5 ] ;
10 }
CHAPTER 2. FLOW CONTROLS, AND ARRAYS 22

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 Enhanced for loop


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


The Java programming language provides wrapper classes to manipulate
primitive data elements as object. Each Java primitive data type has a
corresponding wrapper class in the java.lang package. Each wrapper class
encapsulates a single primitive value. If we change the primitive data types
to their object equivalents, which is called boxing, then we need to use the
wrapper classes. From J2SE version 5.0 introduce the autoboxing concept.
1 p u b l i c c l a s s BoxingTest {
2
3 p u b l i c v o i d boxing ( ) {
4 i n t pInt = 420;
5 I n t e g e r wInt = new I n t e g e r ( p I n t ) ; // boxing
6 i n t p2 = wInt . i n t V a l u e ( ) ; // unboxing
7 }
8
9 p ubl ic void autoboxing (){

Table 3.1: Access Control.


Modifier Same Class Same Package Sub Class Universe
private Yes
default Yes Yes
protected Yes Yes Yes
public Yes Yes Yes Yes

23
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 24

Table 3.2: Wrapper Classes.


Primitive Data Type Wrapper Class
boolean Boolean
byte Byte
char Character
short Short
int Integer
long Long
float Float
double Double

10 i n t pInt = 420;
11 I n t e g e r wInt = p I n t ; // a u t o b o x i n g
12 i n t p2 = wInt ; // autounboxing
13 }
14 }

3.3 Key Features of Java


The Java technology programming language supports three key features of
Object Oriented Programming:

1. Encapsulation

2. Inheritance

3. Polymorphism

3.3.1 Encapsulation
Encapsulation is the technique of hiding some members of a class from other
classes but provides a public interface to access that members.
1 c l a s s MyNumber{
2 p r i v a t e i n t number ;
3
4 p u b l i c v o i d setNumber ( i n t number ) {
5 t h i s . number = number ;
6 }
7
8 p u b l i c i n t getNumber ( ) {
9 r e t u r n number ;
10 }
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 25

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
Inheritance is the process of sub-classing that we can create a child-class
from a parent-class. Java programming language permits single inheritance,
because in Java a class can extend one other class only. A child-class can
inherited all of the members from the parent-class, but it does not inherit
the constructor.
1 c l a s s Cat{
2 public int x = 10;
3 public int y = 20;
4
5 p u b l i c v o i d show ( ) {
6 System . out . p r i n t l n ( x+” ”+y ) ;
7 }
8 }
9
10 p u b l i c c l a s s Rat e x t e n d s Cat{
11 public int z = 30;
12
13 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 ) {
14 Rat r = new Rat ( ) ;
15 r . show ( ) ;
16 System . out . p r i n t l n ( r . x+” ”+r . y+” ”+r . z ) ;
17 }
18 }
In the above code, Rat class extends Cat class, so Rat class become child
class of Cat class.
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 26

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 c l a s s A{
2 p u b l i c v o i d show ( ) {
3 System . out . p r i n t l n ( ” Bird can f l y ” ) ;
4 }
5 }
6
7 p u b l i c c l a s s B e x t e n d s A{
8 p u b l i c v o i d show ( ) {
9 System . out . p r i n t l n ( ” Bird f l y i n t h e sky ” ) ;
10 }
11
12 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 ) {
13 B b = new B ( ) ;
14 b . show ( ) ;
15 }
16 }
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 key-
word. In the following code, line 14 invokes the parent class method showDe-
tails().
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 (){
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 27

14 super . showDetails ( ) ;
15 System . out . p r i n t l n ( ” ”+department ) ;
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 ) {
19 Manager m = new Manager ( ) ;
20 m. s h o w D e t a i l s ( ) ;
21 }
22 }

Invoking Parent Class Constructor


A sub-class constructor can invoke a super-class constructor using the super
keyword. In line 19, show the parent class constructor invoking.
1 c l a s s Employee1 {
2 p u b l i c S t r i n g name ;
3 public float salary ;
4
5 p u b l i c Employee1 ( S t r i n g name , f l o a t s a l a r y ) {
6 t h i s . name = name ;
7 this . salary = salary ;
8 }
9
10 public void showDetails (){
11 System . out . p r i n t l n ( ”Name : ”+name+” S a l a r y : ”+ s a l a r y ) ;
12 }
13 }
14
15 p u b l i c c l a s s Manager1 e x t e n d s Employee1 {
16 p u b l i c S t r i n g department ;
17
18 p u b l i c Manager1 ( S t r i n g department ) {
19 s u p e r ( ”Mahmud” , 50000F ) ;
20 t h i s . department = department ;
21 }
22
23 public void showDetails (){
24 super . showDetails ( ) ;
25 System . out . p r i n t l n ( ” Department : ”+department ) ;
26 }
27
28 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 ) {
29 Manager1 m = new Manager1 ( ” E n g i n e e r i n g ” ) ;
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 28

30 m. s h o w D e t a i l s ( ) ;
31 }
32 }

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 }
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 29

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 c l a s s Man{
2 p r i v a t e i n t weight ;
3
4 p u b l i c Man( i n t w e i g h t ) {
5 t h i s . w e i g h t=w e i g h t ;
6 }
7
8 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
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 30

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 }
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 31

3.4 Polymorphism
Polymorphism is the technique of creating object of parent-class through
the constructor of child-class. Using polymorphism we can call or execute
the child-class overriding method by the parent-class object.
1 c l a s s Man{
2 public void f l y (){
3 System . out . p r i n t l n ( ”Man can not f l y ” ) ;
4 }
5 }
6
7 c l a s s SuperMan e x t e n d s Man{
8 public void f l y (){
9 System . out . p r i n t l n ( ” Superman can f l y ” ) ;
10 }
11 }
12
13 p u b l i c c l a s s TestMan{
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 Man m = new SuperMan ( ) ; // polymorphism
16 m. f l y ( ) ;
17 }
18 }

3.5 Homogeneous Collection


Homogeneous collection is the collection of objects that have a common
class.
1 p u b l i c c l a s s TestHomogeneous {
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 TestHomogeneous [ ] a r r = new TestHomogeneous [ 3 ] ;
4 a r r [ 0 ] = new TestHomogeneous ( ) ;
5 a r r [ 1 ] = new TestHomogeneous ( ) ;
6 a r r [ 2 ] = new TestHomogeneous ( ) ;
7 }
8 }

3.6 Heterogeneous Collection


Heterogeneous collection is a collection of dissimilar objects or classes.
1 c l a s s Man{
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 32

2 public void f l y (){


3 System . out . p r i n t l n ( ”Man can not f l y ” ) ;
4 }
5 }
6
7 c l a s s SuperMan e x t e n d s Man{
8 public void f l y (){
9 System . out . p r i n t l n ( ” Superman can f l y ” ) ;
10 }
11 }
12
13 c l a s s SpiderMan e x t e n d s Man{
14 public void f l y (){
15 System . out . p r i n t l n ( ” Spiderman can ’ t f l y , but can jump ” ) ;
16 }
17 }
18
19 public c l a s s TestHeterogeneous {
20 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 ) {
21 Man [ ] a r r = new Man [ 3 ] ;
22 a r r [ 0 ] = new Man ( ) ;
23 a r r [ 1 ] = new SuperMan ( ) ;
24 a r r [ 2 ] = new SpiderMan ( ) ;
25 }
26 }

3.7 The Object Class


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 p u b l i c c l a s s Car{
2 }
3 // o r we can d e c l a r e t h e Car c l a s s by
5 // e x t e n d i n g Object c l a s s . Both have same mining .
6 p u b l i c c l a s s Car e x t e n d s Object {
7 }

3.8 The instanceof Operator


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)
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 33

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 c l a s s Car{
2 p u b l i c v o i d abc ( ) {
3 System . out . p r i n t l n ( ” Car ” ) ;
4 }
5 }
6
7 c l a s s Bus{
8 p u b l i c v o i d xyz ( ) {
9 System . out . p r i n t l n ( ” Bus ” ) ;
10 }
11 }
12
13 public class Testinstanceof {
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 Car c = new Car ( ) ;
16 Bus b = new Bus ( ) ;
17 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 ( ) ;
18 t . test (c );
19 t . test (b ) ;
20 }
21
22 p u b l i c v o i d t e s t ( Object o b j ) {
23 i f ( o b j i n s t a n c e o f Car ) {
24 System . out . p r i n t l n ( ” Object i s o f Car c l a s s ” ) ;
25 } e l s e i f ( o b j i n s t a n c e o f Bus ) {
26 System . out . p r i n t l n ( ” Object i s o f Bus c l a s s ” ) ;
27 } else {
28 System . out . p r i n t l n ( ” Object i s not o f Car/Bus c l a s s ” ) ;
29 }
30 }
31 }

3.9 The equals Method


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
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 34

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 ( xˆy ) ;
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 ” ) ;
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 35

42 } else {
43 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 ” ) ;
44 }
45 }
46 }

3.10 The toString Method


The toString() method of Object class convert an object to a String rep-
resentation, 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 The Static keyword


In Java technology, members (attributes, methods, and nested classes) of a
class can be declare with static keyword that are associated with the class
rather than the instances of the class. The static variable sometime called
class variable and static method sometime called class method. A static
variable is similar to global variable in other programming languages. We
can use the static members of a class without creating the object or instance
of that class. The static methods can only access the local attributes, static
class attributes, and it’s parameters. Attempting to access non-static class
attributes in a static methods will cause a compiler error. We can not
override the static method. The main() method is a static method because
the JVM does not create an instance of the class when executing the main
method. The static block code executed once when the class is loaded.
1 public class TestStatic {
2 p u b l i c s t a t i c i n t count = 1 0 ;
3
4 p u b l i c s t a t i c v o i d incrementCount ( ) {
5 count++;
6 }
7
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 36

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 The final Keyword


In the Java technology, the final keyword can be apply to the classes, meth-
ods, 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 Declaring Abstract class


In Java technology, we can declare a method in a class which have no body,
this method is called abstract method, if a class contain an abstract method
then the class will be abstract class. An abstract class must have at least
one abstract method and can never be instantiated. In code 3-18, Vehicle
class is an abstract class because it contain an abstract method goFast() in
line 5. This goFast() method is implemented in the sub-class Car at line 13.
1 abstract c l a s s Vehicle {
2 p u b l i c S t r i n g model = ”E c l a s s ” ;
3 public String year = ”2008”;
4
5 p u b l i c a b s t r a c t v o i d goFast ( ) ;
6
7 p u b l i c v o i d show ( ) {
8 System . out . p r i n t l n ( ” Model : ”+model+” Year : ”+y e a r ) ;
9 }
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 37

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


In Java interfaces are declaring only the contract and no implementation,
like a 100% abstract superclass. All methods declared in an interface are
public and abstract (do not need to actually type the public and abstract
modifiers in the method declaration, but the method is still always pub-
lic and abstract). Interface methods must not be static. Because interface
methods are abstract, they cannot be marked final, strictfp, or native. All
variables in an interface are public, static, and final in interfaces. An inter-
face can extend one or more other interfaces. An interface cannot implement
another interface or class.
1 i n t e r f a c e Bounceable {
2 p u b l i c a b s t r a c t v o i d bounce ( ) ;
3 v o i d setBounce ( i n t b ) ;
4 }
5
6 p u b l i c c l a s s T i r e implements Bounceable {
7 p u b l i c v o i d bounce ( ) {
8 System . out . p r i n t l n ( ” Love ” ) ;
9 }
10
11 p u b l i c v o i d setBounce ( i n t b ) {
12 int a = b;
13 System . out . p r i n t l n ( a ) ;
14 }
15
16 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 ) {
17 T i r e t = new T i r e ( ) ;
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 38

18 t . bounce ( ) ;
19 t . setBounce ( 1 5 ) ;
20 }
21 }

3.14.1 Example of abstract and interface


In Java technology, a java class can only extend another one class, but can
implements one or more interfaces.
1 a b s t r a c t c l a s s Animal {
2
3 p u b l i c v o i d type ( ) {
4 System . out . p r i n t l n ( ” Animal ” ) ;
5 }
6
7 p u b l i c a b s t r a c t v o i d name ( ) ;
8
9 }
10
11 i n t e r f a c e Cat{
12 p u b l i c a b s t r a c t v o i d jump ( ) ;
13 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
14 }
15
16 i n t e r f a c e Bird {
17 void f l y ( ) ;
18 }
19
20 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 {
21
22 public void f l y (){
23 System . out . p r i n t l n ( ” T i g e r can ’ t f l y ” ) ;
24 }
25
26 p u b l i c v o i d jump ( ) {
27 System . out . p r i n t l n ( ” T i g e r can jump ” ) ;
28 }
29
30 p u b l i c v o i d run ( ) {
31 System . out . p r i n t l n ( ” T i g e r can run ” ) ;
32 }
33
34 p u b l i c v o i d name ( ) {
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 39

35 System . out . p r i n t l n ( ” T i g e r ” ) ;
36 }
37
38 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 ) {
39 T i g e r t = new T i g e r ( ) ;
40 t . name ( ) ;
41 t . jump ( ) ;
42 t . run ( ) ;
43 t . fly ();
44 }
45 }

3.15 Exceptions
Exceptions are a mechanism used by many programming languages to de-
scribe 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 ex-
ceptions 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
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 40

3.15.1 The try-catch Statement


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 Using Multiple catch Clauses


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 }
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 41

3.15.3 Call Stack Mechanism


If a statement throws an exception, and that exception is not handled in the
immediately enclosing method, then that exception is throws to the calling
method. If the exception is not handled in the calling method, it is thrown
to the caller of that method. This process continues. If the exception is still
not handled by the time it gets back to the main() method and main() does
not handle it, the exception terminates the program abnormally.

3.15.4 The try-catch-finally statement


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 {
}
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 42

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 Method Overriding and Exception


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 p u b l i c c l a s s A{
2 p u b l i c v o i d methodA ( ) throws IOException { }
3 }
4
5 c l a s s B e x t e n d s A{
6 p u b l i c v o i d methodA ( ) throws EOFException {
7 // 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 ;
8 }
9 }
10
11 c l a s s C e x t e n d s A{
12 p u b l i c v o i d methodA ( ) throws E x c e p t i o n {
13 // 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 ;
14 }
15 }

3.15.6 Creating and Throwing User Defined Exception


By extending Exception class we can cerate our own Exception class.
1 p u b l i c c l a s s MyException e x t e n d s E x c e p t i o n {
2 p u b l i c MyException ( S t r i n g massage ) {
3 s u p e r ( massage ) ;
4 }
5
6 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 ) {
7 try {
8 throw new MyException ( ” User d e f i n e d e x c e p t i o n ” ) ;
9 } c a t c h ( MyException e ) {
10 System . out . p r i n t l n ( e ) ;
11 }
12 }
13 }
Chapter 4

Text-Based and GUI-Based


Applications

4.1 Command-Line Arguments


In Java programming, we can provide zero or more command line arguments
of String type from a terminal window. The sequence of arguments follows
the name of the program class and is stored in an array of String objects
passed to the public static void main(String[] args) method.
1 p u b l i c c l a s s CommandLine{
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 =0; i <a r g s . l e n g t h ; i ++)
4 System . out . p r i n t l n ( ” Value o f a r g s i n ”+ i +” i n d e x i s : ”+a r g s [ i ] ) ;
5 }
6 }

[ farid@localhost MyJavaBook ] \ $ j a v a c CommandLine . j a v a


[ farid@localhost MyJavaBook ] \ $ j a v a CommandLine 13 15 17
Value o f a r g s i n 0 i n d e x i s : 13
Value o f a r g s i n 1 i n d e x i s : 15
Value o f a r g s i n 2 i n d e x i s : 17

4.2 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)

43
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 44

3. System.err (System.err is a PrintStream onject)

Following code provides an example of keybord input, which import


the java.io.*; package. In line 6, InputStreamReader reads characters and
converts the row bytes into Unicode characters. In line 7, BufferedReader
provides the readLine() method (in line 10), which enables the program to
read from standard input (keyboard) one line at a time. Line 12, close the
buffered reader. The readLine() method can throw an I/O exception, so this
code is in a try-catch block.
1 import j a v a . i o . ∗ ;
2
3 public c l a s s ConsoleInput {
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 String s ;
6 InputStreamReader i s r = new InputStreamReader ( System . i n ) ;
7 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 ) ;
8 try {
9 System . out . p r i n t l n ( ” Write something : ” ) ;
10 s = in . readLine ( ) ;
11 System . out . p r i n t l n ( ” Read : ” + s ) ;
12 in . close ( ) ;
13 } c a t c h ( IOException e ) {
14 e . printStackTrace ( ) ;
15 }
16 }
17 }

4.3 Scanner
The scanner class provides formated input functionality. It is a part of the
java.util package.
1 import j a v a . i o . ∗ ;
2 import j a v a . u t i l . Scanner ;
3
4 p u b l i c c l a s s ScannerTest {
5 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 ) {
6 Scanner s = new Scanner ( System . i n ) ;
7 S t r i n g s t r = s . next ( ) ;
8 System . out . p r i n t l n ( s t r ) ;
9 i n t num = s . n e x t I n t ( ) ;
10 System . out . p r i n t l n (num ) ;
11 s . close ();
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 45

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 Write String to a File

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 Read String from a File

1 import j a v a . i o . ∗ ;
2
3 p u b l i c c l a s s ReadFile {
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 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 ) ) ;
8 String s t r = in . readLine ( ) ;
9 w h i l e ( s t r != n u l l ) {
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 46

10 System . out . p r i n t l n ( ” Read : ” + s t r ) ;


11 s t r = in . readLine ( ) ;
12 }
13 in . close ( ) ;
14 } c a t c h ( FileNotFoundException e1 ) {
15 System . out . p r i n t l n ( ” F i l e not found ” ) ;
16 } c a t c h ( IOException e2 ) {
17 System . out . p r i n t l n ( ” Input / output problem ” ) ;
18 }
19 }
20 }

4.5 Abstract Window Toolkit (AWT)


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 browser’s 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);
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 47

20 p . setBackground ( C o l o r . g r e e n ) ;
21 f . add ( p ) ;
22 f . s e t V i s i b l e ( true ) ;
23 }
24
25 p u b l i c v o i d windowClosing ( WindowEvent e ) {
26 System . e x i t ( 0 ) ;
27 }
28
29 public void windowOpened ( WindowEvent e ) { }
30 public void w i n d o w I c o n i f i e d ( WindowEvent e ) { }
31 public void w i n d o w D e i c o n i f i e d ( WindowEvent e ) { }
32 public void windowClosed ( WindowEvent e ) { }
33 public void windowActivated ( WindowEvent e ) { }
34 public void windowDeactivated ( WindowEvent e ) { }
35
36 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 ) {
37 FrameWithPanel f p = new FrameWithPanel ( ) ;
38 f p . launchFrame ( ) ;
39 }
40 }

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 ( ) {
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 48

21 mi4 . a d d A c t i o n L i s t e n e r ( t h i s ) ;
22 m1 . add ( mi1 ) ;
23 m1 . add ( mi2 ) ;
24 m1 . add ( mi3 ) ;
25 m1 . a d d S e p a r a t o r ( ) ;
26 m1 . add ( mi4 ) ;
27
28 mb. add (m1 ) ;
29 mb. add (m2 ) ;
30 mb. setHelpMenu (m3 ) ;
31 f . setMenuBar (mb ) ;
32
33 f . addWindowListener ( t h i s ) ;
34 f . setSize (400 ,400);
35 f . setBackground ( C o l o r . r e d ) ;
36 f . setLayout ( n u l l ) ;
37 f . s e t V i s i b l e ( true ) ;
38 }
39
40 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 ) {
41 System . e x i t ( 0 ) ;
42 }
43
44 p u b l i c v o i d windowClosing ( WindowEvent e ) {
45 System . e x i t ( 0 ) ;
46 }
47
48 public void windowOpened ( WindowEvent e ) { }
49 public void w i n d o w I c o n i f i e d ( WindowEvent e ) { }
50 public void w i n d o w D e i c o n i f i e d ( WindowEvent e ) { }
51 public void windowClosed ( WindowEvent e ) { }
52 public void windowActivated ( WindowEvent e ) { }
53 public void windowDeactivated ( WindowEvent e ) { }
54
55 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 ) {
56 TestMenuBar tmb = new TestMenuBar ( ) ;
57 tmb . launchFrame ( ) ;
58 }
59 }
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 49

4.6 J2SE Event Model


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 ) ;
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 50

40 f . add ( t f ) ;
41 f . addWindowListener ( t h i s ) ;
42 f . setSize (250 ,150);
43 f . setBackground ( C o l o r . r e d ) ;
44 f . s e t V i s i b l e ( true ) ;
45 }
46
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 str ;
49 i f ( e . getActionCommand()==” y e s button ” ) {
50 s t r = ”You p r e s s YES button ” ;
51 t f . setText ( s t r ) ;
52 }
53 i f ( e . getActionCommand()==”no button ” ) {
54 s t r = ”You p r e s s NO button ” ;
55 t f . setText ( s t r ) ;
56 }
57 i f ( e . getActionCommand()==” c l e a r button ” ) {
58 str = ” ”;
59 t f . setText ( s t r ) ;
60 }
61 }
62
63 p u b l i c v o i d windowClosing ( WindowEvent e ) {
64 System . e x i t ( 0 ) ;
65 }
66
67 public void windowOpened ( WindowEvent e ) { }
68 public void w i n d o w I c o n i f i e d ( WindowEvent e ) { }
69 public void w i n d o w D e i c o n i f i e d ( WindowEvent e ) { }
70 public void windowClosed ( WindowEvent e ) { }
71 public void windowActivated ( WindowEvent e ) { }
72 public void windowDeactivated ( WindowEvent e ) { }
73
74 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 ) {
75 EventHandle eh = new EventHandle ( ) ;
76 eh . launchFrame ( ) ;
77 }
78 }

4.6.1 Mouse Example

1 import j a v a . awt . ∗ ;
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 51

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 ) ;
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 52

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 public void windowOpened ( WindowEvent e ) { }
49 public void w i n d o w I c o n i f i e d ( WindowEvent e ) { }
50 public void w i n d o w D e i c o n i f i e d ( WindowEvent e ) { }
51 public void windowClosed ( WindowEvent e ) { }
52 public void windowActivated ( WindowEvent e ) { }
53 public void windowDeactivated ( WindowEvent e ) { }
54
55 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 ) {
56 MouseExample me = new MouseExample ( ) ;
57 me . launchFrame ( ) ;
58 }
59 }

4.7 Colors in Java


In Java, we can control the colors used for the foreground using setFore-
ground() 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 import j a v a . awt . ∗ ;
2 import j a v a . awt . e v e n t . ∗ ;
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 53

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 ) { }
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 54

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 compo-
nents 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 container’s 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 }
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 55

14
15 p u b l i c v o i d launchFrame ( ) {
16 f . s e t L a y o u t ( new FlowLayout ( ) ) ;
17 // f . s e t L a y o u t ( new FlowLayout ( FlowLayout . LEFT ) ) ;
18 // f . s e t L a y o u t ( new FlowLayout ( FlowLayout . RIGHT ) ) ;
19 // f . s e t L a y o u t ( new FlowLayout ( FlowLayout .CENTER) ) ;
20 // f . s e t L a y o u t ( new FlowLayout ( FlowLayout . RIGHT, 2 0 , 3 0 ) ) ;
21 f . add ( b1 ) ;
22 f . add ( b2 ) ;
23 f . add ( b3 ) ;
24 f . addWindowListener ( t h i s ) ;
25 f . setSize (250 ,150);
26 f . setBackground ( C o l o r . r e d ) ;
27 f . s e t V i s i b l e ( true ) ;
28 }
29
30 p u b l i c v o i d windowClosing ( WindowEvent e ) {
31 System . e x i t ( 0 ) ;
32 }
33
34 public void windowOpened ( WindowEvent e ) { }
35 public void w i n d o w I c o n i f i e d ( WindowEvent e ) { }
36 public void w i n d o w D e i c o n i f i e d ( WindowEvent e ) { }
37 public void windowClosed ( WindowEvent e ) { }
38 public void windowActivated ( WindowEvent e ) { }
39 public void windowDeactivated ( WindowEvent e ) { }
40
41 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 ) {
42 FlowExample f e = new FlowExample ( ) ;
43 f e . launchFrame ( ) ;
44 }
45 }
The BorderLayout manager contains five distinct areas: NORTH, SOUTH,
EAST, WEST, and CENTER, indicated by BorderLayout.NORTH, and so
on.
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 BorderExample implements WindowListener {
5 p r i v a t e Frame f ;
6 p r i v a t e Button b1 , b2 , b3 , b4 , b5 ;
7
8 p u b l i c BorderExample ( ) {
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 56

9 f = new Frame ( ” FlowLayout ” ) ;


10 b1 = new Button ( ” Button 1 ” ) ;
12 b2 = new Button ( ” Button 2 ” ) ;
13 b3 = new Button ( ” Button 3 ” ) ;
14 b4 = new Button ( ” Button 4 ” ) ;
15 b5 = new Button ( ” Button 5 ” ) ;
16 }
17
18 p u b l i c v o i d launchFrame ( ) {
19 f . add ( b1 , BorderLayout .NORTH) ;
20 f . add ( b2 , BorderLayout .SOUTH) ;
21 f . add ( b3 , BorderLayout .WEST) ;
22 f . add ( b4 , BorderLayout .EAST ) ;
23 f . add ( b5 , BorderLayout .CENTER) ;
24 f . addWindowListener ( t h i s ) ;
25 f . setSize (250 ,250);
26 f . setBackground ( C o l o r . r e d ) ;
27 f . s e t V i s i b l e ( true ) ;
28 }
29
30 p u b l i c v o i d windowClosing ( WindowEvent e ) {
31 System . e x i t ( 0 ) ;
32 }
33
34 public void windowOpened ( WindowEvent e ) { }
35 public void w i n d o w I c o n i f i e d ( WindowEvent e ) { }
36 public void w i n d o w D e i c o n i f i e d ( WindowEvent e ) { }
37 public void windowClosed ( WindowEvent e ) { }
38 public void windowActivated ( WindowEvent e ) { }
39 public void windowDeactivated ( WindowEvent e ) { }
40
41 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 ) {
42 BorderExample be = new BorderExample ( ) ;
43 be . launchFrame ( ) ;
44 }
45 }
The GridLayout manager placing components with a number of rows and
columns. The following constructor creates a GridLayout with the specified
equal size. new GridLayout(int rows, int cols);
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 GridExample implements WindowListener {
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 57

5 p r i v a t e Frame f ;
6 p r i v a t e Button b1 , b2 , b3 , b4 , b5 , b6 ;
7
8 p u b l i c GridExample ( ) {
9 f = new Frame ( ” FlowLayout ” ) ;
10 b1 = new Button ( ” Button 1 ” ) ;
11 b2 = new Button ( ” Button 2 ” ) ;
12 b3 = new Button ( ” Button 3 ” ) ;
13 b4 = new Button ( ” Button 4 ” ) ;
14 b5 = new Button ( ” Button 5 ” ) ;
15 b6 = new Button ( ” Button 6 ” ) ;
16 }
17
18 p u b l i c v o i d launchFrame ( ) {
19 f . s e t L a y o u t ( new GridLayout ( 3 , 2 ) ) ;
20 f . add ( b1 ) ;
21 f . add ( b2 ) ;
22 f . add ( b3 ) ;
23 f . add ( b4 ) ;
24 f . add ( b5 ) ;
25 f . add ( b6 ) ;
26 f . addWindowListener ( t h i s ) ;
27 f . setSize (300 ,300);
28 f . setBackground ( C o l o r . r e d ) ;
29 f . s e t V i s i b l e ( true ) ;
30 }
31
32 p u b l i c v o i d windowClosing ( WindowEvent e ) {
33 System . e x i t ( 0 ) ;
34 }
35
36 public void windowOpened ( WindowEvent e ) { }
37 public void w i n d o w I c o n i f i e d ( WindowEvent e ) { }
38 public void w i n d o w D e i c o n i f i e d ( WindowEvent e ) { }
39 public void windowClosed ( WindowEvent e ) { }
40 public void windowActivated ( WindowEvent e ) { }
41 public void windowDeactivated ( WindowEvent e ) { }
42
43 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 ) {
44 GridExample ge = new GridExample ( ) ;
45 ge . launchFrame ( ) ;
46 }
47 }
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 58

4.9 Java Foundation Classes/ Swing Technology


The Java Foundation Classes (J.F.C.)/ Swing technology is a second-generation
GUI toolkit that is included in the Java 2 SDK as a standard extension.
Swing technology has many improvement over AWT and adds many new
and more-complex components including a table and tree component.

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 import j a v a . awt . ∗ ;
2 import j a v a . awt . e v e n t . ∗ ;
3 import j a v a x . swing . ∗ ;
4
5 p u b l i c c l a s s TestFonts e x t e n d s JFrame{
6 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;
7
8 p u b l i c TestFonts ( ) {
9 s u p e r ( ” Font Examples ” ) ;
10 s e t S i z e (300 , 150);
11 show ( ) ;
12 }
13
14 p u b l i c v o i d p a i n t ( G ra ph ic s g ) {
15 g . d r a w S t r i n g ( ” Welcome t o Java . ” , 2 0 , 5 0 ) ;
16 g . setC olor ( Color . red ) ;
17 g . s e t F o n t ( new Font ( ” Monospaced ” , Font .BOLD, 1 4 ) ) ;
18 g . d r a w S t r i n g ( ” Welcome t o Java . ” , 2 0 , 7 0 ) ;
19 g . setC olor ( Color . blue ) ;
20 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 ) ) ;
21 g . d r a w S t r i n g ( ” Welcome t o Java . ” , 2 0 , 9 0 ) ;
22 }
23
24 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 ) {
25 TestFonts t f = new TestFonts ( ) ;
26 t f . addWindowListener (
27 new WindowAdapter ( ) {
28 p u b l i c v o i d windowClosing ( WindowEvent e ) {
29 System . e x i t ( 0 ) ;
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 59

30 }
31 }
32 );
33 }
34 }

4.9.2 Drawing Lines, Rectangles, and Ovals


Code 4-15 presents a variety if Graphics methods for drawing lines, rectan-
gles, and ovals.
1 import j a v a . awt . ∗ ;
2 import j a v a . awt . e v e n t . ∗ ;
3 import j a v a x . swing . ∗ ;
4
5 p u b l i c c l a s s TestLineRectOval e x t e n d s JFrame{
6 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;
7
8 p u b l i c TestLineRectOval ( ) {
9 s u p e r ( ” L i n e s R a c t a n g l e s Ovals ” ) ;
10 s e t S i z e (360 , 450);
11 show ( ) ;
12 }
13
14 p u b l i c v o i d p a i n t ( G ra ph ic s g ) {
15 g . setC olor ( Color . red ) ;
16 g . drawLine ( 5 0 , 4 0 , 3 0 0 , 4 0 ) ;
17
18 g . setC olor ( Color . blue ) ;
19 g . drawRect ( 5 0 , 6 0 , 1 0 0 , 6 0 ) ;
20 g . f i l l R e c t (200 ,60 , 100 , 6 0 ) ;
21
22 g . s e t C o l o r ( C o l o r . cyan ) ;
23 g . drawRoundRect ( 5 0 , 1 5 0 , 1 0 0 , 6 0 , 5 0 , 5 0 ) ;
24 g . fillRoundRect (200 ,150 , 100 , 60 , 50 , 5 0 ) ;
25
26 g . setC olor ( Color . yellow ) ;
27 g . draw3DRect ( 5 0 , 2 5 0 , 1 0 0 , 6 0 , t r u e ) ;
28 g . f i l l 3 D R e c t (200 ,250 , 100 , 60 , true ) ;
29
30 g . s e t C o l o r ( C o l o r . magenta ) ;
31 g . drawOval ( 5 0 , 3 5 0 , 1 0 0 , 6 0 ) ;
32 g . f i l l O v a l (200 ,350 , 100 , 6 0 ) ;
33 }
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 60

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, Jpass-
wordField, and Jbutton.
1 import j a v a . awt . ∗ ;
2 import j a v a . awt . e v e n t . ∗ ;
3 import j a v a x . swing . ∗ ;
4
5 p u b l i c c l a s s Password e x t e n d s JFrame{
6 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;
7
8 private JLabel l 1 , l 2 ;
9 private JTextField t1 ;
10 private J P a s s w o r d F i e l d pw ;
11 private JButton b1 , b2 ;
12
13 p u b l i c Password ( ) {
14 s u p e r ( ” Password Example ” ) ;
15 C o n t a i n e r c = getContentPane ( ) ;
16 c . s e t L a y o u t ( new FlowLayout ( ) ) ;
17
18 l 1 = new JLabel ( ” Enter User Name ”);
19 c . add ( l 1 ) ;
20
21 t 1 = new J T e x t F i e l d ( 1 5 ) ;
22 c . add ( t 1 ) ;
23
24 l 2 = new JLabel ( ” Enter Password ”);
25 c . add ( l 2 ) ;
26
27 pw = new J P a s s w o r d F i e l d ( 1 0 ) ;
28 c . add (pw ) ;
29
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 61

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.
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 62

1 import j a v a . awt . ∗ ;
2 import j a v a . awt . e v e n t . ∗ ;
3 import j a v a x . swing . ∗ ;
4
5 p u b l i c c l a s s TestJComt e x t e n d s JFrame{
6 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;
7
8 private JCheckBox bold , i t a l i c ;
9 private JRadioButton male , f e m a l e ;
10 private ButtonGroup radioGroup ;
11 private JComboBox cBox ;
12 private S t r i n g [ ] s t r 1 = {” s p r i n g ” , ”summer ” , ” f a l l ” } ;
13 private JList colorList ;
14 private S t r i n g [ ] s t r 2 = {”Red ” , ” Green ” , ” Blue ” , ” Black ” , ” White ” , ”
15 ” Orange ” , ” Pink ” , ”Magenta ” , ”Sky ” , ”Cya
16 p r i v a t e JTextArea t a 1 ;
17
18 p u b l i c TestJComt ( ) {
19 s u p e r ( ” Test JComponents ” ) ;
20 C o n t a i n e r c = getContentPane ( ) ;
21 c . s e t L a y o u t ( new FlowLayout ( ) ) ;
22
23 b o l d = new JCheckBox ( ” Bold ” ) ;
24 c . add ( b o l d ) ;
25 i t a l i c = new JCheckBox ( ” I t a l i c ” ) ;
26 c . add ( i t a l i c ) ;
27
28 male = new JRadioButton ( ” Male ” ) ;
29 c . add ( male ) ;
30 f e m a l e = new JRadioButton ( ” Female ” ) ;
31 c . add ( f e m a l e ) ;
32 radioGroup = new ButtonGroup ( ) ;
33 radioGroup . add ( male ) ;
34 radioGroup . add ( f e m a l e ) ;
35
36 cBox = new JComboBox ( s t r 1 ) ;
37 c . add ( cBox ) ;
38
39 c o l o r L i s t = new J L i s t ( s t r 2 ) ;
40 c o l o r L i s t . setVisibleRowCount ( 5 ) ;
41 c . add ( new J S c r o l l P a n e ( c o l o r L i s t ) ) ;
42
43 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 ” ;
44 t a 1 = new JTextArea ( s , 1 0 , 1 5 ) ;
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 63

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 import j a v a . awt . ∗ ;
2 import j a v a . awt . e v e n t . ∗ ;
3 import j a v a x . swing . ∗ ;
4
5 p u b l i c c l a s s OpenFile e x t e n d s JFrame{
6 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;
7 p r i v a t e JButton b1 ;
8 private JFileChooser j f c ;
9
10 p u b l i c OpenFile ( ) {
11 s u p e r ( ” F i l e Opener ” ) ;
12 b1 = new JButton ( ” Open F i l e Chooser ” ) ;
13 b1 . a d d A c t i o n L i s t e n e r (
14 new A c t i o n L i s t e n e r ( ) {
15 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 ) {
16 abc ( ) ;
17 }
18 }
19 );
20 getContentPane ( ) . add ( b1 , BorderLayout .NORTH) ;
21 s e t S i z e (300 , 200);
22 show ( ) ;
23 }
24
25 p r i v a t e v o i d abc ( ) {
26 j f c = new J F i l e C h o o s e r ( ) ;
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 64

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

Threads, Sockets, and


Collections API

5.1 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 inter-
face 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 p u b l i c c l a s s ThreadTest implements Runnable {
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 }

65
CHAPTER 5. THREADS, SOCKETS, AND COLLECTIONS API 66

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 p u b l i c c l a s s ThreadSleep implements Runnable {
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 <=10){
5 System . out . p r i n t l n ( ” i : ”+ i ) ;
6 i ++;
7 try {
8 Thread . s l e e p ( 3 0 0 ) ;
9 } catch ( InterruptedException e ){
CHAPTER 5. THREADS, SOCKETS, AND COLLECTIONS API 67

10 System . out . p r i n t l n ( e ) ;
11 }
12 }
13 }
14
15 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 ) {
16 ThreadSleep t s = new ThreadSleep ( ) ;
17 Thread t h r e a d 1 = new Thread ( t s ) ;
18 Thread t h r e a d 2 = new Thread ( t s ) ;
19 Thread t h r e a d 3 = new Thread ( t s ) ;
20 thread1 . s t a r t ( ) ;
21 thread2 . s t a r t ( ) ;
22 thread3 . s t a r t ( ) ;
23 }
24 }

Code : The S t a c k T e s t . j a v a a p p l i c a t i o n
1 c l a s s MyStack{
2 p r i v a t e i n t i d x =0;
3 p r i v a t e c h a r [ ] data = new c h a r [ 6 ] ;
4
5 p u b l i c s y n c h r o n i z e d v o i d push ( c h a r c ) {
6 this . notify ();
7 i f ( i d x !=5){
8 data [ i d x ]= c ;
9 i d x ++;
10 }
11 }
12
13 p u b l i c s y n c h r o n i z e d c h a r pop ( ) {
14 i f ( i d x ==0){
15 try {
16 t h i s . wait ( ) ;
17 } catch ( InterruptedException e ){
18 System . out . p r i n t l n ( e ) ;
19 }
20 }
21 idx −−;
22 r e t u r n data [ i d x ] ;
23 }
24 }
25
26 c l a s s Producer implements Runnable {
27 p r i v a t e MyStack s t a c k ;
CHAPTER 5. THREADS, SOCKETS, AND COLLECTIONS API 68

28
29 p u b l i c Producer ( MyStack s ) {
30 stack = s ;
31 }
32
33 p u b l i c v o i d run ( ) {
34 char c ;
35 f o r ( i n t i =0; i <50; i ++){
36 c = ( c h a r ) ( Math . random ()∗26+ ’A ’ ) ;
37 s t a c k . push ( c ) ;
38 System . out . p r i n t l n ( ” Producer : ”+c ) ;
39 try {
40 Thread . s l e e p ( ( i n t ) ( Math . random ( ) ∗ 3 0 0 ) ) ;
41 } catch ( InterruptedException e ){
42 System . out . p r i n t l n ( e ) ;
43 }
44 }
45 }
46 }
47
48 c l a s s Consumer implements Runnable {
49 p r i v a t e MyStack s t a c k ;
50
51 p u b l i c Consumer ( MyStack s ) {
52 stack = s ;
53 }
54
55 p u b l i c v o i d run ( ) {
56 char c ;
57 f o r ( i n t i =0; i <50; i ++){
58 c = s t a c k . pop ( ) ;
59 System . out . p r i n t l n ( ” Consumer : ”+c ) ;
60 try {
61 Thread . s l e e p ( ( i n t ) ( Math . random ( ) ∗ 3 0 0 ) ) ;
62 } catch ( InterruptedException e ){
63 System . out . p r i n t l n ( e ) ;
64 }
65 }
66 }
67 }
68
69 pub lic c l a s s StackTest {
70 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 ) {
71 MyStack s = new MyStack ( ) ;
CHAPTER 5. THREADS, SOCKETS, AND COLLECTIONS API 69

72 Producer p = new Producer ( s ) ;


73 Thread t 1 = new Thread ( p ) ;
74 t1 . s t a r t ( ) ;
75 Consumer c = new Consumer ( s ) ;
76 Thread t 2 = new Thread ( c ) ;
77 t2 . s t a r t ( ) ;
78 }
79 }

5.2 The Collection API


A collection is a single object representing a group of objects. The objects
in the collection are called elements. Implementation of collection determine
whether there is specific ordering and whether duplicates are permitted.

1. Set – An unordered collection, where no duplicates are permitted.

2. List – An ordered collection, where duplicates are permitted.

1 import j a v a . u t i l . ∗ ;
2
3 p u b l i c c l a s s SetExample {
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 g r s ) {
5 S e t s e t = new HashSet ( ) ;
6 s e t . add ( ” One ” ) ;
7 s e t . add ( ” 2 nd ” ) ;
8 s e t . add ( ” 3 rd ” ) ;
9 s e t . add ( new I n t e g e r ( 6 ) ) ;
10 s e t . add ( new F l o a t ( 7 . 7 F ) ) ;
11 s e t . add ( ” 2 nd ” ) ; // d u p l i c a t e a r e not added
12 System . out . p r i n t l n ( s e t ) ;
13 }
14 }

1 import j a v a . u t i l . ∗ ;
2
3 p u b l i c c l a s s ListExample {
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 g r s ) {
5 L i s t l i s t = new A r r a y L i s t ( ) ;
6 l i s t . add ( ” One ” ) ;
7 l i s t . add ( ” 2 nd ” ) ;
8 l i s t . add ( ” 3 rd ” ) ;
9 l i s t . add ( new I n t e g e r ( 6 ) ) ;
CHAPTER 5. THREADS, SOCKETS, AND COLLECTIONS API 70

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 Sockets or Networking in Java


Socket is the Java programming model to establish the communication link
between two processes. A socket can hold input and output stream. A
process sends data to another process through the network by writing to
the output stream associated with the socket. A process reads data written
the another process by reading from the input stream associated with the
socket.
Code 5 −7: The H o s t S e r v e r . j a v a a p p l i c a t i o n
1 import j a v a . n e t . ∗ ;
2 import j a v a . i o . ∗ ;
3
4 public c l a s s HostServer {
5 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 ) {
6 ServerSocket s = null ;
7 try {
8 s = new S e r v e r S o c k e t ( 5 4 3 2 ) ;
9 Socket s1 = s . accept ( ) ;
10 OutputStream s 1 o u t = s 1 . getOutputStream ( ) ;
11 B u f f e r e d W r i t e r bw = new B u f f e r e d W r i t e r ( new OutputStreamWriter ( s 1
12 bw . w r i t e ( ” Hellow Net World ” ) ;
13 bw . c l o s e ( ) ;
14 s1 . c l o s e ( ) ;
15 } c a t c h ( IOException e ) {
16 e . printStackTrace ( ) ;
17 }
18 }
19 }

1 import j a v a . n e t . ∗ ;
2 import j a v a . i o . ∗ ;
3
4 public class ClientServer {
5 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 ) {
6 try {
7 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 ) ;
8 InputStream i s = s 1 . g e t I n p u t S t r e a m ( ) ;
CHAPTER 5. THREADS, SOCKETS, AND COLLECTIONS API 71

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 }

You might also like