Upload
maddi
View
213
Download
0
Embed Size (px)
Citation preview
8/9/2019 handnote on java
1/72
Chapter 1
CSI 211, Object Oriented
Programming
1.1 Faculty Details
Dr. Dewan Md. FaridAssistant ProfessorDepartment of Computer Science and EngineeringUnited International UniversityRoom: 401 at UIU BhabanCell: 01715-833499 and Email: [email protected]
1.1.1 Short Biography of Dr. Farid
Dr. Dewan Md. Farid is an Assistant Professor in the Department of Computer Science and Engineering, United International University, Bangladesh.He was a Post Doctoral Fellow in the Computational Intelligence Group(CIG), Department of Computer Science and Digital Technology, Univer-sity of Northumbria at Newcastle, UK in 2013. He has received a Ph.D.degree in Computer Science and Engineering from Jahangirnagar Univer-sity, Bangladesh in 2012. Part of his Ph.D. research has been done at ERICLaboratory, University Lumire Lyon 2, France. He has received numerous
awards for his contribution on research into knowledge discovery and datamining, including Senior Fellowship I & II awarded by National Science & In-formation and Communication Technology (NSICT), Ministry of Science &Information and Communication Technology, Govt. of Bangladesh in 2008and 2011 respectively, and eLink (east west Link for Innovation, Networkingand Knowledge exchange) & cLink (Centre of excellence for Learning, Inno-vation, Networking and Knowledge) Erasmus Mundus scholarship awardedby European Union in 2009 and 2013 respectively. He has published a bookchapter, 13 international journals and 17 international conference papers in
1
8/9/2019 handnote on java
2/72
CHAPTER 1. CSI 211, OBJECT ORIENTED PROGRAMMING 2
the field of data mining and machine learning. He has participated and pre-
sented his papers in international conferences at Malaysia, Portugal, Italy,and France. He is a member of IEEE and IEEE Computer Society.
1.2 What is Java?
Java is a computer programming language that is used to build softwares.It is also an application, development, and deployment environment. Javais object oriented programming language to help us visualize the program inreal-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 runon 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 softwaredesigner 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 atSun. In May 1995, Sun Microsystems formally announced Java (Oak was re-named Java). Finally, in 1996, Java arrived in the market as a programminglanguage.
With the advent of Java 2 (released initially as J2SE 1.2 in December
1998), new versions had multiple configurations built for different typesof platforms. For example, J2EE targeted enterprise applications and thegreatly stripped-down version J2ME for mobile applications (Mobile Java).J2SE designated the Standard Edition. In 2006, for marketing purposes, Sunrenamed new J2 versions as Java EE, Java ME, and Java SE, respectively.
On November 13, 2006, Sun released much of Java as free and opensource 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 corecode 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 browserto a client’s computer and run by that browser. Applets are usually smallin size to minimize download time and are invoked by a Hypertext MarkupLanguage (HTML) web page.
8/9/2019 handnote on java
3/72
CHAPTER 1. CSI 211, OBJECT ORIENTED PROGRAMMING 3
Table 1.1: Major release versions of Java.
Version DateJDK 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
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 whichcontains 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 programminginterface (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 andchecks code fragments for illegal code, which is code that forges point-ers, violates access rights on objects, or attempts to change objecttype.
Execute Code Performed by the runtime interpreter.
The Java Runtime Environment(JRE) is an implementation of the JavaVirtual Machine (JVM), which actually executes Java programs. The JavaDevelopment Kit (JDK) is the original Java development environment forJava 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 beallocated dynamically at runtime. After the allocated memory is no longerrequired, 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
8/9/2019 handnote on java
4/72
CHAPTER 1. CSI 211, OBJECT ORIENTED PROGRAMMING 4
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 threadchecks 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 robustapplications.
1.6.1 Simple Java Program for beginners
This short example shows how to write first java application and compileand 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 bl i c s t a t i c v oi d main ( S t ri n g [ ] a r gs ) {3 Syste m . o ut . p r i n t l n ( ” Welcome i n Ja va World ” ) ;4 }5 }
Write this code in Notepad for Windows or Text Editor for Linux andsave the file as: Welcome.java (Source files must be named after the publicclass). Now you are ready to compile and run the program. To compile the
program, open a command window or terminal, and change to the directorywhere the program is stored and type javac Welcome.java
If the program contains no errors then a new file Welcome.class willbe 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 createsa 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 themain() method can be accessed by anything including the Javatechnology interpreter.
static The main() is static method because on instance of the classis needed to execute static methods and static method is a singlecopy.
void The return type of the main() method is void, because the main()method does not return any value.
8/9/2019 handnote on java
5/72
CHAPTER 1. CSI 211, OBJECT ORIENTED PROGRAMMING 5
String[] args The main() method declares the single parameter of
String array named args. If the program is given any argumentson its command line, these are passed into the main() methodthrough this args array of String type.
Line 3 displays or prints a line of text in the command window. System.outis 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 publicclass declaration in that file. A source file can include more then one classdeclaration, but only one class can be declared public.
1 p u b l i c c l a s s Welcome2{2 p ub li c s t a t i c v oi d main ( S tr i ng [ ] a rg s ){3 H e l l o he l l o = new H e l l o ( ) ;4 h e l l o . d i s p l a y ( ) ;5 }6 }7
8 c l a s s He l l o {9 p u b l i c v o i d d i sp l a y ( ) {1 0 S ystem . o ut . p r i n t l n ( ” Welcome t o J ava w or ld ” ) ;11 }12 }
Line 3 creates an object of Hello class named hello
Line 4 call the display() method of Hello class using the hello objectwith 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 (calledattributes), as well as the set of behaviors or functions (called methods).Together, attributes and methods are called members of a class. In Java
8/9/2019 handnote on java
6/72
CHAPTER 1. CSI 211, OBJECT ORIENTED PROGRAMMING 6
technology, class name usually starts with a capital letter, attribute and
method name usually starts with a small letter. The access modifier for theclasses in the Java technology can be public or default. The Java technologyclass, attribute, constructor, and method declaration takes the followingforms:
∗ c l a s s {∗ ∗ ;∗ ∗ [= ] ;
[ ] (∗){∗
}
∗ ∗ (∗){∗
}}
A constructor is a set of instructions designed to initialize an instance orobject. The name of the constructor must always be the same as the classname. Constructor do not return any value. Valid modifiers for constructorsare 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 technologyprovides a default constructor for you. This constructor takes no argumentsand has an empty body.
1 p u bl i c c l a s s MyDate{2 p r i v a t e i n t day ;3 p r iv at e i nt month ;4 p r i v a t e i n t yea r ;56 p ub li c MyDate ( ){7 day = 1 ;8 month = 6 ;
9 y e a r = 1 9 7 9 ;10 }1112 p u bl i c vo id showDate ( ) {13 System . o ut . p r i n t l n ( ”Day : ” + day ) ;1 4 S ystem . o ut . p r i n t l n ( ” Month : ” + month ) ;15 System . o ut . p r i n t l n ( ” Year : ” + y e ar ) ;16 }1718 p u bl i c s t a t i c v oi d main ( S t r in g [ ] a r gs ){
8/9/2019 handnote on java
7/72
8/9/2019 handnote on java
8/72
CHAPTER 1. CSI 211, OBJECT ORIENTED PROGRAMMING 8
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.javathen a package or folder will be create in the same directory named bank-ingPrj. Now you can run this Account.class file in bankingPrj packageby typing the command java bankingPrj.Account
1 p ac ka ge b a nk i ng P rj ;23 i m p o rt b a n k i n g P r j . A cc ou nt ;45 p u bl i c c l a s s Coustomer {6 p u bl i c S t ri n g name = ” James Bond ” ;7
8 p ub li c s t a t i c v o id main ( S tr in g [ ] a rg s ) {9 Account a cc = new Account ( ) ;10 a cc . showAccName ( ) ;11 Coustomer c ou s = new Coustomer ( ) ;12 System . o ut . p r i n t l n ( c o us . 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.
1.9 Comments and Semicolons
1.9.1 Java Comments
In Java Technology, we can add comments to Java source code in three wayswhich are given bellow:
1 p u b l i c c l a s s TestComment{2 // comment on one l i n e3 p ub li c s t a t i c v oi d main ( S tr i ng [ ] a rg s ){4 /∗ comment on one5 ∗ o r more l i n e s6 ∗/7 Syste m . o ut . p r i n t l n ( ” Comments i n J ava ” ) ;8 }9 /∗∗ d ocumentat ion comment10 ∗ can a l s o span one o r more l i n e s
8/9/2019 handnote on java
9/72
CHAPTER 1. CSI 211, OBJECT ORIENTED PROGRAMMING 9
11 ∗/
12 }
1.9.2 Semicolons
In the Java source code a statement is one or more lines of code terminatedwith a semicolons (;).
1 p u bl i c c l a s s T e st Se mi co lo n{2 p ub li c s t a t i c v oi d main ( S tr i ng [ ] a rg s ){3 i n t a =10 , b=20 , c ;4 c = a+b ;5 System . out . p r in t ln ( 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 classdefinition is contained in a block. A block statement can be nested withinganother block. In Java source code, block statements are executed first,then constructor statements are executed, and then method statements are
executed.
1 p ub li c c l a s s B lock Tes t {2 p u b l i c S t r i n g i n f o ;34 p ub li c B lo ck Tes t ( ){5 i n f o = ” Co n s t r u c t o r : Executed in 2nd s t ep ” ;6 System . out . p r in t ln ( i n fo ) ;7 }89 {
10 i n f o = ” Block : Executed in 1 st s te p ” ;11 System . out . p r i nt l n ( i n f o ) ;12 }1314 p ub li c v o id show ( ) {15 i n fo = ”Method : Executed i n 3 rd st ep ” ;16 System . out . p r i nt l n ( i n f o ) ;17 }1819 p ub li c s t a t i c v o id main ( S tr in g [ ] a rg s ) {
8/9/2019 handnote on java
10/72
CHAPTER 1. CSI 211, OBJECT ORIENTED PROGRAMMING 10
20 Bl ock Test bt = new B lock Tes 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 nomaximum 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 betweeninstance variables and parameters. It is also used to pass the current objectas a parameter to another method.
1 p u b l i c c l a s s AddNumbers{2 p r i va t e i n t num1 , num2 , r e s u l t ;34 p u b l i c AddNumbers ( i n t num1 , i n t num2 ){5 t hi s . num1 = num1 ;6 t hi s . num2 = num2 ;7 }89 p u b l i c v o id add () {10 r e s u l t = num1 + num2 ;11 System . out . p r i nt l n (” R es ul t i s : ” + r e s u l t ) ;12 }1314 p ub li c s t a t i c v o id main ( S tr in g [ ] a rg s ) {1 5 AddNumbers addnum = new AddNumbers ( 1 0 , 2 0 ) ;16 addnum . add ( ) ;17 }18 }
8/9/2019 handnote on java
11/72
CHAPTER 1. CSI 211, OBJECT ORIENTED PROGRAMMING 11
Table 1.2: Java Programming Language Keywords.
abstract assert boolean break byte casecatch 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
1.13 Java Programming Language Keywords
Keywords have special meaning to the Java technology compiler. Theyidentify a data type name or program construct name. Lists of keywordsthat 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: primitivetypes and class types.
Primitive data are eight types in four categories:
1. Logical: boolean (true or false)
2. Textual: char (16 bits)
3. Integral: byte (8 bits), short (16 bits), int (32 bits), and long (64 bits)
4. Floating point: float (32 bits) and double (64 bits)
Class or reference data used to create objects which are two types:
1. Textual: String
2. All classes that declare by ourself
1.14.1 Variable Initialization
In Java source code, the compiler will assign default value for the classvariables, if the programmer does not initialize the class variables. But localvariables must be initialized manually before use, because Java compiler willnot assign the local variables and local variable does not have any modifier.
8/9/2019 handnote on java
12/72
CHAPTER 1. CSI 211, OBJECT ORIENTED PROGRAMMING 12
Table 1.3: Default value of class variables.
Class Variable Types Valueboolean false
char ’0̆000’
byte 0
short 0
int 0
long 0L
float 0.0F
double 0.0D
all class types null
1.15 Operators in Java Programming
The Java programming language operators are similar in style and functionto those of C and C++.
1. Assignment operator (=)
2. Arithmetic operator (+, -, *, /, %, ++, -)
3. Relational operator
4. Logical operator
5. Bitwise operator
6. What operator ((boolean expression)? true exp: false exp;)
7. instanceof operator
1.16 String Concatenation with +
The + operator performs a concatenation of String objects, producing a newString.
1 p u b l i c c l a s s S tr in gC on Te st {2 p u bl i c s t a t i c v oi d main ( S t ri n g [ ] a r gs ) {3 S t r i n g s a l u t a t i o n = ”Mr . ” ;4 S t r in g name = ”Dewan ” + ” Md. ” + ” F ar id ” ;5 S t r i n g t i t l e = s a lu t at i on + name ;6 System . out . p r i nt l n ( t i t l e ) ;7 }8 }
8/9/2019 handnote on java
13/72
CHAPTER 1. CSI 211, OBJECT ORIENTED PROGRAMMING 13
1.17 Casting
Casting means assigning a value of one type to a variable of another type.
1 p ub li c c l a s s C astTest {2 p ub li c s t a t i c v oi d main ( S tr i ng [ ] a rg s ){3 l o n g bi g Va l ue = 99L ;4 i n t s m a l l V a l u e = ( i n t ) b ig V a lu e ; / / Ca s t i n g5 System . o ut . p r i n t l n ( s ma ll Va lu e ) ;6 s m a l l V a l u e = 5 0 ;7 bi g Va l ue = s m a l l V a l u e ; // Auto C a s t i n g8 System . o ut . p r i n t l n ( b ig Va lu e ) ;9 }
10 }
8/9/2019 handnote on java
14/72
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 ()
e l s e
1 p ub li c c l a s s I f Te st {2 p ub li c s t a t i c v oi d main ( S tr i ng [ ] a rg s ){3 i nt x = ( i nt ) (Math . random ( ) ∗ 1 0 0 ) ;4 System . out . p r in t ln ( x ) ;5 i f ( x>100){6 System . out . p r i nt l n ( ”WHITE” ) ;7 }8 e l s e {9 System . out . p r i nt l n ( ”BLACK” ) ;10 }11 }
12 }
2.1.2 The switch Statement
The switch statement syntax is:
s w i t c h (){c a s e : ∗
[ brea k ; ]c a s e : ∗
14
8/9/2019 handnote on java
15/72
CHAPTER 2. FLOW CONTROLS, AND ARRAYS 15
[ brea k ; ]
c a s e : ∗[ brea k ; ]
d e f a u l t : ∗}
1 p ub li c c l a s s Swit chTes t {2 p ub li c v oi d mySwitch ( i n t x) {3 s w i t c h ( x ) {4 c as e 1 : System . out . p r in t l n (”RED” ) ;5 br ea k ;6 c as e 2 : System . out . p r i nt l n (”GREEN” ) ;
7 br ea k ;8 c as e 3: System . out . p r in t l n (”BLUE” ) ;9 br ea k ;10 d e f a u l t : System . o ut . p r i n t l n ( ”WHITE” ) ;11 }12 }1314 p u bl i c s t a t i c v oi d main ( S t r in g [ ] a r gs ){15 Swi tchTes t s t = new Swi tchTes 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 thenreturn 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. Thefor 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 io n ; i nc re me nt / d ec re me nt ) {s t a t e m e n t s ;
8/9/2019 handnote on java
16/72
CHAPTER 2. FLOW CONTROLS, AND ARRAYS 16
}
1 p ub li c c l a s s L oo p f or {2 p u bl i c s t a t i c v oi d main ( S t ri n g [ ] a r gs ) {3 f o r ( i n t i =1; i
8/9/2019 handnote on java
17/72
CHAPTER 2. FLOW CONTROLS, AND ARRAYS 17
Write a Java program to show the following output:
11 2 1
1 2 3 2 11 2 3 4 3 2 1
1 2 3 4 5 4 3 2 11 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 11 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 bl i c c l a s s P yramid {
2 p ub li c s t a t i c v oi d main ( S tr i ng [ ] a rg s ){3 i n t n=9;4 f o r ( i n t i =1; i=1; j −−)6 System . out . p r i n t (” ” ) ;7 f o r ( i n t k =1; k=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:
i n i t i a l i z a t i o n ;w h i l e ( c o n d i t i o n ){
s t a t e m e n t s ;incremen t/ decrement ;
}
1 p u bl i c c l a s s L oo p w hi le {2 p u bl i c s t a t i c v oi d main ( S t ri n g [ ] a r gs ) {3 i n t i =1;4 w h i l e ( i
8/9/2019 handnote on java
18/72
CHAPTER 2. FLOW CONTROLS, AND ARRAYS 18
2.2.3 The do-while Loop
The do-while loop syntax is:
i n i t i a l i z a t i o n ;do {
s t a t e m e n t s ;incremen t/ decrement ;
} w h i l e ( c o n d i t i o n ) ;
1 p u bl i c c l a s s Loop do {2 p u bl i c s t a t i c v oi d main ( S t ri n g [ ] a r gs ) {3 i n t i =1;
4 do {5 System . out . p r in t ln ( i ) ;6 i ++;7 } wh il e ( i
8/9/2019 handnote on java
19/72
8/9/2019 handnote on java
20/72
CHAPTER 2. FLOW CONTROLS, AND ARRAYS 20
2.4 Multidimensional Arrays in Java
The Java programming language provide multidimensional arrays, which isarrays 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 M ultiDim{2 p u b l i c v o id matr ix ( ) {3 // d e c l a r a t i o n and c r e a t i o n o f Array4 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 p6 f o r ( i n t row =0; row
8/9/2019 handnote on java
21/72
CHAPTER 2. FLOW CONTROLS, AND ARRAYS 21
16 c a s e 2 : f o r ( i n t j =0; j
8/9/2019 handnote on java
22/72
CHAPTER 2. FLOW CONTROLS, AND ARRAYS 22
19 System . out . p ri nt ( ” \ n ” ) ;
20 }21 System . o ut . p r i n t l n ( ” M at ri x B : ” ) ;22 f o r ( i n t i =0; i
8/9/2019 handnote on java
23/72
CHAPTER 2. FLOW CONTROLS, AND ARRAYS 23
11
12 p u bl i c v oi d arrayCopy ( ) {13 i n t [ ] x = { 1 ,2 ,3 ,4 ,5 ,6 } ;14 i n t [ ] y = { 11 ,12 ,13 ,14 ,15 ,16 ,17 ,18 ,19 ,20 } ;15 System . a rr ay co py ( x , 0 , y , 0 , x . l en gt 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 bl i c c l a s s EnhanFor {2 p ub li c s t a t i c v o id main ( S tr in g [ ] a rg s ) {3 i nt [ ] myArray = new i n t [ 5 ] ;4 f o r ( i n t i =0; i
8/9/2019 handnote on java
24/72
Chapter 3
Object Oriented
Programming
3.1 Access Control
3.2 Wrapper Classes
The Java programming language provides wrapper classes to manipulateprimitive data elements as object. Each Java primitive data type has acorresponding wrapper class in the java.lang package. Each wrapper classencapsulates a single primitive value. If we change the primitive data typesto their object equivalents, which is called boxing, then we need to use thewrapper classes. From J2SE version 5.0 introduce the autoboxing concept.
1 p u bl i c c l a s s B oxing Test {23 p ub li c vo i d bo xing ( ) {4 i n t p I n t = 4 2 0 ;5 I nt eg er wInt = new I nt eg er ( p In t ) ; // b ox ing6 i n t p2 = wInt . i n tV a lu e ( ) ; // unboxing7 }8
9 p ub li c vo i d a ut o bo x i ng ( ){
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
24
8/9/2019 handnote on java
25/72
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 25
Table 3.2: Wrapper Classes.
Primitive Data Type Wrapper Classboolean Boolean
byte Byte
char Character
short Short
int Integer
long Long
float Float
double Double
10 i n t p I n t = 4 2 0 ;11 I nt eg er wInt = p In t ; // a ut o bo x i ng12 i n t p2 = wInt ; // autounboxing13 }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 otherclasses but provides a public interface to access that members.
1 c l a s s MyNumber{2 p ri va te i nt number ;34 p u b l i c v oi d setNumber ( i n t number ){5 t h i s . number = number ;6 }78 p ub li c i n t getNumber ( ){9 r e t u r n number ;10 }
8/9/2019 handnote on java
26/72
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 26
11 }
121 3 p u b l i c c l a s s E nca pT es t{14 p u bl i c s t a t i c v oi d main ( S t r in g [ ] a r gs ){15 MyNumber my = new MyNumber ( ) ;16 my . setNumber ( 4 5 ) ;1 7 S ys te m . o u t . p r i n t l n (my . ge tN umb er ( ) ) ;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 theEncapTest 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-classfrom a parent-class. Java programming language permits single inheritance,because in Java a class can extend one other class only. A child-class caninherited all of the members from the parent-class, but it does not inheritthe constructor.
1 c l a s s Cat{2 p u b l i c i n t x = 1 0 ;3 p u b l i c i n t y = 2 0 ;45 p u b l i c v o id show () {6 System . o ut . p r i n t l n ( x+” ”+y ) ;7 }8 }910 p u b l i c c l a s s Rat e xt en ds Cat {11 p u b l i c i n t z = 3 0 ;1213 p ub li c s t a t i c v o id main ( S tr in g [ ] a rg s ) {14 Rat r = new Rat ( ) ;15 r . show ( ) ;1 6 Syst em . o ut . 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 childclass of Cat class.
8/9/2019 handnote on java
27/72
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 27
Overriding Methods
If a method is defined in a sub-class so that the name, return type, andargument list must exactly those of a method in the parent class, then thenew method is said to override the old one. The overriding method can notbe 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 nt l n ( ” Bird can f l y ” ) ;4 }5 }6
7 p ub li c c l a s s B ex t e n d s A{8 p u b l i c v o i d show () {9 System . out . p r in t ln ( ” B ird f l y i n t he sky ” ) ;10 }1112 p u bl i c s t a t i c v oi d main ( S t r in g [ ] a r gs ){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 E mployee{2 p u b l i c S tr i n g name = ”Mahmud ” ;3 p u b l i c f l o a t sa l a r y = 5 0 0 0 0 ;45 p ub li c v o id s h o w D e t a i l s ( ){6 System . o ut . p r i n t l n ( name+” ”+ s a l a r y ) ;7 }8 }91 0 p u b l i c c l a s s Manag er e x t e n ds E mp lo yee {11 p u bl i c S t ri n g d epar tment = ” E n gi ne er in g ” ;1213 p ub li c vo id sh ow De ta il s ( ){
8/9/2019 handnote on java
28/72
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 28
14 s u p e r . s h o w D e t a i l s ( ) ;
15 System . o ut . p r i n t l n ( ” ”+d ep ar tm en t ) ;16 }1718 p ub li c s t a t i c v o id main ( S tr in g [ ] a rg 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 superkeyword. In line 19, show the parent class constructor invoking.
1 c l a s s Employee1 {2 p ub li c S tr in g name ;3 p u b l i c f l o a t s a l a r y ;45 p u bl i c Employee1 ( S t r in g name , f l o a t s a l a r y ){6 t h i s . name = name ;7 t h i s . s a l a r y = s a l a r y ;8 }910 p u bl i c v oi d s ho wD et ai ls ( ){1 1 S ys te m . o u t . p r i n t l n ( ” Name : ”+name+” S a l a r y : ”+ s a l a r y ) ;12 }13 }141 5 p u b l i c c l a s s Ma na ge r1 e x t e n ds E mp lo ye e1 {16 p u bl i c S t r in g d epa rtment ;171 8 p u b l i c M anager1 ( S t r i n g d ep ar tm en t ) {19 s up er ( ”Mahmud” , 50 00 0F ) ;20 t h i s . depar tment = depa rt ment ;21 }2223 p u bl i c v oi d s ho wD et ai ls ( ){24 s u p er . s h o w D e t a i l s ( ) ;2 5 S ys te m . o u t . p r i n t l n ( ” D ep ar tm en t : ”+ de pa r tm en t ) ;26 }2728 p u bl i c s t a t i c v oi d main ( S t r in g [ ] a r gs ){2 9 Manager1 m = new Manager1 ( ” E n g i ne e r i ng ” ) ;
8/9/2019 handnote on java
29/72
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 29
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 knownas methods overloading. For overloading methods argument lists must bedifferent and return type can be different. In the following code, there arefour methods of same name with different argument, which is an exampleof overloading methods.
1 p ub li c c l a s s ABC{2 i n t a , b , c ;34 p u b l i c v o id s e t V a l u e ( ) {5 a =2;6 b=4;7 c =6;8 }910 p ub li c v oid s et Va lu e ( i n t a ){11 t h i s . a=a ;12 b=4;13 c =6;14 }1516 p ub li c v o id s et Va lu e ( 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 }2122 p ub li c i nt s e t V a l u e ( i nt a , i nt b , i nt 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 r e t u r n z ;28 }29 }
8/9/2019 handnote on java
30/72
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 30
Overloading Constructors
We can declare several constructors with different arguments in a class,which is overloading constructors.
1 p ub li c c l a s s Li g ht {2 i n t a , b , c ;34 p u b l i c L i g h t ( ) {5 a =2;6 b=4;7 c =6;8 }
910 p ub li c L ig h t ( i nt a ) {11 t h i s . a=a ;12 b=4;13 c =6;14 }1516 p ub li c L ig h t ( i nt a , i nt b ) {17 t h i s . a=a ;18 t h i s . b=b ;19 c =6;
20 }2122 p ub li c L ig h t ( i nt a , i nt b , i nt 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 iv at e in t weig ht ;34 p ub li c Man( i n t weig ht ) {5 t h i s . wei g ht=w eig ht ;6 }78 p ub li c v o id setWeight ( i n t weig ht ) { / / s e t e r m et ho d
8/9/2019 handnote on java
31/72
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 31
9 i f ( weight>=50 && weight
8/9/2019 handnote on java
32/72
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 32
3.4 Polymorphism
Polymorphism is the technique of creating object of parent-class throughthe constructor of child-class. Using polymorphism we can call or executethe child-class overriding method by the parent-class object.
1 c l a s s Man{2 p u b l i c v o id f l y ( ) {3 System . o ut . p r i n t l n ( ”Man can no t f l y ” ) ;4 }5 }67 c l a s s SuperMan e x t e n d s Man{
8 p u b l i c v o id f l y ( ) {9 System . o ut . p r i n t l n ( ” Superman c an f l y ” ) ;10 }11 }121 3 p u b l i c c l a s s TestMan{14 p ub li c s t a t i c v o id main ( S tr in g [ ] a rg s ) {15 Man m = new SuperMan ( ) ; // p olymo rphism16 m. f l y ( ) ;17 }18 }
3.5 Homogeneous Collection
Homogeneous collection is the collection of objects that have a commonclass.
1 p u b l i c c l a s s T es tH om og en eo us {2 p u bl i c s t a t i c v oi d main ( S t ri n g [ ] a r gs ) {3 T es tH om og en eo us [ ] a r r = new T es tH om og en eo us [ 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{
8/9/2019 handnote on java
33/72
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 33
2 p u b l i c v o id f l y ( ) {
3 System . o ut . p r i n t l n ( ”Man can no t f l y ” ) ;4 }5 }67 c l a s s SuperMan e x t e n d s Man{8 p u b l i c v o id f l y ( ) {9 System . o ut . p r i n t l n ( ” Superman c an f l y ” ) ;10 }11 }121 3 c l a s s S pi de rM an e x t e n ds Man{
14 p u b l i c vo id f l y ( ) {1 5 S ystem . o ut . p r i n t l n ( ” S pi der ma n ca n ’ t f l y , b ut c an jump ” ) ;16 }17 }1819 p u b l i c c l a s s T es tH et er o ge ne ou s {20 p ub li c s t a t i c v o id main ( S tr in g [ ] a rg s ) {21 Man [ ] a rr = new Man [ 3 ] ;22 a r r [ 0 ] = new Man ( ) ;23 a rr [ 1 ] = new SuperMan ( ) ;24 a rr [ 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 classin Java programming does not extends any class then this class extends theObject class by default.
1 p ub li c c l a s s Car{2 }
3 // o r we c an d e cl a re t he Car c l a s s by5 / / e x t en d i ng O bj e ct c l a s s . Both h av e same m in in g .6 p u bl i c c l a s s Car e xt en ds O b jec t{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)
8/9/2019 handnote on java
34/72
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 34
method but we do not know this x object is from which class. Then we use
instanceof operator to know object x is from which class by the conditions.1 c l a s s Car{2 p u b l i c v o i d abc ( ) {3 System . out . p r i nt l n ( ”Car ” ) ;4 }5 }67 c l a s s Bus{8 p u b l i c v o i d xyz ( ) {9 System . out . p r i nt l n ( ”Bus ” ) ;10 }11 }1213 p u bl i c c l a s s T e s ti n s ta n c eo f {14 p u bl i c s t a t i c v oi d main ( S t r in g [ ] a r gs ){15 Car c = new Car ( ) ;16 Bus b = new Bus ( ) ;17 T es ti ns ta n c eo f t = new T e st in st a n ce of ( ) ;18 t . t es t ( c ) ;19 t . t e s t ( b ) ;20 }2122 p ub li c v oi d t e s t ( O bject o bj ){23 i f ( o b j i ns t a nc e o f Car ){24 System . out . p r in t ln ( ” O bj ect i s o f Car c l a s s ” ) ;25 } e l s e i f ( o bj i n s t a n ce o f Bus ){26 System . out . p r in t ln ( ” O bj ect i s o f Bus c l a s s ” ) ;27 } e l s e {28 System . out . p r i nt l n ( ” Obj ect 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.langpackage compares two objcets for equality. This method returns true, onlyif the two objects being compared refer to the same object. On the otherhand, == operator performs an equivalent comparison. If x==y returnstrue, that means x and y refer to the same object. We should overridethe public int hashCode() method of Object class whenever we override the
8/9/2019 handnote on java
35/72
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 35
equals method. A simple implementation could use a bit wise XOR on the
hash codes of the elements tested for equality.1 p ub li c c l a s s T es t Eq u al s{2 p u b l i c i n t x ;3 p u b l i c i n t y ;45 p ub li c Tes tE q ua ls ( i nt x , i nt y ) {6 t h i s . x=x ;7 t h i s . y=y ;8 }910 p u bl i c b oo le an e qu a ls ( O b je ct o bj ){11 b o o l e a n r es ul t = f a l s e ;12 i f ( ( o bj != n u l l )&&( ob j i n s t a nc e o f T es t Eq u al s ) ){13 Tes t Eq u al s t = ( Tes tE q ua ls ) o b j ;14 i f ( ( x==t . x)&&(y==t . y ) ) {15 r e s u l t = t r u e ;16 }17 }18 r e t u r n r e s u l t ;19 }2021 p ub li c i nt hashCode ( ) {22 r e t u r n ( xˆy ) ;23 }2425 p u bl i c s t a t i c v oi d main ( S t r in g [ ] a r gs ){26 Tes t Eq ua ls t 1 = new Tes t Eq u al s ( 5 , 1 0 ) ;27 Tes t Eq ua ls t 2 = new Tes t Eq u al s ( 5 , 1 0 ) ;28 i f ( t1==t2 ){29 System . out . p r i nt l n ( ” t 1 i s i d e n t i c a l t o t2 ” ) ;30 } e l s e {31 System . out . p r i nt l n ( ” t 1 i s n ot i d e n t i c a l t o t2 ” ) ;32 }33 i f ( t 1 . e q u a l s ( t 2 ) ) {34 System . out . p r i nt l n ( ” t 1 i s e q u a l t o t 2 ” ) ;35 } e l s e {36 System . out . p r i nt l n ( ” t 1 i s not e qu a l to t 2 ” ) ;37 }38 System . o ut . p r i n t l n ( ” S e t t 2=t 1 ” ) ;39 t 2=t 1 ;40 i f ( t1==t2 ){41 System . out . p r i nt l n ( ” t 1 i s i d e n t i c a l t o t2 ” ) ;
8/9/2019 handnote on java
36/72
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 36
42 } e l s e {
43 System . out . p r i nt l n ( ” t 1 i s n ot i d e n t i c a l t o t2 ” ) ;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. Manyclasses override toString to provide more useful information.
1 p u b l i c c l a s s T e st t oS t ri n g {2 p u bl i c s t a t i c v oi d main ( S t ri n g [ ] a r gs ) {3 T es tt oS tr in g now = new Te st to St ri ng ( ) ;4 System . o ut . 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 . o ut . 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 aclass can be declare with static keyword that are associated with the classrather than the instances of the class. The static variable sometime calledclass variable and static method sometime called class method. A staticvariable is similar to global variable in other programming languages. Wecan use the static members of a class without creating the object or instanceof that class. The static methods can only access the local attributes, staticclass attributes, and it’s parameters. Attempting to access non-static classattributes in a static methods will cause a compiler error. We can notoverride the static method. The main() method is a static method because
the JVM does not create an instance of the class when executing the mainmethod. The static block code executed once when the class is loaded.
1 p ub li c c l a s s T e st St at ic {2 p u b l i c s t a t i c i n t count = 1 0 ;34 p ub li c s t a t i c v oi d incrementCount ( ){5 count++;6 }7
8/9/2019 handnote on java
37/72
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 37
8 p ub li c s t a t i c v oi d main ( S tr i ng [ ] a rg s ){
9 f o r ( i n t i =0; i
8/9/2019 handnote on java
38/72
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 38
10 }
1112 p u bl i c c l a s s Car e xt en ds V e hi cl e {13 p ub li c v oi d goFas t ( ){14 System . o ut . p r i n t l n ( ” Car can go f a s t ” ) ;15 }1617 p u bl i c s t a t i c v oi d main ( S t r in g [ ] a r gs ){18 // Vehcle v = new Ve hi cl e ( ) ; // c om p il er e r ro r19 Car c = new Car ( ) ;20 c . show ( ) ;21 c . goFas t ( ) ;
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 arepublic and abstract (do not need to actually type the public and abstractmodifiers 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. Allvariables in an interface are public, static, and final in interfaces. An inter-face can extend one or more other interfaces. An interface cannot implementanother interface or class.
1 i n t e r f a c e B oun cea ble {2 p ub li c a bs tr ac t v o i d bounce ( ) ;3 v o i d setB ounce ( i n t b ) ;4 }56 p u b l i c c l a s s T ir e i m pl em en ts B o un ce ab le {7 p u b l i c v o id bounce ( ) {
8 System . out . p r i nt l n (” Love ” ) ;9 }1011 p ub li c v o i d setBo unce ( i nt b) {12 i n t a = b ;13 System . out . p r i nt l n ( a ) ;14 }1516 p ub li c s t a t i c v o id main ( S tr in g [ ] a rg s ) {17 T i r e t = new T i r e ( ) ;
8/9/2019 handnote on java
39/72
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 39
18 t . bounce ( ) ;
19 t . setB ounce ( 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 canimplements one or more interfaces.
1 a b st r ac t c l a s s Animal {23 p u b l i c v o id ty pe ( ) {4 System . out . p r i nt l n (” Animal ” ) ;5 }67 p ub li c a bs tr ac t v o i d name ( ) ;89 }1011 i n t e r f a c e Cat{12 p ub li c a b st ra ct v oi d jump ( ) ;13 v o i d run ( ) ; // i t w i l l be a ut om a ti cl y p ub li c and a b s tr ac t14 }1516 i n t e r f a c e Bird {17 v o i d f l y ( ) ;18 }192 0 p u b l i c c l a s s T i ge r e x te n d s Animal i mp le me nt s Cat , B ir d {2122 p u b l i c vo id f l y ( ) {23 System . o ut . p r i n t l n ( ” T ig er can ’ t f l y ” ) ;24 }2526 p ub li c v o id jump () {27 System . o ut . p r i n t l n ( ” T ig er can jump ” ) ;28 }2930 p u b l i c v o id run ( ) {31 System . o ut . p r i n t l n ( ” T ig er can run ” ) ;32 }3334 p ub li c v o id name () {
8/9/2019 handnote on java
40/72
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 40
35 System . o ut . p r i n t l n ( ” T ig er ” ) ;
36 }3738 p ub li c s t a t i c v o id main ( S tr in g [ ] a rg s ) {39 T i g e r t = new Ti g e r ( ) ;40 t . name ( ) ;41 t . jump ( ) ;42 t . run ( ) ;43 t . f l y ( ) ;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 inJava programming, known as checked and unchecked exceptions. Checkedexceptions are those that the programmer can easily handle this type of ex-ceptions like: file not found, and network failure etc. Unchecked exceptionsare arises from the conditions that are difficult for programmers to handle.Unchecked exceptions are called runtime exceptions. In Java, Exceptionclass is the base class that represents checked and unchecked exceptions
and RuntimeException class is the base class that is used for the uncheckedexceptions.
1 p u b l i c c l a s s T es tE xc ep ti on A{2 p u bl i c s t a t i c v oi d main ( S t ri n g [ ] a r gs ) {3 i n t sum = 0 ;4 f o r ( i n t i =0; i
8/9/2019 handnote on java
41/72
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 41
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 willexecute. If try block execute without any error, then catch block will notexecute.
1 p u b l i c c l a s s T e st Ex ce pt io nB {2 p ub li c s t a t i c v oi d main ( S tr i ng [ ] a rg s ){3 i n t sum = 0 ;4 f o r ( i n t i =0; i
8/9/2019 handnote on java
42/72
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 42
3.15.3 Call Stack Mechanism
If a statement throws an exception, and that exception is not handled in theimmediately enclosing method, then that exception is throws to the callingmethod. If the exception is not handled in the calling method, it is thrownto the caller of that method. This process continues. If the exception is stillnot handled by the time it gets back to the main() method and main() doesnot 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 blockexecutes properly then catch block will not execute, and if try block will not
execute properly then catch block will execute, but the finally block mustexecutes.
1 p ub li c c l a s s T e s t f i n a l l y {2 p ub li c s t a t i c v oi d main ( S tr i ng [ ] a rg s ){3 t r y {4 i n t i = 9 / 0 ;5 System . out . p ri nt ln ( 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 e 1 ) {7 System . ou t . p r i n t l n ( ” A ri th me ti c E xc ep ti on . ” + e1 ) ;8 } f i n a l l y {9 System . out . p r i nt l n ( ” f i n a l l y b lo ck must e x ec ut es ” ) ;10 }11 }12 }
The E x c ep t i o n D e c l a r e R u l esI n Java , we ca n d e c l a r e e x c e pt i o n s by f o l l o w i n g :1. try −catch− f i n a l l y2. v oid methodA( ) throws IOEx ception{}3 . v o i d methodB ( ) t h r o ws I O Ex c ep t io n , O t h e r E xc e p t i on {}
1 p u bl i c c l a s s D ec la re Ex ce pt io n {
2 p ub li c v oi d methodA ( ){3 t r y {4 } c a t c h ( E x c ep t i on e ) {5 System . out . p r in t ln ( ” I f e r ro r i n t ry t hen c at c h e x e cu te ” ) ;6 } f i n a l l y {7 System . out . p r in t ln ( ” f i n a l l y must e xe cu te s ” ) ;8 }9 }10 p u b l i c v o i d methodB ( ) t hr ow s S e c u ri t yE x c ep t i on {}
8/9/2019 handnote on java
43/72
CHAPTER 3. OBJECT ORIENTED PROGRAMMING 43
1 1 p u b l i c v o id methodC ( ) t hr ow s S e c u r i t yE x c e pt i o n , E x ce p ti o n{
}12 }
3.15.5 Method Overriding and Exception
The overriding method can declare only exceptions that are either the sameclass or a subclass of the exception. For example, if the superclass methodthrows an IOException, then the overriding method of superclass methodcan throw an IOException, a FileNotFoundException, which is the subclassof 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 vo id methodA ( ) t hr ow s I OE xc ep ti on { }3 }45 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 ( ) t hr ow s EOFException {7 // L eg al , b ec au se EOFException i s t he s u b cl a s s o f I OE xc ept io n ;8 }9 }1011 c l a s s C e x te nd s A{1 2 p u b l i c v o i d methodA ( ) t hr ow s Ex c ep t io n {
13 // I l l e g a l , b eca us e Ex c ept io n i s t he s u pe r c la s s o f I OException ;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 MyE xcept io n e xt e nd s E x c ep t io n {2 p u b l i c MyException ( S t r i n g mass ag e ){3 s u p er ( massage ) ;4 }56 p ub li c s t a t i c v oi d main ( S tr i ng [ ] a rg s ){7 t r y {8 throw new MyException (” User d ef in ed e xc ep ti on ” ) ;9 } catch ( My Ex ception e ) {10 System . out . p ri nt ln ( e ) ;11 }12 }13 }
8/9/2019 handnote on java
44/72
Chapter 4
Text-Based and GUI-Based
Applications
4.1 Command-Line Arguments
In Java programming, we can provide zero or more command line argumentsof String type from a terminal window. The sequence of arguments followsthe name of the program class and is stored in an array of String objectspassed 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 bl i c s t a t i c v oi d main ( S t ri n g [ ] a r gs ) {3 f o r ( i n t i =0; i
8/9/2019 handnote on java
45/72
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 45
3. System.err (System.err is a PrintStream onject)
Following code provides an example of keybord input, which importthe java.io.*; package. In line 6, InputStreamReader reads characters andconverts the row bytes into Unicode characters. In line 7, BufferedReaderprovides the readLine() method (in line 10), which enables the program toread from standard input (keyboard) one line at a time. Line 12, close thebuffered reader. The readLine() method can throw an I/O exception, so thiscode is in a try-catch block.
1 i mp or t j a va . i o . ∗ ;23 p ub li c c l a s s C on so le Inp ut {
4 p ub li c s t a t i c v oi d main ( S tr i ng [ ] a rg s ){5 S t r i n g s ;6 I np ut St re am Re ad er i s r = new I np ut St re am Re ad er ( S yst em . i n ) ;7 B uf fe re dR ea de r i n = new B uf fe re dR ea de r ( i s r ) ;8 t r y {9 System . out . p r i nt l n ( ” Write s omething : ” ) ;10 s = i n . r e a d L i n e ( ) ;11 System . out . p r i nt l n ( ”Read : ” + s ) ;12 i n . c l o s e ( ) ;13 } c a t c h ( I O E xc e p ti o n e ){14 e . p r i n t S t a c k T r a c e ( ) ;
15 }16 }17 }
4.3 Scanner
The scanner class provides formated input functionality. It is a part of the java.util package.
1 i mp or t j a va . i o . ∗ ;2 i m po r t j a v a . u t i l . S c an n er ;34 p u bl i c c l a s s S ca nn er Te st {5 p ub li c s t a t i c v oi d main ( S tr i ng [ ] a rg s ){6 Scanner s = new Scanner ( S ystem . i n ) ;7 S t r i n g s t r = s . nex t ( ) ;8 System . out . p r i nt l n ( s t r ) ;9 i n t num = s . n e x t I n t ( ) ;10 System . o ut . p r i n t l n (num ) ;11 s . c l o s e ( ) ;
8/9/2019 handnote on java
46/72
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 46
12 }
13 }
4.4 File in Java
To access a physical file we have to create a File object, which contains theaddress and name of the file. The FileReader class uses to read charactersfrom a file and the FileWriter class uses to write characters to a file. ThePrintWriter class is used the print() and println() methods.
4.4.1 Write String to a File
1 i mp or t j a va . i o . ∗ ;23 p ub li c c l a s s W ri te Fi le {4 p ub li c s t a t i c v oi d main ( S tr i ng [ ] a rg 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 t r y {7 Inp utS tr ea mRea der i s r = new Inpu tSt re amR ead er ( S ystem . i n ) ;8 B u f f e r e d Re a d e r in = new B u f f e r e d R ea d e r ( i s r ) ;9 P ri nt Wr it er out = new P ri nt Wr it er ( new F i le Wr it er ( f i l e ) ) ;10 System . out . p r in t ln ( ” Write S t ri ng : ” ) ;
11 S t r i n g s t r = i n . r e a d L i n e ( ) ;12 out . p r i n t l n ( s t r ) ;13 i n . c l o s e ( ) ;14 out . c l o s e ( ) ;15 } c a t c h ( I O E xc e p ti o n e ) {16 e . p r i n t S t a c k T r a c e ( ) ;17 }18 }19 }
4.4.2 Read String from a File
1 i mp or t j a va . i o . ∗ ;23 p ub li c c l a s s Rea dF ile {4 p ub li c s t a t i c v oi d main ( S tr i ng [ ] a rg 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 t r y {7 B uf fe re dR ea de r i n = new B uf fe re dR ea de r ( new F i le Re ad er ( f i l e ) ) ;8 S t r i n g s t r = i n . r e a d L i n e ( ) ;9 w h i l e ( s t r != n u l l ) {
8/9/2019 handnote on java
47/72
8/9/2019 handnote on java
48/72
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 48
20 p . setBackg round ( C olo r . g re en ) ;
21 f . add ( p ) ;22 f . s e t V i s i b l e ( t r u e ) ;23 }242 5 p u b l i c v o id wi nd ow Cl os in g ( WindowEvent e ) {26 System . e xi t ( 0 ) ;27 }282 9 p u b l i c v o i d windowOpened ( W indowEvent e ) { }3 0 p u b l i c v o i d w i n d o w I co n i f i e d ( WindowEvent e ){ }3 1 p u b l i c v o id w i nd o w De i co n i fi e d ( WindowEvent e ) { }
3 2 p u b l i c v o i d wi nd ow Cl os ed ( W indowEvent e ) { }3 3 p u b l i c v o i d wi nd ow Ac ti va te d ( WindowEvent e ) { }3 4 p u b l i c v o i d wi nd ow De ac ti va te d ( WindowEvent e ) { }3536 p ub li c s t a t i c v o id main ( S tr in g [ ] a rg s ) {3 7 FrameWithPanel fp = new Fra meWithPanel ( ) ;38 f p . launchFrame ( ) ;39 }40 }
1 i mp or t j a v a . awt . ∗ ;
2 i mp or t j a v a . awt . e v en t . ∗ ;34 p u b l i c c l a s s TestMenuBar i m pl e me n ts W in do wL is te ne r , 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 iv a te MenuBar mb;7 p r iv a te Menu m1, m2, m3 ;8 p r i v a t e M enuItem mi1 , mi2 , mi3 , mi4 ;910 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 dit ” ) ;15 m3 = new Menu(” Help ” ) ;16 mi1 = new MenuItem (”New ” ) ;17 mi2 = new MenuItem (” S ave ” ) ;18 mi3 = new MenuItem (” Load ” ) ;19 mi4 = new MenuItem (” Q uit ” ) ;20 }2122 p ub li c v o id launchFrame ( ) {
8/9/2019 handnote on java
49/72
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 49
21 mi4 . a dd Ac ti on Li st en er ( t h i s ) ;
22 m1 . add ( mi1 ) ;23 m1 . add ( mi2 ) ;24 m1 . add ( mi3 ) ;25 m1 . a dd S ep a r a to r ( ) ;26 m1 . add ( mi4 ) ;2728 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 . s e tS iz e ( 4 0 0 , 4 0 0 ) ;35 f . setBackg round ( C olo r . r ed ) ;36 f . s e t La y o u t ( n ul l ) ;37 f . s e t V i s i b l e ( t r u e ) ;38 }3940 p u b l i c vo id a c ti o nP er f or m ed ( A c ti on Ev en t e ) {41 System . e xi t ( 0 ) ;42 }43
4 4 p u b l i c v o id wi nd ow Cl os in g ( WindowEvent e ) {45 System . e xi t ( 0 ) ;46 }474 8 p u b l i c v o i d windowOpened ( W indowEvent e ) { }4 9 p u b l i c v o i d w i n d o w I co n i f i e d ( WindowEvent e ){ }5 0 p u b l i c v o id w i nd o w De i co n i fi e d ( WindowEvent e ) { }5 1 p u b l i c v o i d wi nd ow Cl os ed ( W indowEvent e ) { }5 2 p u b l i c v o i d wi nd ow Ac ti va te d ( WindowEvent e ) { }5 3 p u b l i c v o i d wi nd ow De ac ti va te d ( WindowEvent e ) { }54
55 p ub li c s t a t i c v o id main ( S tr in g [ ] a rg s ) {5 6 TestMenuBar tmb = new TestMenuBar ( ) ;57 tmb . launchFrame ( ) ;58 }59 }
8/9/2019 handnote on java
50/72
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 50
4.6 J2SE Event Model
An event is issued, when the user performs and action at the user interfacelevel like: clicks a mouse or presses a key.
1 i mp or t j a v a . awt . ∗ ;2 i mp or t j a v a . awt . e v en t . ∗ ;34 p u b l i c c l a s s E ve nt Ha nd le i mp le me nt s W in do wL is te ne r , A c t i o n L i s t e n e r {5 p ri va te Frame f ;6 p ri v a te Button b1 , b2 , b3 ;7 p r iv at e T e x t F i e l d t f ;8
9 p ub li c EventHandle ( ) {10 f = new Frame ( ” But ton H an dl in g ” ) ;11 b1 = new Button ( ”YES ” ) ;1 2 b1 . set Act io nCo mma nd ( ” y e s b u t t on ” ) ;13 b2 = new Button ( ”NO” ) ;1 4 b2 . set Act io nCo mma nd ( ” n o b u tt o n ” ) ;15 b3 = new Button ( ” C le ar ” ) ;1 6 b3 . setActionCommand ( ” c l e a r b ut to n ” ) ;17 t f = new T e x t F i e l d ( 3 0 ) ;18 }19
20 p u bl i c vo id launchFrame ( ) {21 b1 . a dd Ac ti on Li st en er ( t h i s ) ;22 b1 . s et F or eg r ou nd ( C ol or . w hi te ) ;23 b1 . s et Ba ck gr ou nd ( C ol or . b l ue ) ;2425 b2 . a dd Ac ti on Li st en er ( t h i s ) ;26 b2 . s et F or eg r ou nd ( C ol or . r ed ) ;27 b2 . s et Ba ck gr ou nd ( C ol or . g r ee n ) ;2829 b3 . a dd Ac ti on Li st en er ( t h i s ) ;30 b3 . s et F or eg r ou nd ( C ol or . b l ue ) ;
31 b3 . s et Ba ck gr ou nd ( C ol or . y e ll o w ) ;3233 t f . s et F or eg r ou nd ( C o lo r . b l ue ) ;34 t f . s et Ba ck gr ou nd ( C ol or . w hi te ) ;353 6 f . s e tL a yo u t ( new F lo wLa yo ut ( ) ) ;37 f . add ( b1 ) ;38 f . add ( b2 ) ;39 f . add ( b3 ) ;
8/9/2019 handnote on java
51/72
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 51
40 f . add ( t f ) ;
41 f . a dd Wi nd owLi st ene r ( t h i s ) ;42 f . s e t S i z e ( 25 0 , 15 0) ;43 f . s et Ba ck gr ou nd ( C ol or . r ed ) ;44 f . s e t V i s i b l e ( t ru e ) ;45 }4647 p u b l i c v oi d a c ti o nP e rf o rm ed ( A c ti on Ev en t e ) {48 S t r i n g s t r ;4 9 i f ( e . g etActio nComma nd ()==” y e s b u tt o n ” ) {50 s t r = ”You p re ss YES button ” ;51 t f . s e t Te x t ( s t r ) ;
52 }5 3 i f ( e . g et Ac ti on Co mm an d()==” no b u t t o n ” ) {54 s t r = ”You p re ss NO button ” ;55 t f . s e t Te x t ( s t r ) ;56 }5 7 i f ( e . g etActio nComma nd ()==” c l e a r b u tt o n ” ) {58 s t r = ” ” ;59 t f . s e t Te x t ( s t r ) ;60 }61 }62
6 3 p u b l i c v o i d w in do w Cl o si ng ( WindowEvent e ) {64 System . e x it ( 0 ) ;65 }666 7 p u b l i c v o i d w ind ow Op ened ( W indowEvent e ) { }6 8 p u b l i c v o id w i n d o wI c o n i fi e d ( WindowEvent e ) {}6 9 p u b l i c v o i d w i n d o w De i c o n i f ie d ( WindowEvent e ) { }7 0 p u b l i c v o i d w in do wC lo se d ( W indowEvent e ) { }7 1 p u b l i c v o i d w in d ow Ac ti va t ed ( WindowEvent e ) {}7 2 p u b l i c v o i d w in d ow D ea c ti va t ed ( WindowEvent e ) { }73
74 p u bl i c s t a t i c v oi d main ( S t r in g [ ] a r gs ){7 5 E ve nt Ha nd le eh = new Ev en tH an dl e ( ) ;76 eh . launchFrame ( ) ;77 }78 }
4.6.1 Mouse Example
1 i mp or t j a v a . awt . ∗ ;
8/9/2019 handnote on java
52/72
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 52
2 i mp or t j a v a . awt . e v en t . ∗ ;
34 p u b l i c c l a s s M ouse Exa mp le i m p le m e nt s W i nd o wL i st e ne r , M o u se M o ti o n Li s t en5 p ri va te Frame f ;6 p r iv at e T e x t F i e l d t f ;78 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 }1213 p u bl i c vo id launchFrame ( ) {
14 La be l l a b e l = new La be l (” C l ic k and d ra g t he mouse ” ) ;1 5 f . a dd ( l a b e l , B or d er La y ou t .NORTH) ;1 6 f . a dd ( t f , B or d er La yo ut . SOUTH ) ;17 f . a dd Mo us eM ot io nL is te ne r ( t h i s ) ;18 f . a dd Mo us eL is te ne r ( t h i s ) ;19 f . a dd Wi nd owLi st ene r ( t h i s ) ;20 f . s e t S i z e ( 30 0 , 20 0) ;21 f . s e t V i s i b l e ( t ru e ) ;22 }232 4 p u b l i c v o i d m ou se Dr ag ge d ( M ou seE vent e ){
2 5 S t r i n g s = ” Mouse d r a g g ed : X= ”+ e . g et X ( )+ ” Y=”+e . g et Y ( ) ;26 t f . s e t T e x t ( s ) ;27 }282 9 p u b l i c v o id m ou se En te re d ( M ouseEvent e ) {30 S tr i ng s = ”The mouse e nt er ed ” ;31 t f . s e t T e x t ( s ) ;32 }333 4 p u b l i c v o i d m ou se Ex it ed ( MouseEvent e ) {35 S tr in g s = ”The mouse has l e f t th e b u il di ng ” ;
36 t f . s e t T e x t ( s ) ;37 }383 9 p u b l i c v o i d m ou se Pr es se d ( M ouseEvent e ){ }4 0 p u b l i c v o i d m ou se Re le as ed ( MouseEvent e ) { }4 1 p u b l i c v o i d mouseMoved ( M ou seEv ent e ) { }4 2 p u b l i c v o i d mo us eC li ck ed ( MouseEvent e ){ }434 4 p u b l i c v o i d w in do w Cl o si ng ( WindowEvent e ) {45 System . e x it ( 0 ) ;
8/9/2019 handnote on java
53/72
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 53
Table 4.1: Table Color class static constants and RGB values.
Color Constant Color RGB valuepublic 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 }474 8 p u b l i c v o i d w ind ow Op ened ( W indowEvent e ) { }4 9 p u b l i c v o id w i n d o wI c o n i fi e d ( WindowEvent e ) {}5 0 p u b l i c v o i d w i n d o w De i c o n i f ie d ( WindowEvent e ) { }5 1 p u b l i c v o i d w in do wC lo se d ( W indowEvent e ) { }
5 2 p u b l i c v o i d w in d ow Ac ti va t ed ( WindowEvent e ) {}5 3 p u b l i c v o i d w in d ow D ea c ti va t ed ( WindowEvent e ) { }5455 p u bl i c s t a t i c v oi d main ( S t r in g [ ] a r gs ){5 6 Mo useE xam pl e me = new M ou seE xam pl e ( ) ;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 takean arguments that is an instance of of java.awt.Color class. We can use theconstant 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 thecolor by a combination of three byte-sized integers (0-255), one for eachprimary color: red, green, and blue.
1 i mp or t j a v a . awt . ∗ ;2 i mp or t j a v a . awt . e v en t . ∗ ;
8/9/2019 handnote on java
54/72
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 54
3
4 p u b l i c c l a s s T e s tC o l o rs i mp le me nt s W i nd ow Li st en er , A c t i o n L i s t e n e r {5 p ri va te Frame f ;6 p r iv at e Button b ;78 p ub li c T e s t Co lo rs ( ){9 f = new Frame (” Frame T i t l e ” ) ;10 b = new Button ( ” Change Co lo r ” ) ;11 b . setActionCommand ( ” b ut to n p r e s s ” ) ;12 }1314 p u bl i c vo id launchFrame ( ) {
15 b . a dd Ac ti on Li st en er ( t h i s ) ;16 b . s et Fo re gr ou nd ( C o lo r . r ed ) ;17 b . se tBa ck gr ou nd ( C ol or . y el lo w ) ;18 f . add ( b ) ;19 f . addWindowListener ( t h i s ) ;20 f . s et S i z e ( 3 00 , 30 0) ;21 f . se tBa ck gr ou nd ( C ol or . g re en ) ;22 f . s et La yo ut ( new FlowLayout ( ) ) ;23 f . s e t V i s i b l e ( t r u e ) ;24 }25
26 p u b l i c v oi d a c ti o nP e rf o rm ed ( A c ti on Ev en t e ) {27 i n t x , y , z ;2 8 i f ( e . get ActionCo mmand ()==” b u tt o n 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 Col or c = new Co lo r (x , y , z ) ;33 f . s etB ackgr ound ( c ) ;34 }35 }36
3 7 p u b l i c v o i d w in do w Cl o si ng ( WindowEvent e ) {38 System . e xi t ( 0 ) ;39 }404 1 p u b l i c v o i d w ind ow Op ened ( W indowEvent e ) { }4 2 p u b l i c v o id w i n d o wI c o n i fi e d ( WindowEvent e ) {}4 3 p u b l i c v o i d w i n d o w De i c o n i f ie d ( WindowEvent e ) { }4 4 p u b l i c v o i d w in do wC lo se d ( W indowEvent e ) { }4 5 p u b l i c v o i d w in d ow Ac ti va t ed ( WindowEvent e ) {}4 6 p u b l i c v o i d w in d ow D ea c ti va t ed ( WindowEvent e ) { }
8/9/2019 handnote on java
55/72
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 55
47
48 p u bl i c s t a t i c v oi d main ( S t r in g [ ] a r gs ){49 T es t Co lo rs t c = new T e st C ol or 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 areincluded with the Java programming language:
1. FlowLayout The FlowLayout is the default layout manager of Paneland 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 aprimitive tabbed panel.
5. GridBagLayout -
FlowLayout manager uses line-by-line technique to place the componentsin a container. Each time a line is filled, a new line is started. It does notconsider the size of components.
1 i mp or t j a v a . awt . ∗ ;2 i mp or t j a v a . awt . e v en t . ∗ ;3
4 p u b l i c c l a s s Fl owE xam ple i m pl e me n ts W in do wL is te ne r{5 p ri va te Frame f ;6 p ri v a te Button b1 , b2 , b3 ;78 p u bl 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 }
8/9/2019 handnote on java
56/72
8/9/2019 handnote on java
57/72
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 57
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 }1718 p u bl i c vo id launchFrame ( ) {1 9 f . a dd ( b1 , B o r de r La y ou t .NORTH ) ;2 0 f . a dd ( b 2 , B or d er L ay ou t . SOUTH ) ;2 1 f . a dd ( b 3 , B or d er L ay ou t .WEST ) ;
2 2 f . add ( b4 , B or de rL ay ou t . EAST ) ;2 3 f . a dd ( b5 , B o r de r La y ou t . CENTER ) ;24 f . a dd Wi nd owLi st ene r ( t h i s ) ;25 f . s e t S i z e ( 25 0 , 25 0) ;26 f . s et Ba ck gr ou nd ( C ol or . r ed ) ;27 f . s e t V i s i b l e ( t ru e ) ;28 }293 0 p u b l i c v o i d w in do w Cl o si ng ( WindowEvent e ) {31 System . e x it ( 0 ) ;32 }
333 4 p u b l i c v o i d w ind ow Op ened ( W indowEvent e ) { }3 5 p u b l i c v o id w i n d o wI c o n i fi e d ( WindowEvent e ) {}3 6 p u b l i c v o i d w i n d o w De i c o n i f ie d ( WindowEvent e ) { }3 7 p u b l i c v o i d w in do wC lo se d ( W indowEvent e ) { }3 8 p u b l i c v o i d w in d ow Ac ti va t ed ( WindowEvent e ) {}3 9 p u b l i c v o i d w in d ow D ea c ti va t ed ( WindowEvent e ) { }4041 p u bl i c s t a t i c v oi d main ( S t r in g [ ] a r gs ){4 2 B or der Exa mp le b e = new Bo rde rE xa mp le ( ) ;43 be . launchFrame ( ) ;
44 }45 }
The GridLayout manager placing components with a number of rows andcolumns. The following constructor creates a GridLayout with the specifiedequal size. new GridLayout(int rows, int cols);
1 i mp or t j a v a . awt . ∗ ;2 i mp or t j a v a . awt . e v en t . ∗ ;34 p u b l i c c l a s s G ri dE xa mp le i m p l em e nt s W i nd ow Li st en er {
8/9/2019 handnote on java
58/72
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 58
5 p ri va te Frame f ;
6 p r i va t e Button b1 , b2 , b3 , b4 , b5 , b6 ;78 p ub li 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 }
1718 p u bl i c vo id launchFrame ( ) {1 9 f . s e tL a yo u t ( new G r id La yo ut ( 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 . a dd Wi nd owLi st ene r ( t h i s ) ;27 f . s e t S i z e ( 30 0 , 30 0) ;
28 f . s et Ba ck gr ou nd ( C ol or . r ed ) ;29 f . s e t V i s i b l e ( t ru e ) ;30 }313 2 p u b l i c v o i d w in do w Cl o si ng ( WindowEvent e ) {33 System . e x it ( 0 ) ;34 }353 6 p u b l i c v o i d w ind ow Op ened ( W indowEvent e ) { }3 7 p u b l i c v o id w i n d o wI c o n i fi e d ( WindowEvent e ) {}3 8 p u b l i c v o i d w i n d o w De i c o n i f ie d ( WindowEvent e ) { }
3 9 p u b l i c v o i d w in do wC lo se d ( W indowEvent e ) { }4 0 p u b l i c v o i d w in d ow Ac ti va t ed ( WindowEvent e ) {}4 1 p u b l i c v o i d w in d ow D ea c ti va t ed ( WindowEvent e ) { }4243 p u bl i c s t a t i c v oi d main ( S t r in g [ ] a r gs ){4 4 Gri dE xa mp le g e = new Gr idE xa mple ( ) ;45 g e . launchFrame ( ) ;46 }47 }
8/9/2019 handnote on java
59/72
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 59
4.9 Java Foundation Classes/ Swing Technology
The Java Foundation Classes (J.F.C.)/ Swing technology is a second-generationGUI toolkit that is included in the Java 2 SDK as a standard extension.Swing technology has many improvement over AWT and adds many newand 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 Fontclass takes three arguments: the font name, font style, and font size. Thefont name is any font currently supported by the system where the programis running such as standard Java fonts Monospaced, SansSerif, and Serif.The font style is Font.PLAIN, Font.ITALIC, or Font.BOLD. Font styles canbe used in combination such as: Font.ITALIC + Font.BOLD.
1 i mp or t j a v a . awt . ∗ ;2 i mp or t j a v a . awt . e v en t . ∗ ;3 i m po r t j a v a x . s w in g . ∗ ;45 p u b l i c c l a s s T es tF on ts e xt e nd s JFrame{6 p ri v a te s t a t i c f i n a l lo ng s er ia lV er si on UI D =0;78 p ub li c Tes tFonts ( ){
9 s up er ( ”Font Examples ” ) ;10 s et Si ze ( 3 0 0 , 1 5 0 ) ;11 show ( ) ;12 }1314 p ub li c v oi d p a in t ( G raph ics g ) {15 g . d ra wS tr in g ( ” Welcome t o Ja va . ” , 2 0 , 5 0 ) ;16 g . s e tC o lo r ( C o lo r . r ed ) ;1 7 g . s e t F o n t ( new F on t ( ” M o no sp ac ed ” , F on t . BOLD, 1 4 ) ) ;18 g . d ra wS tr in g ( ” Welcome t o Ja va . ” , 2 0 , 7 0 ) ;19 g . s e tC o lo r ( C o lo r . b lu e ) ;
2 0 g . s e t F o n t ( new F on t ( ” S a n s S e r i f ” , F on t . BOLD + F o nt . I TALIC , 1 6 ) ) ;21 g . d ra wS tr in g ( ” Welcome t o Ja va . ” , 2 0 , 9 0 ) ;22 }2324 p u bl i c s t a t i c v oi d main ( S t r in g [ ] a r gs ){25 TestFonts t f = new TestFonts ( ) ;26 t f . a ddW ind ow List en er (27 new WindowAdapter ( ){28 p ub li c v o i d windowClosing ( WindowEvent e ) {29 System . e x i t ( 0 ) ;
8/9/2019 handnote on java
60/72
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 60
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 i mp or t j a v a . awt . ∗ ;2 i mp or t j a v a . awt . e v en t . ∗ ;3 i m po r t j a v a x . s w in g . ∗ ;45 p u b l i c c l a s s T es tL in eR ec tO va l e x t e nd s JFrame{6 p ri v a te s t a t i c f i n a l lo ng s er ia lV er si on UI D =0;78 p u bl i c T est Li ne Re ct Ova l ( ){9 s up er ( ” L in es R a ct an gl es O vals ” ) ;10 s et Si ze ( 3 6 0 , 4 5 0 ) ;11 show ( ) ;12 }1314 p ub li c v oi d p a in t ( G raph ics g ) {15 g . s e tC o lo r ( C o lo r . r ed ) ;16 g . drawLine ( 5 0 , 40 , 30 0 , 4 0 ) ;1718 g . s e tC o lo r ( C o lo r . b lu e ) ;19 g . drawRect ( 5 0 , 60 , 10 0 , 6 0 ) ;20 g . f i l l R e c t ( 20 0 , 60 , 1 0 0 , 6 0 ) ;2122 g . s e t C ol o r ( C o lo r . cya n ) ;23 g . drawRoundRect ( 5 0 , 1 50 , 1 00 , 6 0 , 5 0 , 5 0 ) ;24 g . f i l lR ou nd Re ct ( 20 0 , 15 0 , 1 00 , 6 0 , 5 0 , 5 0 ) ;2526 g . s e tC o lo r ( C o lo r . y el lo w ) ;27 g . draw3DRect ( 5 0 , 2 50 , 1 00 , 6 0 , t r ue ) ;28 g . f i l l 3 DR e ct ( 20 0 , 25 0 , 1 00 , 6 0 , t ru e ) ;2930 g . s e t C ol o r ( C o lo r . magenta ) ;31 g . drawOval ( 5 0 , 3 50 , 1 00 , 6 0 ) ;32 g . f i l l O v a l ( 20 0 , 3 50 , 1 0 0 , 6 0 );33 }
8/9/2019 handnote on java
61/72
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 61
34
35 p u bl i c s t a t i c v oi d main ( S t r in g [ ] a r gs ){36 T es tL in eR ec tO va l t l r o = new Te st Li ne Re ct Ov al ( ) ;37 t l r o . addWindowListener (38 new WindowAdapter ( ){39 p ub li c v o id 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 i mp or t j a v a . awt . ∗ ;2 i mp or t j a v a . awt . e v en t . ∗ ;3 i m po r t j a v a x . s w in g . ∗ ;45 p u b l i c c l a s s Password e xt en ds JFrame{6 p ri v a te s t a t i c f i n a l lo ng s er ia lV er si on UI D =0;78 p r iv at e JLa bel l 1 , l 2 ;
9 p ri va te J T e x t F i e l d t1 ;10 p r i va t e J Pa ss wo rd Fi el d pw ;11 p r i va t e J Button b1 , b2 ;1213 p ub li c Password ( ) {14 s up er ( ” Passwo rd Example ” ) ;15 C on ta in er c = g etCo nt entP ane ( ) ;1 6 c . s e tL a yo u t ( new F lo wLa yo ut ( ) ) ;1718 l 1 = new JLabel ( ” Enter User Name ” ) ;19 c . add ( l 1 ) ;
2021 t 1 = new J T ex t F i e l d ( 1 5 ) ;22 c . add ( t1 ) ;2324 l 2 = new JLabel ( ” E nter Password ” ) ;25 c . add ( l 2 ) ;2627 pw = new JP as sw or dF ie ld ( 1 0 ) ;28 c . add (pw ) ;29
8/9/2019 handnote on java
62/72
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 62
30 b1 = new JButton ( ” E nt er ” ) ;
31 b1 . a dd Ac ti on Li st en er (32 new A c t i o n L i s t e n e r ( ) {33 p ub li c v o id a ct i o n P e r f o r m e d ( ActionEvent e ){34 i f ( t 1 . g et Te xt ( ) . e q ua l s ( ” f a r i d ” ) && pw . g et Tex t ( ) . e qu a ls ( ”1 23 435 JOptionPane . showMessageDialog ( n ul l , ”Welcome t o Java ” ) ;36 } e l s e {37 JOptionPane . showMessageDialog ( n ul l , ” I n co r re ct u se r name38 }39 }40 }41 ) ;
42 c . add (b1 ) ;4344 b2 = new JButton ( ” C an ce l ” ) ;45 b2 . a dd Ac ti on Li st en er (46 new A c t i o n L i s t e n e r ( ) {47 p ub li c v o id a ct i o n P e r f o r m e d ( ActionEvent e ){48 S t r i n g s = ” ” ;49 t 1 . s e t T e x t ( s ) ;50 pw . s e t T e x t ( s ) ;51 }52 }
53 ) ;54 c . add (b2 ) ;5556 s et Si ze ( 3 0 0 , 1 2 5 ) ;57 show ( ) ;58 }5960 p u bl i c s t a t i c v oi d main ( S t r in g [ ] a r gs ){6 1 P as sw or d PW = new P ass wo rd ( ) ;6 2 PW. a dd Wi nd ow Li st en er (63 new WindowAdapter ( ){
64 p ub li c v o id 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.
8/9/2019 handnote on java
63/72
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 63
1 i mp or t j a v a . awt . ∗ ;
2 i mp or t j a v a . awt . e v en t . ∗ ;3 i m po r t j a v a x . s w in g . ∗ ;45 p u b l i c c l a s s TestJComt e x te n ds J Frame{6 p ri v a te s t a t i c f i n a l lo ng s er ia lV er si on UI D =0;78 p r iv a te JCheckBox bold , i t a l i c ;9 p r i v a t e J Rad io Bu tt on male , f e ma l e ;1 0 p r i v a t e Butto nGro up r ad io Gr ou p ;1 1 p r i v a t e JComboBox cBox ;12 p ri va te S tr in g [ ] s tr 1 = {” s p r i n g ” , ” summer ” , ” f a l l ”} ;
13 p ri va te J L is t c o l o r L i s t ;14 p ri va te S tr in g [ ] s tr 2 = {” Red ” , ” G re en ” , ” B l u e ” , ” B l a c k ” , ” Wh it e ” , ”15 ” Orange ” , ” Pink ” , ”Magenta ” , ”Sky ” , ”Cya16 p r i va t e J TextArea t a 1 ;1718 p u b l i c TestJComt ( ) {19 s up er ( ” T es t JComponents ” ) ;20 C on ta in er c = g etCo nt entP ane ( ) ;2 1 c . s e tL a yo u t ( new F lo wLa yo ut ( ) ) ;2223 b ol d = new JCheckBox ( ” Bold ” ) ;
24 c . add ( b o ld ) ;25 i t a l i c = new JCheckBox (” I t a l i c ” ) ;26 c . add ( i t a l i c ) ;2728 male = new JR ad io Bu tt on ( ” Male ” ) ;29 c . add ( male ) ;30 f em a le = new JR adio Bu tt on ( ” F emale ” ) ;31 c . add ( f e m a l e ) ;3 2 r ad io Gr ou p = new ButtonGroup ( ) ;33 r ad io Gr oup . a dd ( male ) ;34 r ad io Gr oup . a dd ( f em al e ) ;
353 6 cBox = new JComboBox ( s t r 1 ) ;37 c . add ( cBox ) ;3839 c o l o r L is t = new J L i st ( s t r 2 ) ;40 c o l o r L i s t . se tV is ib le Ro wC ou nt ( 5 ) ;41 c . a dd ( new J S c ro ll P an e ( c o l o r L i s t ) ) ;4243 S tr i ng s = ” Java i s a o b je ct o r ie nt e d programming l a ng ua ge ” ;44 ta 1 = new JTextArea ( s , 1 0 , 1 5 );
8/9/2019 handnote on java
64/72
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 64
45 c . a dd ( new J Sc ro ll P an e ( t a 1 ) ) ;
4647 s et Si ze ( 2 0 0 , 3 5 0 ) ;48 show ( ) ;49 }5051 p u bl i c s t a t i c v oi d main ( S t r in g [ ] a r gs ){5 2 TestJComt j c = new TestJComt ( ) ;53 j c . a dd Win do wLis ten er (54 new WindowAdapter ( ){55 p ub li c v o id windowClosing ( WindowEvent e ) {56 System . e x i t ( 0 ) ;
57 }58 }59 ) ;60 }61 }
1 i mp or t j a v a . awt . ∗ ;2 i mp or t j a v a . awt . e v en t . ∗ ;3 i m po r t j a v a x . s w in g . ∗ ;45 p u b l i c c l a s s O pe nF il e e x te nd s JFrame{
6 p ri v a te s t a t i c f i n a l lo ng s er ia lV er si on UI D =0;7 p ri va te JButton b1 ;8 p ri va te J F i l e C h o o s e r j f c ;910 p u bl i c Op en Fil e ( ) {11 s up er ( ” F i l e Opener ” ) ;12 b1 = new JButto n (” Open F i l e C ho os er ” ) ;13 b1 . a dd Ac ti on Li st en er (14 new A c t i o n L i s t e n e r ( ) {15 p ub li c v o id a ct i o n P e r f o r m e d ( ActionEvent e ){16 abc ( ) ;
17 }18 }19 ) ;2 0 g e t Co n t en t P an e ( ) . a dd ( b1 , B o r de r La y ou t .NORTH ) ;21 s et Si ze ( 3 0 0 , 2 0 0 ) ;22 show ( ) ;23 }2425 p ri va te vo id abc ( ){26 j f c = new J F i l e C h o os e r ( ) ;
8/9/2019 handnote on java
65/72
CHAPTER 4. TEXT-BASED AND GUI-BASED APPLICATIONS 65
27 j f c . showOpenDia log ( t h i s ) ;
28 }2930 p u bl i c s t a t i c v oi d main ( S t r in g [ ] a r gs ){31 OpenFile o f = new OpenFile ( ) ;32 o f . a ddW indo wList en er (33 new WindowAdapter ( ){34 p ub li c v o id windowClosing ( WindowEvent e ){35 System . e x i t ( 0 ) ;36 }37 }38 ) ;
39 }40 }
8/9/2019 handnote on java
66/72
Chapter 5
Threads, Sockets, and
Collections API
5.1 Java Threads
Modern computer performs multiple jobs at the same time. Thread is theprocess of multi-tasking using CPU, which performs computations. A threador 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. Aprocess is a program in execution. One or more threads a process. A threadis composed of CPU, code, and data. Code can share multiple threads, twothreads can share the same code. We can create thread by implementingRunnable 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 mustcall its start() method.
1 p u b l i c c l a s s T hr ea dT es t i m pl em en ts R un na bl e{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
8/9/2019 handnote on java
67/72
CHAPTER 5. THREADS, SOCKETS, AND COLLECTIONS API 67
8 }
910 p u bl i c s t a t i c v oi d main ( S t r in g [ ] a r gs ){11 Th rea dTest t = new Th rea dTe st ( ) ;12 Thread t hr ea d1 = new Thread ( t ) ;13 Thread t hr ea d2 = new Thread ( t ) ;14 Thread t hr ea d3 = new Thread ( t ) ;15 t h r e a d 1 . s t a r t ( ) ;16 t h r e a d 2 . s t a r t ( ) ;17 t h r e a d 3 . s t a r t ( ) ;18 }19 }
1 p u b l i c c l a s s MyThread e x t e nd 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
8/9/2019 handnote on java
68/72
8/9/2019 handnote on java
69/72
CHAPTER 5. THREADS, SOCKETS, AND COLLECTIONS API 69
28
29 p u b l i c P ro du ce r ( MyStack s ) {30 s