Escolar Documentos
Profissional Documentos
Cultura Documentos
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
1/198
Document History
Date Version By Remarks
27 Dec. 2006 0.01 Y. Shiraishi Draft version
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
2/198
Contents at a Glance
1. Concept of Java Language <Day1> .............................................................................. 9
2. Java Programming Grammar basics (I) <Day1> ......................................................... 19
3. Java Programming Grammar basics (II) <Day2> ........................................................ 35
4. Class and Object <Day2>............................................................................................62
5. Thread <Day3> ........................................................................................................ 79
6. Input and Output Stream <Day3-2>............................................................................. 90
7. Network <Day4-1>..................................................................................................... 103
8. Nested Classes <Day 4-2>........................................................................................ 114
9. J2SE5.0 New features <Day 4-2> ............................................................................. 125
10. Java GUI (I) <Day 5> ............................................................................................. 140
11. Java GUI (II) <Day 6> ............................................................................................ 162
Tables and Figures ........................................................................................................... 195
Indexes ............................................................................................................................. 196
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
3/198
Table of Contents
1. Concept of Java Language <Day1-1> ........................................................................... 9
1.1. Characteristic of Java Language ............................................................................ 9
1.1.1. What is object oriented language? .................................................................. 9
1.1.2. What is Java?..................................................................................................9
1.1.3. Characteristic of Java Language ..................................................................... 9
1.2. Getting started with “HelloWorld” program ........................................................... 11
1.2.1. Download JDK from Sun site ........................................................................ 11
1.2.2. Create a program .......................................................................................... 12
1.2.3. How to compile?............................................................................................ 14
1.2.4. How to execute?............................................................................................ 15
1.2.5. HelloWorld with Eclipse................................................................................. 16
Exercise 1: HelloWorld .................................................................................................... 18
2. Java Programming Grammar basics (I) <Day1-2> ...................................................... 19
2.1. Variable data ........................................................................................................ 19
2.1.1. Variables ....................................................................................................... 19
2.1.2. Reference types ............................................................................................ 19
2.1.3. Primitive types ............................................................................................... 20
2.1.4. The scope of a variable ................................................................................. 21
2.1.5. Naming rules ................................................................................................. 22
2.1.6. Reserved Keywords ...................................................................................... 23
2.1.7. Escape Sequences ....................................................................................... 24
2.1.8. null................................................................................................................. 24
2.2. Operators .............................................................................................................24
2.2.1. Arithmetic operators ...................................................................................... 25
2.2.2. Increment and Decrement operators............................................................. 25
2.2.3. Bitwise complement Operator: ...................................................................... 26
2.2.4. Widening .......................................................................................................26
2.2.5. Cast............................................................................................................... 28
2.2.6. Relational operators ...................................................................................... 28
2.2.7. Logical operators........................................................................................... 29
2.2.8. Bit manipulation operators............................................................................. 29
2.2.9. Shift operators << >> >>> ............................................................................. 30
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
4/198
2.2.10. Assignment operators ................................................................................... 30
2.2.11. Instanceof operator ....................................................................................... 31
2.2.12. Conditional operator ...................................................................................... 31
2.2.13. String of characters, concatenation operand (+) ........................................... 31
2.2.14. Operators precedence................................................................................... 31
2.2.15. Comment....................................................................................................... 31
Exercises2: Variables, operators..................................................................................... 33
3. Java Programming Grammar basics (II) <Day2> ........................................................ 35
3.1. Flow Control .........................................................................................................35
3.1.1. if, elseif and else statements ......................................................................... 35
3.1.2. switch statement............................................................................................ 36
3.1.3. for loop .......................................................................................................... 37
3.1.4. while loop ...................................................................................................... 41
3.1.5. do loop .......................................................................................................... 42
3.1.6. Branching Statements ................................................................................... 42
3.2. Exception; try{...} catch {...} finally {...} block......................................................... 44
3.2.1. Try, catch block ............................................................................................. 44
3.2.2. throws............................................................................................................ 45
3.2.3. Throwing exception ....................................................................................... 46
3.3. Array.....................................................................................................................46
3.3.1. Characteristics of array ................................................................................. 46
3.3.2. Declaration of array ....................................................................................... 47
3.3.3. Array creation ................................................................................................ 47
3.3.4. Initialization primitive types............................................................................ 47
3.3.5. Initialization of object type ............................................................................. 48
3.4. Useful packages ................................................................................................... 48
3.4.1. String class.................................................................................................... 48
3.4.2. Wrappers....................................................................................................... 49
3.4.3. Collection ...................................................................................................... 50
3.4.4. Date............................................................................................................... 54
Exercises3: Flow control, Arrays and Useful packages................................................... 59
4. Class and Object <Day3-1>......................................................................................... 62
4.1. What is an object? ................................................................................................ 62
4.2. Class .................................................................................................................... 62
4.2.1. Class declaration........................................................................................... 62
4.2.2. Package ........................................................................................................ 64
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
5/198
4.2.3. Instance......................................................................................................... 65
4.2.4. Constructor.................................................................................................... 67
4.2.5. Overloading ................................................................................................... 68
4.2.6. Inheritance .................................................................................................... 68
4.2.7. Abstract class ................................................................................................ 69
4.2.8. Interface ........................................................................................................70
4.2.9. Overriding...................................................................................................... 72
4.2.10. static variable ................................................................................................ 73
4.2.11. Polymorphism................................................................................................ 73
Exercise 4: Class programming ...................................................................................... 75
5. Thread <Day3-2> ..................................................................................................... 79
5.1. Thread Concept.................................................................................................... 79
5.2. Thread programming ............................................................................................ 81
5.2.1. Thread creation. ............................................................................................ 81
5.2.2. Thread creation inheriting from Thread class. ............................................... 81
5.2.3. Thread creation implementing the Runnable interface .................................. 82
5.2.4. Life cycle of a thread. .................................................................................... 83
5.2.5. Call a new thread .......................................................................................... 84
5.2.6. To temporally stop a Thread: Not Runnable .............................................. 84
5.2.7. Synchronization............................................................................................. 86
5.2.8. TimerTask ....................................................... Error! Bookmark not defined.
Exercise 5: Thread ..........................................................................................................89
6. Input and Output Stream <Day4-1>............................................................................. 90
6.1. Input and Output of Data ...................................................................................... 90
6.1.1. Stream...........................................................................................................90
6.1.2. java.io package ............................................................................................. 90
6.2. Standard input and output (keyboard and screen) ............................................... 95
6.2.1. Write to console............................................................................................. 95
6.2.2. Read from console ........................................................................................ 95
6.3. Reading a file .......................................................................................................97
6.3.1. Byte code file................................................................................................. 97
6.3.2. Text file.......................................................................................................... 97
6.3.3. BufferedReader ............................................................................................. 98
6.4. Writing to a file...................................................................................................... 98
6.4.1. Byte code file................................................................................................. 98
6.4.2. Text file.......................................................................................................... 99
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
6/198
6.4.3. BufferedWriter ............................................................................................... 99
6.4.4. PrintWriter .....................................................................................................99
6.5. File class ............................................................................................................ 100
Exercise 6: I/O programming......................................................................................... 102
7. Network <Day4-2>..................................................................................................... 103
7.1. TCP/IP................................................................................................................ 103
7.1.1. Basic of TCP/IP ........................................................................................... 103
7.1.2. TCP/IP Layer Model .................................................................................... 103
7.1.3. IP Address................................................................................................... 104
7.1.4. Subnet Masks.............................................................................................. 104
7.2. Network programming with Java ........................................................................ 104
7.2.1. Internet resources ....................................................................................... 105
7.2.2. URL resources ............................................................................................ 105
7.2.3. Client and Server program .......................................................................... 106
Exercise 7: Network Programming................................................................................ 111
8. Nested Classes <Day 5-1>........................................................................................ 114
8.1. Nested Classes .................................................................................................. 114
8.1.1. Top level class............................................................................................. 115
8.1.2. Nested class................................................................................................ 115
8.1.3. Non static member class ............................................................................. 116
8.1.4. static nested class ....................................................................................... 117
8.1.5. Local inner class.......................................................................................... 119
8.1.6. anonymous inner class................................................................................ 121
Exercise 8 Nested Classes ........................................................................................... 124
9. J2SE5.0 New features <Day 5-2> ............................................................................. 125
9.1. Generics ............................................................................................................. 126
9.2. For each sentence.............................................................................................. 130
9.2.1. What's new.................................................................................................. 130
9.2.2. Which object is target of For each ............................................................... 132
9.3. Enum .................................................................................................................. 133
9.3.1. example of enum......................................................................................... 133
9.3.2. benefits of enum.......................................................................................... 134
9.3.3. example of enum with switch statement...................................................... 134
9.3.4. Example of enum with for statement ........................................................... 135
9.4. Boxing/unboxing ................................................................................................. 136
9.4.1. What's new.................................................................................................. 136
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
7/198
9.4.2. How to use .................................................................................................. 136
Exercise 9: J2SE5.0 New features................................................................................ 137
10. Java GUI (I) <Day 6> ............................................................................................. 140
10.1. AWT ................................................................................................................... 140
10.1.1. What is GUI ................................................................................................. 140
10.1.2. What is AWT ............................................................................................... 140
10.1.3. Sample programs ........................................................................................ 141
10.2. Swing.................................................................................................................. 149
10.2.1. What is Swing.............................................................................................. 149
10.2.2. Why another GUI in the same java?............................................................ 149
10.2.3. Sample programs of Swing ......................................................................... 150
10.2.4. Pluggable Look and Feel............................................................................. 155
Exercise 10: AWT and Swing........................................................................................ 161
11. Java GUI (II) <Day 7> ............................................................................................ 162
11.1. SWT with Eclipse................................................................................................ 162
11.1.1. What is SWT ............................................................................................... 162
11.1.2. Why SWT .................................................................................................... 162
11.1.3. How to install (Quoted From Eclipse SWT Manual) .................................... 165
11.1.4. HelloWorld SWT application........................................................................ 168
11.1.5. Sample program of SWT............................................................................. 171
11.2. Visual Editor ....................................................................................................... 177
11.2.1. What is Visual Editor ................................................................................... 177
11.2.2. How to download and install VE .................................................................. 177
11.2.3. How to create project .................................................................................. 179
11.2.4. How to create a Visual Editor class ............................................................. 183
Exercise 11: Practice Programming Java GUI with SWT .............................................. 190
Tables and Figures ........................................................................................................... 195
Figures .......................................................................................................................... 195
Tables ........................................................................................................................... 195
Indexes ............................................................................................................................. 196
Keywords ...................................................................................................................... 196
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
8/198
Fundamental Programming (Java Basic)
Concept of Java Language <Day1-1>
Characteristic of Java Language
Object oriented language is compared with procedural language such as C, Basic, Fortran,
and Cobol. A procedural program is written as a list of instructions, telling the computer,
what to do, e.g. open, read, close a file, send message, and display data to the screen. All
these instructions are executed line by line. Program units include the main (or program
block), subroutines, functions, procedures; modules or libraries. In object oriented program,
a program is not divided into the blocks for data area, subroutines or procedure but
everything (data and behaviors) is encapsulated in objects. Each block (or object)
maintains its state in one or more variables. An object implements its behavior with
methods. In other words, a method is a function (subroutine) associated with an object.
code” that runs anywhere the JVM(Java Virtual Machine) is installed. What you need is to
install platform specific JVM downloading from Sun Microsystems site, but you do NOT
need to make platform-specific program any more, nor need to compile again in the other
platform. Just compile on your environment and the byte code runs in any environment
under JVM. That is “Write once, run anywhere.”
package ictti;
public class
HelloWorld { Machine
public static Code
main (String Byte Hello
arg[]){ Compile Code JVM BBHGWOE World
IL_000 KK33KCM,
System.out.pri 0: Idstr CX/FR
ntln("HelloWor ………….
ld") }
} Compile phase Execution phase
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
10/198
Fundamental Programming (Java Basic)
Concept of Java Language <Day1-1>
Getting started with “HelloWorld” program
If you are using Suse10 and you can use YaST Control Center, you can download from
YaST installation source.
1) Start YaST Control Centre
2) Select "Software" -> "Software Management"
3) Write "JAVA" in the search and check "java-1_5_0sun-devel".
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
11/198
Fundamental Programming (Java Basic)
Concept of Java Language <Day1-1>
Getting started with “HelloWorld” program
z Development tools: Development tools in bin directory are executable program files
that can be used for development, e.g. “javac” (compiler) or “java” (execute class files).
They are installed in JAVA_HOME/bin directory.
z Class libraries: Class libraries are libraries where various useful functions are stored,
e.g. network, tcp/ip, mail, GUI, etc. They are installed in JAVA_HOME/lib.
You can also check which version of Java is used by the following command;
java -version
JDK stands for Java Developmet Kit that includes necessary packages for development
Java programs, including javac compiler which convers the source code to Java Byte code.
JDK also includes the JRE of Runtime environment.
JRE stands for Java Runtime Environment that includes necessary packages for running
Java applications.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
12/198
Fundamental Programming (Java Basic)
Concept of Java Language <Day1-1>
Getting started with “HelloWorld” program
/*
* This is a Hello World program, the first program in our class.
*/
public class HelloWorld {
/**
* @param args
*/
public static void main (String[] args) {
System.out.println("Hello World");
}
}
Create the above program with some editor (like vi editor) and save the file named
“HelloWorld.java”.
Be careful that Java is case sensitive.
Source file always should have extension “.java”.
Usually the class name starts with capital letter followed by lower case. On the other hand
the method name starts with lower case.
z {} (braces)
A block can start with a block label and they are delimited by braces ({}). All the action
in Java happens between the context of a block, or multiple blocks. A block can hold
sentences or other blocks and the execution of the instructions inside them is
sequential, starting from the first line of the block. In our example we have 2 blocks,
one inside another. When we define a block, we are also defining a context or scope
where the action takes place and the definitions are valid.
z main method
In Java, a program is processed from “main()” method. Method is like a function or
subroutine in procedural programs. The main method has “String[] args” a variable,
that is defined as a parameter of the main method. String[] is array of strings and args
has one command line parameter in each position of its index, that is, args[0] has the
first parameter, args[1] the second one, and so on.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
13/198
Fundamental Programming (Java Basic)
Concept of Java Language <Day1-1>
Getting started with “HelloWorld” program
- “public” means that the class is accessible from any other classes.
- “static” is a class attribute and means that it is a method on the class rather than on
instances of the class.
- “void” means that there is no return from this class.
It is recommendable that you write a program with adequate indent to be clear and
clean although spaces or indent are flexible without any rule.
z System.out.println() method
Statement is an instruction unit and at the end of statement you should end with “;”.
System.out.println() is a message of printout to Standard output (usually console window).
println() means to print out the data inside the parenthesis and terminate the current line
by writing the line separator string.
z package ictti
Package is a way of grouping classes. In the example the class HelloWorld is grouped
into the package named “ictti”.
z Comment area
Comment is expressed as follows;
- // This is comment for only one line
- /* This is also comment line
- You can write more than one line */
- /** This is a comment for Java Doc*/
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
14/198
Fundamental Programming (Java Basic)
Concept of Java Language <Day1-1>
Getting started with “HelloWorld” program
"-d" parameter indicates the destination of the class file. You need to have a right to
create a new directory, since the compiler creates automatically the directory for package.
if the file path of JAVA_HOME/bin is set, you can directly call “javac” compiler, otherwise
type the entire directory name of JAVA_HOME, e.g.
/usr/lib/jvm/java/bin/javac –d ./ HelloWorld.java
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
15/198
Fundamental Programming (Java Basic)
Concept of Java Language <Day1-1>
Getting started with “HelloWorld” program
If your environment does not have path for java directory, you need to specify the entire
directory name where your jvm is located, such as;
/usr/lib/jvm/java/bin/java –classpath ./ ictti.HelloWorld
“–classpath” indicates JVM to the class path directories to search files. It is different
from file path that indicates to operating system. Class path is not used by operating
system but by JVM(Java Vertial Machine). “./” means current directory. Therefore,
“-classpath ./” shows that the current directory will be included to the class path so that JVM
can search “ictti.HelloWorld.class” with package name from the current directory. If the
classpath is not specified correctly, the java command can not look for the class file and
generates "NoClassDefFoundError".
You do NOT need to write “.class” extension. Just write the file name without extension.
Let’s see how we can create and execute a program using Eclipse in the exercise.
[Tips of Eclipse]
z If you save the source file, automatically the source code is compiled. The compile
error will be displayed in the Problems view.
z If you put the cursor over some object, te javadoc will be displayed shortly.
z PF4 will show you the hierarchy of the type.
z By Ctrl + space the code assist works to complete the name of the class or variables.
z You can set the JavaDoc location right clicking the rt.jar, so that in the javadoc view
appears more detail javadoc specification.
z By "Ctrl + Shift + f", the source code will be formatted.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
16/198
Fundamental Programming (Java Basic)
Concept of Java Language <Day1-1>
Getting started with “HelloWorld” program
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
17/198
Fundamental Programming (Java Basic)
Concept of Java Language <Day1-1>
Exercise 1: HelloWorld
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
18/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (I) <Day1-2>
Variable data
A = 5;
B = 34.09;
Lisa = "is a great programmer!";
Flag = true;
As we can see, a variable can hold different kind of information, numbers, strings, etc.
Because of this diversity, we need to specify the type of the variable. This specification of
types is called declaration. In a declaration we introduce the variables and its types.
class VariableExample {
public static void main (String[] args){
int X; // Declaration of the variable and its type
(integer)
X = 5; // Assignation of a value
System.out.print(X); // Print the value of X
}
}
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
19/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (I) <Day1-2>
Variable data
note
1. The boolean type is not a numerical value. It just admits true or false values. The
boolean type does not identify with the equal or distinct of zero, like in C/C++. The result of
the logical expression that appears as condition in a loop bifurcation must be boolean. The
default is false.
2. The char type contains characters in UNICODE, and it takes 16 bits for character.
It includes the characters of practically all the languages.
char c1 = '\u0057'; // character W is inserted.
char c2 = 'W';
char c3 = (char)87; // character W is inserted. Integer is converted
to character.
char c4 = '\r'; // carriage return is inserted.
3. The type byte, short, int and long are all numbers that can be positive or
negative, with different maximum and minimum values. Unlike C/C++, in Java there aren't
unsigned values.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
20/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (I) <Day1-2>
Variable data
4. The "L" is appended to each number for the long type, so that Java can
differentiate between of 32-bit int type and 64-bit long type.
-20L
123456L
5. The float and double types are values of floating point (real numbers). Whenever
a floating point number is specified, it is automatically considered as double. It is always
important to add the "F" to the end of any floating point number.
float wrong = 555.66; // Compile error
float correct = 555.66F // Works as float
6. The word void is used to indicate the absence of a determined type of variable
that is used as return value in a method declaration.
7. Unlike C/C++, the variable types in Java are perfectly defined in all and each one
of the possible platforms. For example, int always takes the same memory and has the
same range of values, in any kind of computer.
[ScopeTest1.java]
class ScopeTest1 {
public static void main (String[] args){
int i=1;
/* This is a new Block */
{
int j=5;
int k=i; /* This is right since the block is contained
inside */
/* the block where i is defined */
System.out.println(j);
System.out.println(k);
}
System.out.println(j); /* Wrong! j is not defined in this
block */
}
}
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
21/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (I) <Day1-2>
Variable data
If we avoid the last println, and compile the previous program we will see 5 and 1 (in
different lines) as output. Note that we used the variable “i” inside another block, but
because it is between the contexts of the main block the definition is still valid. There is also
an example of erroneous use of variable scope in the last line, when we try to use “j”
outside the scope of the block where it is defined. Here is another example of wrong scope
declaration:
[ScopeTest2.java]
class scopeTest2 {
public static void main (String[] args) {
int i=1;
/* This is a new Block */
{
int i;
{
int i; /* Wrong! */
int k;
System.out.print("TEST!");
}
}
}
}
This is a sample defining a variable that is already defined in the scope in the previous
block,
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
22/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (I) <Day1-2>
Variable data
CaMeL // valid
11thVariable // invalid
z It's important to mention that all the identifiers are case sensitive, so the variable “foo”
is not the same as “Foo”.
z It's a very common practice (but not an obligation) to use a naming convention when
working in projects. This is an aid for maintaining a standard among all of the
programmers, avoiding mistakes and improving the clarity of the code. Choose
meaningful names that describe what the variable is being used for. Avoid generic
names like number or temp whose purpose is unclear. Compose variable names using
mixed case letters starting with a lower case letter. For example, use systemPreassure
or databaseConnection.
z Class names usually start with a capital letter, with embedded words capitalized, e.g.,
TableManager, use plural names for arrays, e.g., use testScores instead of testScore.
z The first letter should be alphabet letter, “$” or “_”.
Reserved Keywords
abstract boolean break byte case cast
catch char class const(not used) continue default
do
double else extends final finally float for
future(not used) generic(not used) goto(not used) if implements
import inner instanceof int interface long native new
null operator(not used) outer(not used) package private protected
public rest return short static super switch
synchronized this
throw throws transient try var(not used) void
volatile
while
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
23/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (I) <Day1-2>
Operators
2.1.8. null
“null” is a value that is used to initialization of reference of object. When an object is
declared, “null” is assigned. If you want to initialize an object, you can also assign null to
the object.
Object object; // object is null
object = null; // object is initialized
NullPointerException occurs when an object that is not instantiated with "new" keyword
is referred in a program.
2.2. Operators
It's a very useful for programmers to have operators to express arithmetic expressions and
relations between variables and constants. Java provides us with a complete set of
operators that we can group into the following kinds: arithmetic, relational, conditional, shift,
logical, assignment and others.
Table 3 operators
Precedence Type of operators Operators
1 postfix operators expr++ expr--
1 prefix operators ++expr --expr +expr -expr ! ~
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
24/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (I) <Day1-2>
Operators
As we can see it is a standard mathematical infix notation, where each operator “+”,”-“, “*”,
“/”, “%” is equivalent of sum, subtraction, multiplication, divide and modulus.
The following table summarizes the arithmetic operators:
1) Preceding the variable (for example: ++i). In this case first the variable is
incremented and then it is set to the expression.
x=++i; i = i + 1;
x=i;
2) Following the variable (for example: i++). In this case first the variable is set to the
expression (with the previous value) and then it is increased.
x=i++; x=i;
i = i + 1;
2.2.4. Widening
Computer arithmetic is not the same as real mathematical arithmetic: In Java just like in
almost every computer language, all the operations are performed in computer arithmetic.
This means that the result depends on the types of the operands. Let see an example:
in the real world
5 / 9= 0.555...
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
26/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (I) <Day1-2>
Operators
in Java
5 / 9 = 0 !!!
How is this possible? Well, java assumes that 5 and 9 to be integer values, so the data type
of the division must be integer, when the division is calculated it converts the result to
integer, 0.555, which is truncated to 0.
If we like to have the exact result, we must code it in the following way
5.0 / 9.0
now Java assumes the result must by double and the calculation isn't truncated any more.
"The type of the result and the result itself depends on the type of the operands."
[OperatorsDemo.java]
public class OperatorsDemo {
public static void main (String[] args) {
int a = 20;
int b = 17;
double x = 18.23;
double y = 15.17;
System.out.println("a + b = " + (a + b) );
System.out.println("x + y = " + (x + y) );
System.out.println("a * x = " + (a * x) );
System.out.println("b / y = " + (b / y) );
}
}
In “a * x” and “b / x” we mixed variables of different types. Before the calculation is done the
operands applies widening promoting to the "less restrictive type", in this case “a” and “b”
are converted to double, and then the calculation is performed.
This is a very important concept to understand because it can save a lot of time debugging
errors in calculations.
Java deduces the data type of the expression from the type of the operands using a few
simple rules summarized in the following table.
Table 6 Widening
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
27/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (I) <Day1-2>
Operators
The widening is implicit conversion that can be safely performed without any loss of
information. It is realized as follows in order;
byte->short->int->long->float->double
2.2.5. Cast
Cast is to explicitly convert primitive type to lower level, e.g. from long to int.
long lnumber = 9223372036854775807L;
int inum = (int) lnumber;
Cast may cause overflow or lost of information.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
28/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (I) <Day1-2>
Operators
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
29/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (I) <Day1-2>
Operators
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
30/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (I) <Day1-2>
Operators
The booleanExpression is evaluated and gives back res1 if the result is true and res2 if the
result is false. It is the only ternary operator (three arguments) of Java. Like all operators
who give back a value, icttian be used in an expression. For example the sentences
x=1;
y=10;
z = (x<y)? x+3: y+8;
will assign to z the value 4, that is x+3.
The concatenation operand is used twice to construct the chain of characters that is
desired to print by means of the println() method. The result of the numerical variable is
converted automatically by Java in a chain of characters to be able to concatenate it.
2.2.15. Comment
There are two ways to express comment in Java; slashes (//) in the beginning of a line code
is considered as comment. The second form is to include comment between the symbols /*
and */. This second method is used when the comment extends from a single line. For
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
31/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (I) <Day1-2>
Operators
example:
// This line is a comment
In Java using /**...*/ will automatically generate the documentation of the classes and
packages developed by the programmer called JavaDoc. Once introduced this type of
comments, the program javadoc.exe (included in the JDK) will generate the documentation
of a similar way to the one presented in the JDK documentation. The syntax of these
comments and the form to use the program javadoc.exe can be found in the Javadoc tool .
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
32/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (I) <Day1-2>
Exercises2: Variables, operators
1. Test in your computer what will happen with the following code. Why?
[TestVar1.java]
class TestVar1{
public static void main (String[] args){
int a = 10;
int b = 15;
{
int a = 13;
b = 10;
System.out.println("The value of a and b are " + a + " " +
b);
}
}
}
2. Test in your computer what will happen with the following code. Why?
[ScopeTest.java]
public class ScopeTest {
public static void main(String[] args) {
int i=1;
{
int j=5;
int k=i;
System.out.println(j);
System.out.println(k);
}
System.out.println(j);
}
}
3. Write a program "TestIncrement.java" to see increment operator. First declare int value
“i” and “iInc”. Set any integer to variable “i”. Perform “iInc = i++;”. Print out the content of
variables “iInc” and “i”. Test also “iInc = ++i;”. Compare both results.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
33/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (I) <Day1-2>
Exercises2: Variables, operators
int c = (int)x;
System.out.println("c = " + c);
}
}
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
34/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (II) <Day2>
Flow Control
The Flow Control allows you to execute one of several actions based on the value of a
logical or relational expression. They are very important structures since they're the ones in
charge of control the flow of the program.
if ( condition ) {
/* Instructions to execute if condition is true */
}
If the condition evaluates to true, then the code inside the braces is executed. If the
condition is false, it is omitted. Sometimes it is needed to execute some instructions if
certain condition is true and others if it is false. We use if/else statements for this.
if ( condition ) {
/* Instructions to execute if condition is true */
} else {
/* Instructions to execute if condition is false */
}
It checks if there is a parameter passed from console at runtime. It verifies that there is at
least one element in args[]. If the condition is false it means that there are no parameters,
we print a message requiring to the user to specify a parameter.
switch (variable) {
case value1: statements1; break;
case value2: statements2; break;
case value3: statements3; break;
case value4: statements4; break;
case value5: statements5; break;
case value6: statements6; break;
[default: statements7;]
}
2) The values not included in any sentence can be managed in the default section, which
is optional.
3) In case of the absence of break, it executes all the case until a break is reached or until
switch finishes.
default:
System.out.println(" it's a consonant.");
}
[GrammerFor.java]
class GrammarFor {
public static void main (String[] args) {
int x = Integer.parseInt(args[0]);
int i;
for (i=0; i<=x; i++) {
System.out.println(i);
}
}
}
When Java program is executed from command line, parameters can be set to pass to the
program separated by space in the following format.
java program_name arg_0 arg_1 arg_2 …
The command line parameters are stored to args[] array in a program.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
37/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (II) <Day2>
Flow Control
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
38/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (II) <Day2>
Flow Control
The following code converts the first command line parameter from String to int and
assigns it to “x”. The “for” sentence is the iterator itself and it has the following structure:
int x = Integer.parseInt(args[0]);
In our example we initialize the “i” variable to 0. The for will iterate until the loop condition is
false, and each step will perform the increment specified of the variable in the step, in this
case i++, that means increment “i” in 1.
There is another way of using “for” loop. There is no need of specifying an initialization,
loop condition or incrementor. If there is no condition, it is assumed true by default. If we
wish an infinite loop of instructions we can use “for” loop like:
for(;;) {
// code_block;
}
This will loop code_block forever. The break statement can be employed when it meets
some condition.
[GrammarFor1.java]
class GrammarFor1 {
public static void main (String[] args) {
if (args.length > 0) {
int x = Integer.parseInt(args[0]);
int i = 0;
for (;;){
if(i<=x){
System.out.println(i);
i++;
} else {
break;
}
}
} else {
System.out.println("You must specify a number in the
command line.");
}
}
}
This program behaves similarly as the previous example but the initialization is done before
the for loop, and the condition is tested inside an if/else statement. In the case it is false, it
executes the break and exits the loop.
Note that now the program checks if there is a parameter argument specified from the
command line.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
40/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (II) <Day2>
Flow Control
If we want to exit the while loop anywhere inside the code_block we can use the break
statement.
[GrammarWhile.java]
class GrammarWhile {
public static void main (String[] args) {
if (args.length > 0) {
int x = 0;
try{
x = Integer.parseInt(args[0]);
}catch (Exception e){
System.out.println("You must specify a number in
the command line.");
}
int i = 0;
while (i<=x) {
System.out.println(i);
i++;
}
} else {
System.out.println("You must specify a number in the
command line.");
}
}
}
Note that now try catch statement is inserted to check if the passed parameter argument
is other than number to process Exeption.
From the last two examples we can conclude that there is equivalence between for and
while. All the iterations we may write using for can be written using while statement or for
and vice versa. It is up to the programmer to choose which is better. We can say that the
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
41/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (II) <Day2>
Flow Control
for loop is better for "indexed" or fixed iterations where we need a counter, while loops are
better for iterations where the amounts of repetitions of the code_block depends on the
external conditions or user interaction.
3.1.5. do loop
“do” loop is quite similar as “while” loop except code block is performed at least once
before logical check of condition.
do {
// code_block
}while (condition)
[GrammarDo.java]
class GrammarDo {
public static void main (String[] args) {
if (args.length > 0) {
int x = Integer.parseInt(args[0]);
int i = 0;
do {
System.out.println(i);
i++;
} while (i<=x);
} else {
System.out.println("You must specify a number in the
command line.");
}
}
}
z Break
The break statement terminates the enclosing switch, for, while, do-while statements, and
Flow Control moves to the end of flow.
[BreakDemo.java]
public class BreakDemo {
public static void main (String[] args) {
int i = 0;
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
42/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (II) <Day2>
Flow Control
boolean bl = true;
while (bl) {
if (i==5) {
break; //Finish while loop when i equals with
5
}
System.out.println(i);
i++;
}
}
}
z Continue
The continue statement behaves similarly to break, but instead of terminating the execution
of the loop, it just terminates the execution of the current iteration, skipping the remainder
of the loop iteration and go back to the loop.
[ContinueDemo.java]
public class ContinueDemo {
public static void main (String[] args) {
int i =0;
while (i<=8 ) {
if (i==0) {
i++;
continue; //if i equals with 0, i is not printed.
}
System.out.println(10/i)
i++;
}
}
}
z Return
You can use return to exit from the current method. To return a value, simply put the value
(or an expression that calculates the value) after the return keyword:
return ++counter;
return i;
The data type of the value returned by return must match the type of the method's
declaration. When a method is declared void, you do not have to specify return.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
43/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (II) <Day2>
Exception; try{...} catch {...} finally {...} block
Java incorporates the management of errors in the own language. The best moment to
detect the errors is during the compilation. Nevertheless only the syntax errors are detected
in this operation. The rest of the problems arise during the execution of the programs.
In the Java language, an exception is a certain type of error or an abnormal condition that
has taken place during the execution of a program. Some exceptions are fatal and cause
that the execution of the program should be finalized. Upon fatal cases a program finishes
giving a message about the type of error that has taken place. Other exceptions such as
file not found which you want to read or write can be recoverable. In this case the program
must
give to the user the opportunity to correct the error (e.g. defining a new path instead).
The errors are represented through classes derived from the Throwable class, but those
that a programmer has to check derives from Exception (java.lang.exception that derives
as well from Throwable). The exception is described in the try, catch and finally blocks.
void method1() {
try {
// Code that can throw
//IOException and MyException exceptions
} catch (IOException e1) {
// It handles IOException by just displaying a message
System.out.println(e1.getMessage());
} catch (MyException e2) {
// It handles MyException giving a message and ending the
function.
System.out.println(e2.getMessage()); return;
} finally {
// Sentences that will execute in any case.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
44/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (II) <Day2>
Exception; try{...} catch {...} finally {...} block
}
} // End of method1
3.2.2. throws
In the case a program prefers not managing error exception inside the method, it is
necessary that the system passes the exception to the method from which it has been
called. This is done by means of the keyword throws followed by the name of the
exception after the list of arguments of the method. The superior method will have to
include the try/catch blocks or to pass the exception as well. This way it is possible to pass
the exception from a method to another until the last method of the program is reached,
that is, the main () method.
[example of printStackTrace ]
java.lang.ArrayIndexOutOfBoundsException: 3
at Primitive.main(MyException.java:40)
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
45/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (II) <Day2>
Array
3.3. Array
We have learned about variables that store values temporally in the memory. But if there
are thousand of data you want to manage, by this way you have to declare the same
number(thousands) of valuables that is almost impossible. Array is a way to manage values
of the same type with index (number) instead of naming one by one, so that declaring only
array name you can manage thousands of data by index.
Figure 6 Array
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
46/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (II) <Day2>
Array
type if the array is declared as int. You can not mix int, double, long or String in the
same array.
z An array is associated with “length” to see the array size, e.g.
Array_name.length
z If you get access to an index bigger or smaller than the declared array size,
IndexOutOfBoundsException occurs.
z Multidimensional array is accepted in Java.
z The elements of an array can be accessed with an index that varies from o to length-1.
z It is possible to create arrays of objects of any type. In principle an array of objects is
an array of references that are to be completed calling to the operator new.
z The array elements are initialized to the value by default of the corresponding type
(zero for numerical values, false for boolean, null for String and reference).
z Like all the objects, arrays are passed as arguments to the methods through reference.
[Example]
int counts[];
int[] counts[]; // same as int counts[];
String names[];
String[] names; // same as String names[];
Color[] myColor;
counts[0] = 1;
counts[1] = 2;
counts[2] = 3;
[Example code]
// create an array of 10 integers, that by default initialize to zero
int iArray[] = new int[10];
// create arrays initializing them with default values
int iArray1[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
// array of 5 objects
MyClass objList[] = new MyClass[5]; // right now there are 5 references
to null
for (i=0; i<5; i++)
objList[i] = new MyClass (...);
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
48/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (II) <Day2>
Useful packages
2) Compare
The logical operator “==” compares the reference of the object. Note that it does NOT
compare the contents of the object.
[?] Is it true of false in the following example?
String a1, a2;
boolean bl;
a1 = new String("Hello");
a2 = new String("Hello");
if (a1 == a2){
bl = true;
} else {
bl = false;
}
System.out.println(bl);
if (a1.equals(a2)){
bl = true;
}else{
bl = false;
}
System.out.println(bl);
3.4.2. Wrappers
The Wrapper class provides various functions for the primitive data. The wrapper class has
a lot of static method (you can use directly with the class name and method name without
instantiating the object).
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
49/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (II) <Day2>
Useful packages
z Integer
The Integer class is most used, especially for the conversion of data between String and
int.
int iCode = Integer.parseInt("12345"); //String -> int
Integer IntegerCode = Integer.valueOf("12345");// String -> Integer
3.4.3. Collection
To manage a collection of data there is a Collection Interface in the java.util package. The
main collection interfaces are Collection, List, Set, Map, Queue, SortedSet and SortedMap.
They are all included in java.util packages. There is quite big difference between Java 1.4
and Java1.5 function. The new feature of Java 1.5 is described in another chapter of this
textbook. Here we will see mainly the Java1.4 feature of collection.
z Collection
Collection is at the top of this hierarchy and includes the core methods add(),
clear(),iterator(), isEmpty(), remove(), size(), and toArray() as well as other less common
ones.
z List
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
50/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (II) <Day2>
Useful packages
The characteristic of this interface is guarantee of the order of data. Therefore all the
classes derived from their interface the order of the data are assured. AbstactList is an
abstract class that implements the List interface. List interface does not check the duplicate
date since it does not have the concept of key (so, duplicate data is OK).
z Map
This interface forces subclasses to associate key with value. Key should be identical (you
can not share the same key with other data). AbstractMap implements this interface.
z Iterator
Iterator is an interface that provides to move in fixed order within a collection. This is used
to refer data in a collection, especially from beginning to the end of data. This interface
provides the following methods.
z HashMap
This class derives from Map interface and quite frequently used.
[Characteristics of HashMap]
- Consists of key and value. Both should be object. You can not specify primitive type.
- The order of data is not guaranteed.
- permits null values and the null key.
- Note that when you get the value or key from HashMap, object type is returned (in Java
1.4). You have to cast to the adequate type.
String str = (String)hashmap_name.get(keyname)
[TestHashMapSample1.java]
/* TestHashMap */
import java.util.HashMap;
public class TestHashMapSample1{
public static void main (String[] args) {
// instantiate HashMap
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
51/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (II) <Day2>
Useful packages
// Set values
hashMap.put("Karaoke", "interesting");
hashMap.put("Study", "boring");
hashMap.put("Lunch", "delicious");
// Display hashMap
System.out.println("Display hashMap : " + hashMap);
// Get value
String str = (String)hashMap.get("Karaoke");
System.out.println("Get value of Karaoke is : " + str);
// Check key
if (hashMap.containsKey("Study")) {
System.out.println("ContainsKey: There is Study key");
}else{
System.out.println("ContainsKey: no Study key");
}
// Display hashMap
System.out.println("Display hashMap : " + hashMap);
}
}
[The results]
Display hashMap : {Lunch=delicious, Study=boring,
Karaoke=interesting}
Get value of Karaoke is : interesting
ContainsKey: There is Study key
Display hashMap : {Study=boring, Karaoke=interesting}
Note that the HashMap contents are displayed without order of insert data.
KeySet method of HashMap returns Set implementation containing keys of HashMap. Set
interface has iterator() method to returns an Iterator over the elements in this set. The
following code shows how to get all the keys and values in the HashMap,
hm.put("Police","199");
hm.put("Fire","191");
Iterator it = hm.keySet().iterator();
while(it.hasNext()){
String strKey = (String)it.next();
String strValue = (String)hm.get(strKey);
System.out.println(strKey + "," + strValue);
}
z ArrayList
This class derives from List interface.
[Characteristics of ArrayList]
- ArrayList extends AbstructList interface.
- Represents an array of objects that can resize (grow and reduce) dynamically according
to the number of elements.
- It allows acceding to the elements with an index.
- It keeps the order of the stored data.
[TestArrayListSample1.java]
/* TestArrayList */
import java.util.ArrayList;
// Set values
arrayList.add("Star cola");
arrayList.add("Myanmar beer");
arrayList.add("Alpin");
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
53/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (II) <Day2>
Useful packages
// Add element
String str = "Fantasy";
arrayList.add(1, str);
System.out.println("ArrayList content after addition : " +
arrayList);
// remove element
arrayList.remove(0);
System.out.println("ArrayList content after deletion: " +
arrayList);
// Get element
System.out.println("Get element : " + arrayList.get(2));
// Delete all
arrayList.clear();
System.out.println("Delete all : " + arrayList);
// isEmpty
if (arrayList.isEmpty()) {
System.out.println("is Empty ");
} else {
System.out.println("is not Empty");
}
}
}
[The result]
ArrayList contents: [Star cola, Myanmar beer, Alpin]
ArrayList content after addition : [Star cola, Fantasy, Myanmar beer,
Alpin]
ArrayList content after deletion: [Fantasy, Myanmar beer, Alpin]
Get element : Alpin
data size : 3
Delete all : []
is Empty
Note that the order of the data is guaranteed by its inserted order.
3.4.4. Date
Java has quite rich class libraries related to the dates;
- java.util.Date
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
54/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (II) <Day2>
Useful packages
- java.util.Calendar
- java util.GregorianCalendar.
- java.text.DateFormat
- java.text.SinpleDateFormat
There are several time and calendar related terminologies used in Java Packege.
Table 11 - Time standard
Time Concept
UTC (Coordinated Universal Time) a high-precision atomic time standard.
GMT (Greenwich Mean Time) means solar time at the Royal Observatory, Greenwich in
England. This is a time standard based on the earth's
angular rotation, rather than a uniform passage of seconds.
epoch The epoch serves as a reference point from which time is
measured. In Java Jan.1 1970 is employed.
Gregorian Calendar The most widely used calendar in the world and a
modification of the Julian calendar.
The last day of the Julian calendar was Thursday 4 October
1582 and this was followed by the first day of the Gregorian
calendar, Friday 15 October 1582.
Leap years system is included which are all years divisible by
4, with the exception of those divisible by 100, but not by 400.
Julian Calendar Introduced in 46 BC by Julius Caesar. It has a regular year of
365 days divided into 12 months, and a leap day is added to
February every four years.
Locale a set of parameters that defines the user's language, country
and any special variant preferences that the user wants to
see in their user interface. Language, number format, date,
currency depend on the Locale.
(Reference to Wikipedia)
z Date class
The Date class is helpful when some specified date is shown although the mayor part of
Date class is already deprecated and recommended to use Calender class which is more
precise in expressing dates. The Date class has some methods to compare two dates.
- after()
- before()
- compareTo()
- equals()
-
[DateExample.java]
import java.util.Date;
public class DateExample {
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
55/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (II) <Day2>
Useful packages
[results]
date1 is after date2? false
date1 is before date2? true
date1 is same as date2? false
date1 is after date2? -1
date2 is after date1? 1
The after() or before() method returns true or false. The compareTo() method returns
the value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is
before the Date argument; and a value greater than 0 if this Date is after the Date
argument.
z Calendar class
The Calendar class is an abstract class that provides methods for manipulating the
calendar fields, such as getting the date of the next week. It also converts between a
specific instant in time and a set of calendar fields such as YEAR, MONTH,
DAY_OF_MONTH, HOUR.
[CalendarExample.java]
import java.util.Calendar;
public class CalendarExample {
public static void main(String[] args) {
Calendar c1 = Calendar.getInstance();
Object obj = Calendar.getInstance().getClass();
System.out.println("Calendar Instance;" + c1);
System.out.println("Calendar getClass;" + obj);
System.out.println("Show date; " + c1.get(Calendar.YEAR) +
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
56/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (II) <Day2>
Useful packages
"/" + c1.get(Calendar.MONTH) +
"/" + c1.get(Calendar.DATE));
}
}
[results]
Calendar
Instance;java.util.GregorianCalendar[time=1172978298260,areFields
Set=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar
.ZoneInfo[id="Asia/Tokyo",offset=32400000,dstSavings=0,useDayligh
t=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDays
InFirstWeek=1,ERA=1,YEAR=2007,MONTH=2,WEEK_OF_YEAR=10,WEEK_OF_MON
TH=2,DAY_OF_MONTH=4,DAY_OF_YEAR=63,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_M
ONTH=1,AM_PM=1,HOUR=0,HOUR_OF_DAY=12,MINUTE=18,SECOND=18,MILLISEC
OND=260,ZONE_OFFSET=32400000,DST_OFFSET=0]
Calendar getClass;class java.util.GregorianCalendar
Show date; 2007/2/4
Since the Calenda class is an abstract class, it can not be instantiated but by way of
getInstance() method, the object is created, getting back the GregorianCalendar
implemented object.
z SimpleDateFormat class
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive
manner. It allows for formatting (date -> text), parsing (text -> date), and normalization. In
the JavaDoc specification, you can check how the date and time patterns are. For example,
using a pattern of "MM/dd/yy" and a SimpleDateFormat instance creates the date
"03/04/07".
[SimpleDateFormatExample.java]
import java.text.SimpleDateFormat;
import java.util.Date;
class SimpleDateFormatExample {
public static void main(String[] args) {
Date date1 = new Date();
// Create SimpleDateFormat
SimpleDateFormat sdf1 = new SimpleDateFormat("'year'yyyy'
month'MM' day'dd");
System.out.println(sdf1.format(date1));
// Change pattern
sdf1.applyPattern("yyyy/MM/dd");
System.out.println(sdf1.format(date1));
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
57/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (II) <Day2>
Useful packages
}
}
[results]
year2007 month03 day04
2007/03/04
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
58/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (II) <Day2>
Exercises3: Flow control, Arrays and Useful packages
(3) To check if it is not numerical, catch “NumberFormatException” and print error message,
e.g.
try{
(4) Write loop statement that repeats printing message output for the number input by user,
e.g.
System.out.println("Loop index is " + i);
If you use Eclipse, you can set parameters from "Run" -> "Run As" -> "Arguments"
If you want to stop execution of the program, you can use:
System.exit(1);
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
59/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (II) <Day2>
Exercises3: Flow control, Arrays and Useful packages
2. Execute the following program to see false. Modify the program to be able to compare
the String object.
(2) Get the all value of the HashMap. You can use “keySet()” method getting the key parts
of the HashMap, or you can get the value specifying the key get(“key_name”); Try to use
Sun Microsystems Java API Specification to see how to use methods.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
60/198
Fundamental Programming (Java Basic)
Java Programming Grammar basics (II) <Day2>
Exercises3: Flow control, Arrays and Useful packages
menu table and print out all. You can use iterator() method to get Iterator.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
61/198
Fundamental Programming (Java Basic)
Class and Object <Day3-1>
What is an object?
An object is a representation of a real-life entity. All the “things” can be object. For example,
“television”, “car”, “airplane”, “PC”, “money”. These are physical object that you can see or
touch. Object has two components, “Property” and “Method”. An object is defined via its
class. In a class, you will define everything about an object, like its possible states and its
behavior. An object sends message to other object for interaction.
Property
Property is an attribute about the object,. e.g. properties of a television are “channel”,
“volume”, “maker”, “size”, or “weight” and these are important data to identify and
characterize the television. Property can be considered as variables in a program.
Behavior (Method)
An object has not only attributes but also has behaviors, e.g. a television has behaviors
such as “change the channel” or “change the volume”.
Human being has behaviors such as “have lunch”, “walk”, “go to work”, “sleep”, etc. A
procedure or function of a program corresponds to a method.
Message
we need to take an action for an object to work. This action to invoke the behavior of the
object is called “send message or “message passing”, e.g. we take an action to accelerate
a car, to change the channel of the television. In a program send message is to call a
method of an object.
4.2. Class
4.2.1. Class declaration
A class is a template of an object, in other words, class is an abstract state while object is a
concrete entity by setting concrete properties.
class. The data associated with a class or object is stored in variables; the behavior
associated with a class or object is implemented with methods. Methods are similar to the
functions or procedures in procedural languages such as C.
from Sun Microsystems Tutorial ”Defining a Class”
A class in Java language is where source code is written and works as a template of the
object at runtime. The specification of a class has the following syntaxes;
[access modifier][class modifier] class class_name ["extends" object_name]
z Access modifier;
Access modifier indicates access level from other classes. One of “public”, “protected”,
“private” and default(not specified) is specified.
z Class modifier
- abstract
Indicates an abstract class that contains abstract method.
- final
A class can be declared final if its definition is complete and no subclasses are desired or
required.
- static
Indicates a static class. Static class is instantiated only once at the time of loading the
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
63/198
Fundamental Programming (Java Basic)
Class and Object <Day3-1>
Class
class.
static modifier is only available for inner class.
4.2.2. Package
In JAVA Language package is a kind of container to classify classes together, similar to the
concept of folders of files.
1) Purpose
A class is generally grouped into packages for the following purpose:
z To identify the name of class uniquely with package name in order not to have conflict
with other class of the same name. A class with correct package name can be referred
without any conflict in the world. For example;
- java.io.writer.FileWriter Sun Microsystems FileWriter class
- mm.ictti.io.FileWriter mm.ictti.io (private) package
z To be able for user to understand the main function of the class by grouping with
package name. Example of packages:
- database
- util
- network
- io
Package is used with domain name to be unique, e.g. if your domain name is jica.it.mm
and a class is related with database and class name is “DBAccess”, the entire name of
class with package name can be:
mm.it.jica.database.DBAccess
z Access control
Grouping a class into a package means to provide certain access control to the class. For
example, if a class A belongs to the same package with class B, specifying the protected or
default access modifier to the class A, it is accessible from B.,
[Example code]
package mm.ictti;
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
64/198
Fundamental Programming (Java Basic)
Class and Object <Day3-1>
Class
3) import statement
When you want to use classes of the other package in a program, you have to write
“import” statement, e.g.;
import java.io.Writer.FileWriter;
if you want to import multiple classes from a package, you can specify with asterisk (*);
import java.io.*
4.2.3. Instance
An object is a concrete identity of a class. In the program an object is created in the
memory in order to manage concrete data of the object. An object is created by copying
from a class that does not have concrete data yet. This creation of an object is called
instantiation. To use variables or methods of an object you need to instantiate a class. After
you get an instance of a class, you can call methods to request to do something.
z How to code
In Java you can create instances of a class using the keyword new.
Person person = new Person();
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
65/198
Fundamental Programming (Java Basic)
Class and Object <Day3-1>
Class
[access modifier]
The same access modifier explained in the class declaration.
[method modifier]
- final; indicates that the subclass can not override this method.
- abstract; indicates that method is declared without implementation.
- static; indicates that method is independent of the object but accessible to the
static variable
- synchronized; indicates that the method is locked while one object is accessing to this
method.
[return_type]
- void indicates that there is no data returned from this method.
- data type; indicates that the specified data type is returned from this method.
[Exception]
-throws; indicates that the method throws specified exception.
[parameter lists]
Set parameter lists as follows;
Data type parameter_name, data_type parameter_name,…
Method name with parameter lists are called method signature.
[Example code]
public class Person{
int iBaseSalary = 10000;
int calcSalary(int allowance){ // Declare a method
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
66/198
Fundamental Programming (Java Basic)
Class and Object <Day3-1>
Class
4.2.4. Constructor
A constructor is used in the creation of an object to set initial values to the object. When an
instance is created by “new” keyword, one constructor is called to allocate memory and
initialize variables. If the class does not have constructor, super class constructor is called.
Unless the class has super class, the constructor of object class, the top hierarchy of the
class will be called.
z Rules
- A constructor name should be the simple name of the class that contains the
constructor declaration.
- It is similar to the method but has not return type.
- Several constructors can be declared with different parameters. This is called
overloading.
- The superclass constructor can be called by super keyword.
- The keyword this is used to the object the method is called upon.
class MyClass {
int value;
MyClass (int value){
this.value = value;
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
67/198
Fundamental Programming (Java Basic)
Class and Object <Day3-1>
Class
}
}
4.2.5. Overloading
Overloaded methods are methods with the same name signature but either a different
number of parameters or different types in the parameter list. Although methods have the
same name, its behaviors are different setting different parameters. The caller program
selects one of overloaded methods to get the desired result.
z Why overloading?
This may be used to ease programmers work enabling to call various form of method. For
example, a caller program can call with int or String to get the result of calculation.
Overloaded methods are responsible to convert String to number format.
[Example code]
setValue(int i);
setValue(String str);
setValue(int I, String str);
4.2.6. Inheritance
z What is Inheritance?
Inheritance is a generalization of the objects. It has a relationship between classes where
one class is the parent class of another.
Inheritance provides and can be used as an is-a-kind-of (or is-a) relationship. For example
a dog is animal. In this case animal can be parent class and dog is subclass.
Another example, Copy machine is a machine. Computer is also a machine. So computer
is generalized as a concept of copy machine and computer.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
68/198
Fundamental Programming (Java Basic)
Class and Object <Day3-1>
Class
Super
Animal Machine
l
Sub classes
dog Copy machine Computer
Figure 7 Inheritance
The super class contains variables and methods common to all of the subclasses.
z How to code
Use “extends” keyword in subclass.
z How to code
Use “abstract” keyword for super class and methods you want to declare. In the subclasses
use “extends” keyword to implement the abstract class. You have to implement all the
methods that are declared as abstract in the super class.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
69/198
Fundamental Programming (Java Basic)
Class and Object <Day3-1>
Class
(note) You can not instantiate abstract class directly, e.g. the following code will cause
compile error.
Animal animal = new Animal(); //This causes a compile error.
4.2.8. Interface
Interface is an abstract type without any code associated with it and contains only a list of
methods. These methods do not have any functionality but force the programmer to define
them at the class which implements that interface. The difference between abstract and
interface is that abstract class contains non-abstract methods, while interface consists of all
abstract methods.
z How to code
Use “interface” key word for super class. In the interface you declare only the method
without functionality. In the subclasses, use “implements” keyword and implant the
functionality.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
70/198
Fundamental Programming (Java Basic)
Class and Object <Day3-1>
Class
[Why Interface?]
z Define the functions to be implemented in the subclass
Defining the method in an interface obligates the subclasses to have the same functions,
which is a kind of having the same programming style for good maintainability. If you add a
new class, you do not have to think how to design about functions but using interface
makes you know what kind of functions is required. This technique is widely used to divide
the tasks between those who design specifications and who implement the contents. For
example Database specifications are defined in the interface by the program language
(such as Sun Microsystem) vendor and the third parties (such as Postgre, Oracle, MSSQL,
MySQL, etc) implement the driver of their product according to the specification.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
71/198
Fundamental Programming (Java Basic)
Class and Object <Day3-1>
Class
4.2.9. Overriding
Overriding means to create a new set of method statements for the same method signature
(name and parameters). If a subclass overrides the super class method, subclass method
is processed and the super class method is ignored. You can also redefine the method in
the subclasses including “super()” to process super class methods and add your own code
to expand the functionality in the constructor.
[Person.java] (Parent class)
public class Person{
int iBaseSalary;
Person (int iBaseSalary){ // this is constructor
this.iBaseSalary = iBaseSalary;
}
public void calcSalary(){
return iBaseSalary;
}
}
[Caller program]
// the constructor of Person class is called
President pres = new President(100);
// The next code calls the calcSalary() method of
//President class that overrides the same name
// method in super class.
Int iSalary = pres.calcSalary(); /
4.2.11. Polymorphism
1) What is Polymorphism?
Via the message sending, polymorphism is to get the different reaction depending on the
object to where the message is sent. If you send a message “getCPUType” to the notebook
object, it returns you Notebook CPU Type while sending it to the desktop machine object, it
responds you with its Desktop CPU type.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
73/198
Fundamental Programming (Java Basic)
Class and Object <Day3-1>
Class
The following figure shows polymorphism. “printOut method of caller program calls just
“print” method of Machine class and get the result of print method of CopyMachine children
class.
Figure 8 Polymorphism
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
74/198
Fundamental Programming (Java Basic)
Class and Object <Day3-1>
Exercise 4: Class programming
(3) In the calcSalary method write a code that returns total salary by adding two
parameters.
int calcSalary(int iBase, int iFamily){
return iBase + iFamily;
}
(4) Create a class “MySalary” with main() class, and call calcSalary() of SalaryBase class
setting parameters for base and family. Check if the calculation is correct.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
75/198
Fundamental Programming (Java Basic)
Class and Object <Day3-1>
Exercise 4: Class programming
MySalary SalaryBase
CalcSalary()
(5) Create a class “SalaryEmployee” (without main() method) that extends SalaryBase.
You can select "Superclass" to define the superclass in creating Java class of Eclipse.
(6) From MySalary, call calcSalary() of SalaryEmployee class. Check if you get the
calculation of the super class method printing out to the console. (Inheritance test)
SalaryBase
calcSalary()
MySalary SalaryEmployee
(7) Create a class “SalaryPresident” (without main() method) that extends SalaryBase.
(8) Create a method “calcSalary” in the SalaryPresident. Write the following calculation in
the method.
int calcSalary(int iBase, int iFamily){
return iBase * 2 + iFamily;
}
(9) From “MySalary” call the “calcSalary” method of SalaryPresident. Check if you get the
correct salary of President who has double base salary and family allowance. (Overriding
test)
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
76/198
Fundamental Programming (Java Basic)
Class and Object <Day3-1>
Exercise 4: Class programming
SalaryBase
calcSalary()
MySalary SalaryPresident
calcSalary()
(10) Create an Interface “InterfaceAllowance”. Create a public method “calcBonus” with the
following parameter and return type.
public int calcBonus(int iBase);
Right clicking on the source editor of SalaryEmployee in Eclipse, you can choose
"Source" -> "Override/Implement". Check calcBonus() method to implemenjt the method.
(12) Call the method “calcBonus” of SalaryEmployee class from MySalary class. Check if
the bonus calculation is correct. (Interface test)
<<Interface>>
InterfaceAllowance
calcBonus()
MySalary SalaryEmployee
calcBonus()
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
78/198
Fundamental Programming (Java Basic)
Thread <Day3-2>
Thread Concept
5. Thread <Day3-2>
5.1. Thread Concept
The modern processors and operating systems allow the multiprocess, that is, two or more
simultaneous processes (at least apparently) executing. In reality, a computer with a single
CPU cannot make two processes simultaneously. Nevertheless the present operating
systems enable to seem to execute several programs "simultaneously": they distribute the
time between two (or more) activities, or use the dead times of an activity (for example,
operations of data reading/writing).
A process is a program executing itself with independent way and with an own memory
space. A multiprocess operating system is able to execute more than one process
simultaneously. One process can also have several threads executing simultaneously. For
example the Internet Explorer program would be a process. If you have multiple Internet
Explorer windows open, it is because multiprocess programming is enabled. whereas each
one of the windows that is simultaneously open bringing different HTML pages would be
formed by at least one thread.
ProgramA
ProgramA
Thread1
Thread2
ProgramB
ProgramB
MultiProcess Multithread
- multithread
Threads are a way for a program to split itself into two or more simultaneously
running tasks, typically sharing the state information of a single process, and sharing
memory and other resources directly. Multithreading is an execution model that allows
multiple threads that a single process can contain sharing the same process' resources but
able to execute independently.
Process A Proccess B
Memory Memory
The term "multiprocessing" sometimes refers to the use of multiple CPU within a single
computer. And the term "multiprogramming" refers to the execution of multiple concurrent
software processes in a system.
[Benefits of multithreading]
z Better response time
The better response time can be expected for the client request or input request from user
interface by employing multithreading for those that take times causing serious wait
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
80/198
Fundamental Programming (Java Basic)
Thread <Day3-2>
Thread programming
between stages, such as some network communication, disk I/O access, or quite heavy
and complicated calculation. One of the examples is an Internet browser which downloads
HTML data from Web server. If the browser is programmed with single thread, you can not
press "go back " button, or "Stop" button , nor any mouse input while downloading HTML
data.
To execute threads It will be enough to indicate what to do in the run() method, which is the
method that defines the main activity of threads.
In this case, the SimpleThread class has been created, which inherits from Thread class.
In its constructor a String is used (optional) to put name to the new created thread, and by
means of super() the constructor of the Thread super-class is called. Also, in the run()
method the main activity of the thread is defined, consequently it writes 10 times the name
of thread.
In order to start up this new thread, an object of the SimpleThread class and the start()
method must be created, inherited from the Thread super-class in charge of calling run().
For example:
// thread created
SimpleThread myThread = new SimpleThread("Thread test");
// start the thread
myThread.start();
Do not call run() method directly but call start() method of the Thread class that is
responsible for running the method according to the thread situation.
[SimpleRunnable.java]
public class SimpleRunnable implements Runnable {
// a name is created
String nameThread;
// constructor
public SimpleRunnable (String str) {
nameThread = str;
}
// definition of the run() method
public void run() {
for (int i=0; i<10; i++)
System.out.println("This is the thread: " + nameThread);
}
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
82/198
Fundamental Programming (Java Basic)
Thread <Day3-2>
Thread programming
}
}
The following code creates a new thread and executes the second procedure:
SimpleRunnable p = new SimpleRunnable("Test thread");
// an object of the Thread class is created by passing the Runnable
object as argument
Thread myThread = new Thread(p); // thread created
// the object of the Thread class is launched
myThread.start(); // start the thread
1) New: The thread has been created but not initialized, that is to say, the start() method
has not been executed yet. An error message will take place (IllegalThreadStateException)
if it is tried to execute any method of the Thread class different from start().
2) Runnable: start() method is called to enter this stage. The thread is ready to be
executed, as long as a certain CPU time has been assigned to it.
3) Blocked or Not Runnable: The thread is in a state of wait while there is some internal
activity that prevents the execution, such as a delay produced because of writing operation,
because sleep() method is called or due to reading data by keyboard (I/O). If a thread is in
this state, CPU time is not assigned to the thread.
4) Dead: The habitual form to kill a thread is finalizing the run() method. Also the stop()
method of the Thread class can be called, although this method is considered "dangerous"
and it is not recommended to use since it kills in the middle of execution.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
83/198
Fundamental Programming (Java Basic)
Thread <Day3-2>
Thread programming
wait()
New start() Runnable sleep() Blocked
notify()
notifyAll()
end of sleep
run() ends
Dead
Once the start() method has been called, it can be said that the thread is "runnable", which
does not mean that it is being executed at every moment, because the thread must share
the CPU time with the other threads that are also running.
.
5.2.6. To temporally stop a Thread: Not Runnable
As we see, the CPU times that the system continuously assigns to the different threads in
runnable state is used for execution of the run() method of each thread. For some reason, a
thread can at a certain moment resign "voluntarily" his CPU time and give it back to the
system so that the resources can be assigned to another one. This "resignation" is made
by means of the static yield() method. It is important that this method is used by the
activities that tend "to monopolize" the CPU. The static yield() method comes to indicate
that at this moment it is not as important as this thread is executed continuously and
therefore to occupy the CPU. In case that no thread is requiring the CPU for a very
intensive activity, the system will return almost immediately to assign new time to that
thread that was "generous" with the others.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
84/198
Fundamental Programming (Java Basic)
Thread <Day3-2>
Thread programming
z Block a thread
To block a thread, there are several ways to do it:
- Executing the static sleep() method of the Thread class. This stops the thread for a
predefined time. The sleep() method is called from the run() method.
- Executing the wait() method. It makes a thread wait due to the situation in which requires
to suspend the execution. A thread will again return to the runnable situation by means of
the notify() or notifyAll().
- When a thread is waiting to do some Input/Output tasks.
- When a thread is trying to call a synchronized method of an object that is occupied by
other thread
A thread passes automatically from states Not Runnable to Runnable when some of the
previous conditions ends or when notify() or notifyAll() are called.
z Deprecated methods
A Thread class also has a stop() method, but it is not recommended to use since icttian
cause blockades of the program (deadlocks). The suspend() method has been also
deprecated.
z Sleep() method
The sleep() method of the Thread class receives as argument the time in milliseconds.
Additionally, an integer number with an additional time in nanoseconds can be included.
The declarations of these methods are the following ones:
public static void sleep(long millis) throws InterruptedException
public static void sleep(long millis, int nanoseconds) throws
InterruptedException
[Example code]
System.out.println ("Counter in seconds");
int count=0;
public void run() {
try {
sleep(1000);
System.out.println(count++);
} catch (InterruptedException e){
}
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
85/198
Fundamental Programming (Java Basic)
Thread <Day3-2>
Thread programming
The sleep() method can cause an InterruptedException that is to be captured when the
thread is interrupted with interrupt().
The sleep() method is static method. You can use it without object reference.
z wait()method
There are two forms to call wait() method:
1) Indicating the maximum time that must be blocked (in milliseconds and with the option to
also indicate nanoseconds). Unlike the sleep() method that simply stops the thread during
the indicated time, the wait() method establishes the maximum time that must be blocked. If
during that time the notify() or notifyAll() methods are executed it indicates the liberation
of the blocked objects and the thread continues without concluding the indicated time. The
two declarations of the method wait() are as follows:
2) Without arguments, in which case the thread remains blocked until it is reinitialized
explicitly by means of the notify() and notifyAll() methods.
public final void wait() throws InterruptedException
The wait() ,notify() and notifyAll() methods have to be included in a synchronized method
or block, otherwise an exception of the IllegalMonitorStateException type will be obtained in
run time.
5.2.7. Synchronization
The synchronization was born from the necessity to avoid that two or more threads try to
get access to the same resource at the same time. Thus, for example, if a thread tries to
write in a file, and another thread is at the same time trying to erase this file, unexpected
result will take place. Another case is when a thread must wait for data from another thread.
In order to solve these kinds of problems it is important to control synchronization of
threads.
The following figure shows execution of two threads simultaneously getting access to the
same resource “x”. If this is a case of bank account, the result is not what expected, since
the both threads get access to the variable “x” at the same time,.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
86/198
Fundamental Programming (Java Basic)
Thread <Day3-2>
Thread programming
Thread1 Thread2
get x x=100 get x
x=x+10 x=x+10
The following figure shows that while Thread1 is accessing to the variable “x”, Thread 2 has
to wait for synchronization since the resource is locked. Once the Thread1 releases the
resources (the resources is unlocked), Thread2 can start the process.
Thread1 Thread2
get x x=100 get x
x=x+10 x=x+10
z How to program
1) Set “synchronized” key to object
synchronized (this){
x=x+1;
}
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
87/198
Fundamental Programming (Java Basic)
Thread <Day3-2>
Thread programming
[MyThreadClass.java]
public class MyThreadClass {
public static void main(String[] args) {
System.out.println("MyThreadClass starts");
Runnable rn = new WaitTest();
Thread th = new Thread(rn);
System.out.println("WaitTest will start");
th.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (rn){
rn.notify();
}
System.out.println("MyThreadClass ends");
}
}
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
88/198
Fundamental Programming (Java Basic)
Thread <Day3-2>
Exercise 5: Thread
2. Write the following programs and execute MyThread2.java to see how the threads
work.
[TestThread.java]
public class TestThread extends Thread {
int iCount;
// constructor
public TestThread (String str, int iCount) {
super(str);
this.iCount=iCount;
// run() method
public void run() {
try {
for(int i=0; i<5; i++){
Thread.sleep(iCount);
System.out.println(getName() + "count " + i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
[MyThread2.java]
public class MyThread {
public static void main(String[] args) {
TestThread myThread1 = new TestThread("Thread1 ",1000);
// thread created
TestThread myThread2 = new TestThread("Thread2 ",2000);
// thread created
myThread1.start();
myThread2.start();
}
}
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
89/198
Fundamental Programming (Java Basic)
Input and Output Stream <Day4-1>
Input and Output of Data
6.1.1. Stream
Stream is a connection between a program and the source of the data, in other words, it is
a flow of data that communicates with outside, such as file, monitor, keyboard or network.
Note that stream is not limited to a file data but it be applied to any data communication.
This is quite convenient since a program is independent of its hardware and you do not
have to rewrite a program each time a new device is integrated. There are InputStream
class for input data and OutputStream for output.
File
Keyboard
Byte Stream
Monitor
Network
The main difference is that one operates with bytes and the other with characters (the
character of Java is formed by two bytes because it follows the Unicode).
The input and output of byte data is operated with classes derived from InputStream (for
reading) and OutputStream (for writing). These classes have the basic methods read() and
write() that handle bytes.
z InputStream(abstract class)
This is the superclass of all classes representing an input stream of bytes.
z OutputStream(abstract class)
This is the superclass of all classes representing an output stream of bytes
public abstract void write(int b) throws IOException
Writes the specified byte to this output stream.
z FileOutputStream(extends OutputStream)
A file output stream is an output stream for writing data to a File. Whether or not a file is
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
91/198
Fundamental Programming (Java Basic)
Input and Output Stream <Day4-1>
Input and Output of Data
On the other hand the text based package derives from Reader and Writer abstract class
that handle characters instead of byes. These classes are more practical for the
applications in which text is handled. FileReader and FileWriter creates stream for a text
file.
[Characters in Java]
The Java programming language is based on the Unicode character set. The primitive data
type char in the Java programming language is an unsigned 16-bit integer that can
represent a Unicode code point in the range U+0000 to U+FFFF, or the code units of
UTF-16.
Unicode is an international character set standard which covers almost all scripts in current
use today, including Burmese or Japanese. UTF-8 and UTF16 are the most widely used
character encoding of Unicode. The term Unicode in Java refers to UTF-16.
z Reader (abstract)
Abstract class for reading character streams. The read() method will be implemented in
subclass returning char charcter by int.
z Writer (abstract)
Abstract class for writing to character streams.
Figure 19 - InputStreamReader
The following example shows how to create InputStreamReader that convert from "UTF8"
to Unicode charcter
FileInputStream fis = new FileInputStream("MyExample.txt");
InputStreamReader reader = new InputStreamReader(fis, "UTF8");
Figure 20 OutputStreamReader
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
93/198
Fundamental Programming (Java Basic)
Input and Output Stream <Day4-1>
Input and Output of Data
z BufferedReader/BufferedWriter
The Reader or Writer class allows buffering the data in stead of operating in bytes. For
example:
BufferedReader in = new BufferedReader (new
FileReader("MyTxt.txt"));
String strOneLine = in.readLine();
With this line a stream has been created that allows reading of the file MyTxt.txt. In addition,
a BufferedReader object has been created. The characters that are read through
FileReader will go through the BufferedReader, to use the buffer. Once the BufferedReader
is created, readLine() method read one line of text. A line is considered to be terminated by
any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately
by a linefeed.
BufferedReader takes just Reader class as its parameter. For binary stream,
BufferedInputStream is employed for its buffering.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
94/198
Fundamental Programming (Java Basic)
Input and Output Stream <Day4-1>
Standard input and output (keyboard and screen)
z System.out: Object of the PrintStream class that will print the data to the standard
output of the system (normally associated with the screen).
z System.err: Object of the PrintStream class. Used for error messages shown by
screen by default.
These classes allow the alphanumeric communication with the program through the
methods. They are methods that allow the input/output to a very elementary level.
System.out.println("Hello World!");
System.out.println(57);
double numberPI = 3.14;
System.out.println(numberPI);
String hello = new String("Hello");
System.out.println(hello);
Several variables can be written in one call in a parameter using the + operator, that's
equivalent to convert to String all of the variables.
System.out.println("Hello World!"+numberPI);
The objects System.out and System.err are instance of the PrintStream class.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
95/198
Fundamental Programming (Java Basic)
Input and Output Stream <Day4-1>
Standard input and output (keyboard and screen)
In order to read from keyboard the method System.in.read() of the InputStream class can
be used. This method reads one character by each call. Its value of return is int. If any
other type is expected there must be an explicit conversion by means of a cast.
char c;
c=(char)System.in.read();
In order to read more data than one simple character we need to use a while or a for loop
and concatenate the characters.
char c;
StringBuffer phrase=new StringBuffer("");
try {
while((c=(char)System.in.read()) !='\n')
phrase.append(c);
System.out.println(phrase);
}
catch(java.io.IOException ioex) {}
StringBuffer is a class that manages string character dynamically. This class enables to
resize the string size. By "append() " method a character is added to the StringBuffer.
readLine() of BufferedReader returns String type. The conversion from int to String is
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
96/198
Fundamental Programming (Java Basic)
Input and Output Stream <Day4-1>
Reading a file
performed.
If they do not find the indicated file, the constructors of FileReader and FileInputStream
can launch the java.io.FileNotFoundException.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
97/198
Fundamental Programming (Java Basic)
Input and Output Stream <Day4-1>
Writing to a file
6.3.3. BufferedReader
The read() method of the InputStreamReader or FileReader class process the following;
- read single character
- convert from original or specified enconding to Unicode
- return
A BufferedReader object can be created to read using buffer fo process the character
conversion process from a text file in the following way:
BufferedReader br = new BufferedReader(new FileReader("file.txt");
In case of files it is very advisable to use the buffer so as to provide for the efficient reading
of characters, arrays, and lines. For example:
[TestBufferedReader]
// Reads a complete file the same manner as from keyboard
import java.io.BufferedReader;
import java.io.FileReader;
public class TestBufferedReader {
public static void main(String[] args) {
StringBuffer text = new StringBuffer();
try {
FileReader fr = new FileReader("readme.txt");
BufferedReader input = new BufferedReader(fr);
String s;
while ((s = input.readLine()) != null)
text.append(s + "\r");
input.close();
System.out.println(text);
} catch (java.io.FileNotFoundException fnfex) {
System.out.println("File not found: " + fnfex);
} catch (java.io.IOException ioex) {
System.out.println("IO exception: " + ioex);
}
}
}
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
98/198
Fundamental Programming (Java Basic)
Input and Output Stream <Day4-1>
Writing to a file
6.4.3. BufferedWriter
Just the same as BufferdReader, BufferedWriter provides buffering of output of one line
characters so as to provide for the efficient writing of single characters, arrays, and strings.
6.4.4. PrintWriter
The PrintWriter class is most practical to write a text file because it has the methods print
(any type) and println (any type), identical to those of System.out (of the PrintStream
class).
The println() of the PrintWriter terminates the current line by writing the line separator string
of the platform. The line separator string is defined by the system property line.separator.
This means that you do not have to change program code although the platform
changes. The system automatically obtains system dependant line separator.
A PrintWriter object can be created from a BufferedWriter, which is created from FileWriter.
The file name is passed to the parameter of FileWriter. The following example illustrates
how to write to a text file:
[TestBufferedWriter.java]
try {
FileWriter fw = new FileWriter("writeme.txt");
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter output = new PrintWriter(bw);
output.println("Hi, I'm the first line");
output.close();
// Append mode
bw = new BufferedWriter(new FileWriter("writeme.txt", true));
output = new PrintWriter(bw);
output.print("And I'm the second one. ");
double b = 123.45;
output.println(b); //double data is written.
output.close();
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
99/198
Fundamental Programming (Java Basic)
Input and Output Stream <Day4-1>
File class
}
catch(java.io.IOException ioex) {}
Note that in the above sample, double type is passed as a parameter of println() method
of the PrintWriter class which is converted to the Unicode string.
It can be given the complete name of the file, the name and directory, or just the directory.
In order to know if the file exists,you can call exists() method.
The example of File constructors;
File f1 = new File("c:\\windows\\notepad.exe"); // The slash '\' it's written '\\'
File f2 = new File("/usr/share"); // A directory for Linux
File f3 = new File("c:\\windows”, "notepad.exe"); // Set directory and file name
File separator string depends on each platform, e.g. in Windows back slash “\” is used
while Unix is slash “/“. You can get the adequate file separator dependent to the
actual platform by “file.separator” of getProperty() of the System class.
In Java, back slash “\” means tab control string. If you want to use the back slash as file
separator, you have to use escape sequence “\\” to represent back slash. For
example:
C:\\windows\\notepad.exe
The followings are some of methods of File class extracted from Java API Documentation.
See the Java API documentation File class more detail.
Table 14 Methods of File class (from Sun Microsystems Java API documentation)
Return type Method name specification
boolean exists() Tests whether the file or directory specified by this
abstract pathname exists
String getName() Returns the name of the file or directory specified by
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
100/198
Fundamental Programming (Java Basic)
Input and Output Stream <Day4-1>
File class
[Example code]
public static void main(String[] args) {
File f = new File("/temp","TextFile.txt");
System.out.println("file name = " + f.getName());
System.out.println("file directory = " + f.getParent());
System.out.println("file path = " + f.getPath());
}
[result]
file name = TextFile.txt
file directory = /temp
file path = /temp/TextFile.txt
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
101/198
Fundamental Programming (Java Basic)
Input and Output Stream <Day4-1>
Exercise 6: I/O programming
2. Create a program "TestReadFile.java" that reads the file "TestFile.txt" and print out all
the data to the console.
4. If you have some font other than English (Bermese, Japanese, etc), create a file with
those characters in UTF-8 format. If you do not have font, create it in English. Create
"TestReadEncoding.java". Read the file in Java program and check if it is correctly
read.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
102/198
Fundamental Programming (Java Basic)
Network <Day4-1>
TCP/IP
7. Network <Day4-1>
7.1. TCP/IP
The TCP/IP suite is packet based, which means that data is broken into little chunks on the
transmit end for transmission to the receiving end. Breaking data up into manageable
packets allows for faster and more accurate transfers. The suite consists of the Internet
Protocols (IP), Transport Control Protocol (TCP), and Universal Datagram Protocol (UDP).
IP is the base protocol. All data travels via IP packets, which is why addresses are referred
to as IP addresses. It is the lowest level of the suite. TCP is a connection based protocol.
Before data is transmitted, a connection is established between the two machines
communicating. Once a connection is made, a stream of data is sent to the Internet
Protocol to be broken into the packets that are then transmitted. At the receiving end, the
packets are put back in order and sent to the proper application port. UDP is
connectionless protocol. Applications using this protocol just chose their destination and
start sending.
7.1.3. IP Address
An IP address is four sets of numbers ranging from zero to 255 (known as octets)
separated by dots (.). The first set of numbers usually determines what class the network
belongs to. There are three classes of networks.
By definition, an IP address that begins with 10 in the first octet is in a Class A network, so
the network part of the address is the first byte, or first octet. An address that begins with
128 is in a Class B network. By definition, Class B addresses have a 2-byte network part,
as shown. Any addresses that begin with 192 are in a Class C network, which has a 3-byte
network part. Also by definition, a Class A address has a 3-byte host part, Class B has a
2-byte host part, and Class C has a 1-byte host part.
Table 16 Class A, B, and C Networks: Network and Host Parts and Default Masks
Class of Size of Network Size of Host Default Mask for
Address Part of Address Part of Address Each Class of
in Bits in Bits Network
A 8 24 255.0.0.0
B 16 16 255.255.0.0
C 24 8 255.255.255.0
package can be classified into two groups: One that manages Internet resources such as
host name or URL. Another one has classes that manipulate TCP/IP protocol for data
communication on the Internet.
[HostInfo.java]
/** Get local host information */
import java.net.*;
public class HostInfo {
public static void main ( String args[] ) {
try {
InetAddress inetAddress = InetAddress.getLocalHost();
System.out.println( "Machine Name:" +
inetAddress.getHostName() );
System.out.println( "IP Address:" +
inetAddress.getHostAddress() );
}
catch( UnknownHostException e ){
System.err.println( e.getMessage() );
}
}
}
The above sample code shows how to get local host information with the InetAddress class.
Since the InetAddress class does not have public constructor, the methods are defined as
static. That means, you do not have to instantiate the class by “new” keyword, but use
static method “getLocalHost()” directly to get the object of actual local host machine. Once
you get object of InetAddress, it is easy to get local host machine name and IP address.
Note that in case it fails to get correct information, it throws “UnknownHostException”.
The following code determines the IP address of a host with the given host's name.
InetAddress.getByName(String host)
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
105/198
Fundamental Programming (Java Basic)
Network <Day4-1>
Network programming with Java
When you need to get directly the resources that reside in Internet, the resources are
identified by URL and there is no conflict with other resources. The format of URL is:
http://www.jica.it.mm/index.html
(protocol)(host name with domain)(file name)
To get URL resources in Java program, “openStream()” of “URL” class gets the
connection with the Web Server. If the connection with the server by HTTP protocol
succeeds, the server sends the required resource. The programmer can read the sent data
with “InputStream” object.
[URLFile.java]
/** Get requested file from URL object stream */
import java.net.*;
import java.io.*;
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
106/198
Fundamental Programming (Java Basic)
Network <Day4-1>
Network programming with Java
z Socket
A socket is a network communications endpoint which was introduced when TCP/IP is
implemented in UNIX (4.2BSD). Each port can have a single socket, awaiting incoming
connections established by way of TCP or UDP. The mechanism is introduced for data
communication between programs using the same way as reading and writing of file I/O.
Many socket libraries are developed to realize communication program. Java has “Socket”
class in the “java.net” package that is in charge of the socket connection and data flow.
Figure 21 - Socket
z Ports
In the TCP/IP connection, port number is required to identify an application running on the
host machine. Just like IP address is identical to specify one host machine in the network,
port number also is identical associated with application to distinguished service, so that
the data sent across the network is submitted correctly to the application. Web server is
famous for its port number 80. Some web server uses 8080 port. A program can use any
port number for the communication but you should be careful not to have conflict with other
applications.
The following code shows client-server communication.
[SocketClient.java]
import java.io.*;
import java.net.*;
public class SocketClient {
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
107/198
Fundamental Programming (Java Basic)
Network <Day4-1>
Network programming with Java
- First step is to create socket object to connect with server. Host name and port number
should be set for socket connection. The host "127.0.0.1" means the host is localhost,
the same machine as that executes client program.
- “getInputStream()” method of socket connection returns InputStream object. You can
read buffered data obtained from the server.
- Note that in case host is not found in the Internet, UnknownHostException is thrown.
SocketException is thrown when it fails to create socket connection.
[SocketServer.java]
/** SocketCommunication for Server */
import java.net.*;
import java.io.*;
import java.util.*;
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
108/198
Fundamental Programming (Java Basic)
Network <Day4-1>
Network programming with Java
- First step is to create ServerSocket. The same port number declared in the client
program should be set in a parameter.
- ServerSocket method works as an auditor of the port communication. The program is
blocked until the server gets the client requirement by accept() method.
- Once the server gets the client requirement, accept() method returns the socket object
through port number.
- Creating bufferedWriter, the server program sends the message to the destination.
- After sending message the connection has been closed and goes back to the loop to
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
109/198
Fundamental Programming (Java Basic)
Network <Day4-1>
Network programming with Java
[How to execute]
- First execute the server program.
- Then execute client program providing host name as a parameter, e.g.
Java SocektClient "196.168.0.1"
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
110/198
Fundamental Programming (Java Basic)
Network <Day4-1>
Exercise 7: Network Programming
2. Write a program "URLFile.java" in the textbook. Set some URL in the program and
output its content of HTML format to check how the URL Resources are obtained by
the URL class.
You have to check if your firewall setting allows to pass the specified port (1069 in our
example) from the zone. You can set additional allowed port by YaST Firewall configuration
as follows if the port is closed;
1.) Start Yast Control Center.
2.) Select "Security and Users" -> Firewall
Ports.
4) Set the port number you want to open.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
112/198
Fundamental Programming (Java Basic)
Network <Day4-1>
Exercise 7: Network Programming
[SocketServerSendReceive.java]
1) Open the Socket Server
2) Get the connection from any client.
3) Get the file name sent from the client
4) Read the file required from the client. If the file does not exist, send back some error
message to the client. if the file exists, read it and send it back to the client.
5) Close the socked connection with the client.
Client Server
2) Connect to the server
1) Open Socket
3) Send file name 127.0.0.1:1070
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
113/198
Fundamental Programming (Java Basic)
Nested Classes <Day 4-2>
Nested Classes
[Example of classes]
class TopLevelClass { // Top level class
static class StaticInnerClass {} // static inner class
static {
class StaticInitializerLocalClass {} // Local class
}
Runnable AnonymousClassInstance =
new Runnable() { // Anonymous class
public void run() {}
};
}
void method() {
class MethodLocalClass {} // Local class
}
}
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
114/198
Fundamental Programming (Java Basic)
Nested Classes <Day 4-2>
Nested Classes
[Where to use]
- The inner classes may be helpful by giving direct reference to all the outer class's fields.
- If you find you are doing a huge amount of referencing of the outer class's fields, inner
classes will be available.
- When you want to change the behavior of some class or if you want to implement the
methods of some interface just locally and never used again in other cases, you can use
the inner class.
[ClassOne.java]
class ClassOne
{
}
class ClassTwo
}
class Outer
{
void someOuterMethod(){
}
public class Inner {
void someInnerMethod(){
}
}
static class StaticInnerClass {
void someStaticInnerMethod()
}
}
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
115/198
Fundamental Programming (Java Basic)
Nested Classes <Day 4-2>
Nested Classes
To instantiate an inner class from outside the outer class, you need once to instantiate the
outer.
Outer out = new Outer();
Outer.Inner in = out.new Inner();
or
Outer.Inner in = new Outer().new Inner();
[rules]
- can be called both from inside and outside the outer class.
- can not declare static variables except final constant.
- can use instance variables or method of the outer class.
- can access to the private variables of the outer class.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
116/198
Fundamental Programming (Java Basic)
Nested Classes <Day 4-2>
Nested Classes
- if the inner class is declared as private, it can be called only from inside of the outer
class.
[example of variable's call]
class Outer {
public int iPub = 0;
private void someOuterMethod() {}
class Inner {
public void someInnerMethod() {
System.out.println("iPub = " + iPub);
someOuterMethod ();
}
}
}
class Other {
public static void main(String[] args) {
Outer.Inner inner = new Outer().new Inner(); // Compile err
}
}
[Where to use]
- You may declare non static member class as private to avoid being called from outside.
Maybe you want it to be unknown and just to be used internally.
- When the inner class has a lot of reference of the outer class's fields that contain the
values in time of the final local variables of an outer class's calling method.
class Outer
{
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
117/198
Fundamental Programming (Java Basic)
Nested Classes <Day 4-2>
Nested Classes
[rules]
- can be called both from inside and outside the outer class.
- static nested classes may access only static outer variables and methods. This is
logical, since there is no corresponding instance object. Further, there is no
requirement for variables accessed to be final.
- You can access to private static variables from static inner class.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
118/198
Fundamental Programming (Java Basic)
Nested Classes <Day 4-2>
Nested Classes
[Where to use]
- If there are a lot of parameters to pass to a method using static variables of the outer
class, you can use static inner class.
import javax.swing.JButton;
import javax.swing.JFrame;
/**
* @param args
*/
public static void main(String[] args) {
NestedLocal myAnonymous = new NestedLocal();
myAnonymous.pack();
myAnonymous.setVisible(true);
}
public NestedLocal() {
super("NestedAnonymous");
The class that is interested in processing an action event especially in GUI application has
the following procedures;
6) implements the ActionListener interface.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
119/198
Fundamental Programming (Java Basic)
Nested Classes <Day 4-2>
Nested Classes
7) The object created with that class is registered with a component, using the
component's addActionListener method.
8) When the action event occurs, that object's actionPerformed method is
invoked.
MyListener class is created to implement actionPerformed() method of ActionListener
interface.
class MyListener implements ActionListener{
public void actionPerformed(ActionEvent e){
System.out.println("click");
}
}
[rules]
- Local inner class is called just from inside the method. It can not be called from outside
although it is named.
- You can access just field variables of the outer class, the final method variables and
final method parameters.
[Where to use]
- This class is rarely used. If the local class is available in some cases inside the method
implementing some interface, it may be used.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
120/198
Fundamental Programming (Java Basic)
Nested Classes <Day 4-2>
Nested Classes
[NestedAnonymous.java]
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
* @param args
*/
public static void main(String[] args) {
NestedAnonymous myAnonymous = new NestedAnonymous();
myAnonymous.pack();
myAnonymous.setVisible(true);
}
public NestedAnonymous() {
super("NestedAnonymous");
addWindowListener(
new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
JButton button = new JButton("click");
button.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("clicked!");
}
});
getContentPane().add(button);
}
}
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
121/198
Fundamental Programming (Java Basic)
Nested Classes <Day 4-2>
Nested Classes
The following code also uses the anonymous inner class. This is the same function as
shown in the Local inner class. If the anonymous inner class is employed, you do not have
to create a class separated, but it is expressed all inside the method.
button.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("clicked!");
}
});
Clicking the "click button", "clicked!" will be appeared in the output stream.
[rules]
- Since it has no name, it can not be called from outside of the outer class.
[where to use]
- You can define an anonymous class, create an anonymous instance of it, and pass it as a
parameter to some method all in one line.
- You want to implement the method of an interface, but the method is used only once in
that case, you can declare anonymous class to avoid coding an implemented class
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
122/198
Fundamental Programming (Java Basic)
Nested Classes <Day 4-2>
Nested Classes
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
123/198
Fundamental Programming (Java Basic)
Nested Classes <Day 4-2>
Exercise 8 Nested Classes
2. Select which variables can be accessible from the line 10 of the next program
1: class NestedExercise {
2: String str = "";
3: final int iNum;
4: void myMethod (long lSum, final int iQuant ){
5: long lSal = 0;
6: final int iMonth = 12;
7: class Inner {
8: void print(){
9: System.out.println("printing results")
10:
11: }
12: }
13: }
14: }
variables;
str
iNum
lSum
iQuant
lSal
iMonth
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
124/198
Fundamental Programming (Java Basic)
J2SE5.0 New features <Day 4-2>
Exercise 8 Nested Classes
z Generics
This enhancement to the type system allows a type or method to operate on objects of
various types while providing compile-time type safety informing of error at the compile time
in place of execution time. This new feature of compile-time type safety is especially helpfut
to the Collections Framework and eliminates the drudgery of casting.
HashMap<String,String> map = new HashMap<String,String>();
z Autoboxing/Unboxing
This facility eliminates the drudgery of manual conversion between primitive types (such as
int) and wrapper types (such as Integer).
Autoboxing
Integer(100)
100
Unboxing
Figure 25 - Autoboxing/Unboxing
z Typesafe Enums
This flexible object-oriented enumerated type facility allows you to create enumerated types
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
125/198
Fundamental Programming (Java Basic)
J2SE5.0 New features <Day 4-2>
Generics
with arbitrary methods and fields. It provides all the benefits of the Typesafe Enum pattern
without the verbosity.
public enum EnumNumber {
ONE, TWO, THREE, FOUR, FIVE
}
z Varargs
The varargs functionality allows multiple arguments to be passed as parameters to
methods. It requires the simple ... notation for the method that accepts the argument list
and is used to implement the flexible number of arguments required for printf.
void testVarargs (Object ... args) {
for (int i=0;i <args.length; i++) {
}
}
z Static Import
The static import feature, implemented as "import static", enables you to refer to static
constants from a class without needing to inherit from it. Instead of BorderLayout.CENTER
each time we add a component, we can simply refer to CENTER.
import static java.awt.BorderLayout.*;
z Metadata (Annotations)
The metadata feature in J2SE 5.0 provides the ability to associate additional data alongside
Java classes, interfaces, methods, and fields. This additional data can be read by the javac
compiler or other tools by "declarative" programming style where the programmer says
what should be done. Also it eliminates the need for maintaining to be kept up to date with
changes in source files. Instead the information can be maintained in the source file.
9.1. Generics
In the usual use of Collection, you must cast it to the type of element that is stored in the
collection. Besides being inconvenient, this is unsafe since the compiler does not check
that your cast data type is the same as the collection's type, so the cast can fail at run time
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
126/198
Fundamental Programming (Java Basic)
J2SE5.0 New features <Day 4-2>
Generics
with ClassCastException.
[C91PrevProgram.java]
import java.util.HashMap;
/**
* Display the contents of HashMap using previous function.
*/
public class C91PrevProgram {
map.put("one","one");
map.put("two","two");
}
}
Generics provides a way for you to inform the type of a collection to the compiler, so that
the type is checked. Once the compiler knows the element type of the collection, the
compiler can check that you have consistently used the collection and can insert the correct
casts on values being taken out of the collection, which means that you can get compile
check if the type is different than you defined before.
[C91NewProgram.java]
import java.util.HashMap;
/**
* @author
*
* Display the contents of HashMap using new Generics function.
*/
public class C91NewProgram {
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
127/198
Fundamental Programming (Java Basic)
J2SE5.0 New features <Day 4-2>
Generics
map.put("one","one");
map.put("two","two");
}
}
You do not have to cast any more the data type. If the wrong type is defined, you will get
the compile error.
[C91GenericsErr.java]
import java.util.HashMap;
/**
*
* Display the contents of HashMap using new Generics function.
*/
public class C91GenericsErr {
map.put("one","one");
map.put("two","two");
map.put("three",3); // NG; compile error!
String s1 = map.get("one");
String s2 = map.get("two");
int i = map.get("three"); // NG: compile error!
}
}
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
128/198
Fundamental Programming (Java Basic)
J2SE5.0 New features <Day 4-2>
Generics
In the above program you will get the following compile error :
map.put("three",3);
The method put(String, String) in the type HashMap<String,String> is
not applicable for the arguments (String, int)
int i = map.get("three");
Type mismatch: cannot convert from String to int
public C91GenericsParameter (T t) {
this.t = t;
}
public T getParam() {
return t;
}
public void setParam(T arg) {
t = arg;
}
}
/**
* Execute C91GenericsParameter
*/
public static void main(String[] args) {
// call generics with String
C91GenericsParameter<String> genStr = new
C91GenericsParameter<String>("myParam");
System.out.println("The parameter is " + genStr.getParam());
C91GenericsParameter<Integer>(12345);
System.out.println("The parameter is " + genInt.getParam());
}
}
[The results]
The parameter is myParam
The parameter is 12345
You can not insert primitive type to the collection such as int type. You have to use
object type such as Integer instead.
Generic types therefore enable an API designer to provide common functionality that can
be used with multiple data types and which also can be checked for type safety at compile
time.
/**
* For loop with previous style
*/
public static void main(String[] args) {
List list = new ArrayList();
The result is
0
1
2
3
4
5
6
7
8
9
z Using Generics
As we have seen in Generics in the previous section, we can omit the class casting.
[ForGenerics.java]
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
131/198
Fundamental Programming (Java Basic)
J2SE5.0 New features <Day 4-2>
For each sentence
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
132/198
Fundamental Programming (Java Basic)
J2SE5.0 New features <Day 4-2>
Enum
9.3. Enum
Enums are references to a fixed set of Objects that represent the various possible choices.
This flexible object-oriented enumerated type facility allows you to create enumerated types
with arbitrary methods and fields.
What we could before with Java 1.4 was to define the references "static".:
final static int ZERO = 0;
final static int ONE = 1;
final static int TWO = 2;
Now in the new feature of Java, we can define the references as follows:
modifier enum type name {identifier, identifier,…}
class EnumExample {
private EnumNumber number;
private int iNum;
this.iNum = iNum;
this.number = number;
}
System.out.println(enum1);
System.out.println(enum2);
System.out.println(enum3);
}
}
[Results]
ONE=1
TWO=2
THREE=3
[EnumSwitch.java]
/**
* Enum sample with Switch statement
*
*/
public static void main(String[] args) {
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
134/198
Fundamental Programming (Java Basic)
J2SE5.0 New features <Day 4-2>
Enum
switch (num){
case ONE:
System.out.println("The number is 1");
break;
case TWO:
System.out.println("The number is 2");
break;
case THREE:
System.out.println("The number is 3");
break;
}
}
The constant name of enum can be described in the case statement directly. You do not
have to specify the enum class name "EnumNumber.ONE", but just ONE is OK.
[EnumFor.java]
/**
* @param args
*/
public static void main(String[] args) {
for (EnumNumber num: EnumNumber.values()){
System.out.println("Number is " + num);
}
}
The result is ;
Number is ONE
Number is TWO
Number is THREE
Number is FOUR
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
135/198
Fundamental Programming (Java Basic)
J2SE5.0 New features <Day 4-2>
Boxing/unboxing
Number is FIVE
Each enum type has a static values() method that returns an array containing all of the
values of the enum type in the order they are declared. This method is commonly used in
combination with the for-each loop to iterate over the values of an enumerated type.
9.4. Boxing/unboxing
This new feature is an auto-conversion between primitive types (such as int) and wrapper
types (such as Integer) without necessity of casting.
Autoboxing means the automatic conversion from primitive type to wrapper class.
Auto-Unboxing means the automatic conversion from wrapper to primitive type.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
136/198
Fundamental Programming (Java Basic)
J2SE5.0 New features <Day 4-2>
Exercise 9: J2SE5.0 New features
1. Modify the following program using new features of J2SE5.0 with the name
"NewFeatureArrayList.java". Execute it and check if the result is the same.
[PreviousFeatureArrayList.java]
/* Compare ArrayList */
import java.util.ArrayList;
// Set values
arrayList.add("a");
arrayList.add("b");
arrayList.add("c");
2. Modify the following program using new features of J2SE5.0 with the name
"NewFeatureHashMap.java". Execute it and check if the result is the same.
[PreviousFeatureHashMap.java]
import java.util.HashMap;
import java.util.Iterator;
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
137/198
Fundamental Programming (Java Basic)
J2SE5.0 New features <Day 4-2>
Exercise 9: J2SE5.0 New features
Fill the following two boxes to print out the above results.
[NewFeatureEnumNumber.java]
}
}
}
(note) The following line indicates to pass the parameter to the constructor.
public enum Number { One(1),Two(2),Three(3),Four(4),Five(5);
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
139/198
Fundamental Programming (Java Basic)
Java GUI (I) <Day 5>
AWT
10.1. AWT
10.1.1. What is GUI
GUI stands for Graphic User Interface. GUI application is an application that provides a
user interface (usually some screen) where you can operate the components such as
window, button, menu, or icon.
[characteristics]
z Platform dependent
The user interface elements provided by the AWT are implemented using each platform's
native GUI toolkit, thereby preserving the look and feel of each platform (Window, Unix,
Mac, etc). In other words, look and feel depends on the operating system’s GUI functions.
Once you create a GUI program, it looks and behaves different in each platform.
z Applet
You can use AWT functions inside the Applet
z AWT components
The AWT consists of components, both container and non-container ones (eg. Button,
Checkbox, Choice, ...) Container components (eg. Frame, Dialog, Window, Panel)
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
140/198
Fundamental Programming (Java Basic)
Java GUI (I) <Day 5>
AWT
control the layout of other components. As containers are themselves components, they
can be placed inside other containers.
[AWTFrameTest.java]
import java.awt.Frame;
• Import java.awt.Frame
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
141/198
Fundamental Programming (Java Basic)
Java GUI (I) <Day 5>
AWT
• Implements Frame
• Call Frame (parent) constructor by calling super()
• Change the frame size by setSize() method
• Display the frame by setVisible() method
[How to execute]
Just compile the FrameTest.java. The 200 X 100 window will be displayed. To finish, type
Ctrl-C because close event is not implemented.
2. Display Button
[AWTButtonTest.java]
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
add(b1);
// Close window when user click the close button
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// show(); // java1.4
setVisible(true); // java1.5
}
}
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
to implement the above named class, you can generate your named class;
public class MyFrame extends Frame {
public MyFrame() {
addWindowListener(new ExitWhenWindowClosing());
}
}
3. Display Label
[AWTLabelTest.java]
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
AWTLabelTest() {
super("LabelTest");
setSize(200, 100);
setLayout(new FlowLayout());
Label l1 = new Label("This is label test");
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
144/198
Fundamental Programming (Java Basic)
Java GUI (I) <Day 5>
AWT
add(l1);
// Close the window when user click “x” to close.
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//show(); //java1.4
setVisible(true); //java1.5
}
}
4. Other components
z TextField
TextField t1 = new TextField("Hello World!!");
z CheckBox
Checkbox c1 = new Checkbox("OK?");
5. Event programming
Clicking the button, appears the text “Hello”.
[AWTEventTest.java]
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.Button;
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
145/198
Fundamental Programming (Java Basic)
Java GUI (I) <Day 5>
AWT
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class AWTEventTest extends Frame implements ActionListener {
Button button;
Label label;
public AWTEventTest() {
super("EventTest");
// setSize(200, 200);
setLayout(new GridLayout(2, 1));
// Create button
button = new Button("Click here");
add(button);
// Create label
label = new Label("");
label.setAlignment(Label.CENTER);
add(label);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
/**
* This method is called when the action event happens
*
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
146/198
Fundamental Programming (Java Basic)
Java GUI (I) <Day 5>
AWT
*/
public void actionPerformed(ActionEvent e) {
// Event
if (e.getSource().equals(button)) {
label.setText("Hello");
}
}
/**
* @param args
*/
public static void main(String[] args) {
new AWTEventTest();
}
}
Add the specified action listener to receive action events from this button. Action events
occur when a user presses or releases the mouse over this button.
button.addActionListener(this);
This method is called when the action (or event) happens once the action is registered to
the action listener. You can write the process you want here when the event happens
public void actionPerformed(ActionEvent e) {
// Event
if (e.getSource().equals(button)) {
label.setText("Hello");
}
}
.
You can also use the anonymous class to implement ActionListener interface as follows;
[AWTEventTestAnonymous.java]
import java.awt.Button;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
*/
Button button;
Label label;
public AWTEventTestAnonymous() {
super("AWTEventTest");
// setSize(200, 200);
setLayout(new GridLayout(2, 1));
// Create button
button = new Button("Click here");
add(button);
// Create label
label = new Label("");
label.setAlignment(Label.CENTER);
add(label);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
148/198
Fundamental Programming (Java Basic)
Java GUI (I) <Day 5>
Swing
10.2. Swing
10.2.1. What is Swing
Swing is also part of the Java Foundation Classes (JFC) which is included in the core Java
package of javax.swing from java1.2.
All Swing parts are also AWT parts, using the AWT event model and support classes, such
as Colors, Images, and Graphics with new and improved components that enhance the
look and functionality of GUIs.
.
[characteristics]
z Platform independent
Most components (JComponent and its subclasses) are emulated in pure-Java code. This
means that Swing is naturally portable across all hosts. Thus, Swing does not depend on
the operating system's native GUI.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
149/198
Fundamental Programming (Java Basic)
Java GUI (I) <Day 5>
Swing
approach for AWT. Only GUI components defined for all Java host environments would be
used. As a result -- and unfortunately -- some commonly used components, such as Tables,
Trees, Progress Bars, and others, are not supported. For applications that need more
component types, you need to code it entirely in Java
[SwingFrameTest.java]
import javax.swing.JFrame;
public class SwingFrameTest extends JFrame {
/**
* Display just Frame with Swing
*/
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
150/198
Fundamental Programming (Java Basic)
Java GUI (I) <Day 5>
Swing
• Import java.swing.JFrame.
• Implements JFrame
• Call Frame (parent) constructor by calling super()
• Change the frame size by setSize() method
• Display the frame by setVisible() method
2. Display Button
[SwingButtonTest.java]
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
SwingButtonTest() {
super("SwingButtonTest");
setSize(200, 100);
// set layout of the components(center)
getContentPane().setLayout(new FlowLayout());
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
151/198
Fundamental Programming (Java Basic)
Java GUI (I) <Day 5>
Swing
// create button
JButton b1 = new JButton("OK");
// get container to locate button
getContentPane().add(b1);
// close window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//show();
setVisible(true);
}
}
To make an application that has controls like JLabel, first a top level container is created,
the middle container is located inside, and finally the controls are put inside of the middle
container. The top level Swing window classes have a privileged child container known as
the content pane.
Middle container
button Label
The JFrame has various Panes as shown in the figure. The Content Pane is used to put
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
152/198
Fundamental Programming (Java Basic)
Java GUI (I) <Day 5>
Swing
various controls. To get the Cntent Pane of the JFrame, getContent() method is called.
The following code gets the Content Pane Container from the JFrame and set the default
Layout style by FlowLayout class. The constructor constructs a new FlowLayout with a
centered alignment and a default 5-unit horizontal and vertical gap.
getContentPane().setLayout(new FlowLayout());
4. Event programming
z Clicking the button appears the text “Hello”.
[SwingTestEvent.java]
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
153/198
Fundamental Programming (Java Basic)
Java GUI (I) <Day 5>
Swing
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
JButton button;
JLabel label;
public SwingEventTest() {
super("SwingEventTest");
setSize(300, 200);
getContentPane().setLayout(new GridLayout(2, 1));
// Create button
button = new JButton("Click here");
getContentPane().add(button);
// Create label
label = new JLabel("");
label.setHorizontalAlignment(JLabel.CENTER);
getContentPane().add(label);
pack();
//show();
setVisible(true);
}
}
}
Swing gives any program that uses Swing components a choice of look and feel. For
example, the same program can use either the Java or the Windows look and feel. The
following Look and Feels are provided by the package.
z Metal
This is Java L&F that looks the same on all platforms. It is part of the Java API
(javax.swing.plaf.metal) and is the default that will be used if you do nothing in your
code to set a different L&F.
The name of Look and Feel : javax.swing.plaf.metal.MetalLookAndFeel
z CDE/Motif
Look and Feel of X Window System.
The name of Look and Feel : com.sun.java.swing.plaf.motif.MotifLookAndFeel
z GTK+
Look and Feel for GNOME of X Window System. If the system is Linux, the GTK+, is
included in the package by default.
The name of Look and Feel : com.sun.java.swing.plaf.gtk.GTKLookAndFeel
z Windows
Look and Feel of Microsoft Window. If the default system is Window, it is included in
the Java package.
The name of Look and Feel : com.sun.java.swing.plaf.windows.WindowsLookAndFeel
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
155/198
Fundamental Programming (Java Basic)
Java GUI (I) <Day 5>
Swing
The GTK+ L&F will only run on UNIX or Linux systems with GTK+ 2.2 or later installed,
while the Windows L&F runs only on Windows systems. Like the Java (Metal) L&F, the
Motif L&F will run on any platform.
To change look and feel dynamically from program, call the setLookAndFeel() method of
UIManager setting the Look And Feel name that you want to display, and update the
component by updateComponentTreeUI() method.
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.Windows
LookAndFeel");
SwingUtilities.updateComponentTreeUI(frame)
The following program switches from java default Look and Feel (Metal) to CDE/Motif when
the button is clicked.
[SwingTestLookFeel.java]
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
JButton btnHello;
JButton btnLookFeel;
JLabel label;
public SwingTestLookFeel() {
super("SwingEventTest");
setSize(500, 200);
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
156/198
Fundamental Programming (Java Basic)
Java GUI (I) <Day 5>
Swing
getContentPane().setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
// Create label
label = new JLabel("");
c.gridwidth = 2;
c.gridx = 0;
c.gridy = 1;
label.setHorizontalAlignment(JLabel.CENTER);
getContentPane().add(label, c);
LookAndFeel");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
SwingUtilities.updateComponentTreeUI(this);
}
You can see that setLookAndFeel() method of UIManager is called to change its style
dynamically to Motif.
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.Motif
LookAndFeel");
The following code shows how to set the GridBagLayout for the Container.
getContentPane().setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
The following figure is after clicking the left button to display the name of current look and
feel.
The following figure is after clicking the right button to change the look and feel to Motif and
display the name of the new look and feel.
2. Window decorations
The JFrame we used in the previous programs still has their Window decorations (borders,
widgets to close the window, title, etc) of the default window manager. The method
"setDefaultLookAndFeelDecorated" of JFrame provides whether or not newly created
JFrames should have their Window decorations of the current look and feel. If it is set true,
current LookAndFeel supports providing window decorations. If false, newly created
JFrames will have their Window decorations provided by the current window manager.
[SwingButtonTestDecoration.java]
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
new SwingButtonTestLookFeel();
}
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
159/198
Fundamental Programming (Java Basic)
Java GUI (I) <Day 5>
Swing
SwingButtonTestDecoration() {
super("SwingButtonTest");
setSize(200, 100);
// set layout of the components(center)
getContentPane().setLayout(new FlowLayout());
// create button
JButton b1 = new JButton("OK");
// get container to locate button
getContentPane().add(b1);
// close window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//show();
setVisible(true);
}
}
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
160/198
Fundamental Programming (Java Basic)
Java GUI (I) <Day 5>
Exercise 10: AWT and Swing
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
161/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
SWT with Eclipse
[characteristics]
z Not Java core library
SWT is maintained by Eclipse Foundation, which means that it is not included in Java
core library. The package should be downloaded from http://www.eclipse.org/swt/
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
162/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
SWT with Eclipse
To provide better performance, they decided to employ a new toolkit with better
performance using native widgets.
The basic concepts behind SWT and AWT are fairly similar since both AWT and SWT
delegate widget control to the native components on the user's machine, although the way
of implementations are quite different on the point that how the two toolkits use the native
components:
z AWT
In AWT, native "peer" code, written in a language like C or C++, is used to control the real
widgets on the system. If you're running on Windows, this peer code uses MFC or Win32
calls to display widgets. On other platforms, the native GUI calls window manager for their
operating system.
for Windows
JRE for Windows
Each Java Runtime Environment (JRE) distribution provides a unique set of peers for the
target platform. The same Java classes stay. while the native code changes upon different
platforms.
As we have seen, AWT implements some commonly used components for all platforms
that JRE covers. So that is why AWT implementations suffer the problem of its primitive
components. It is also true that If the mayor part of control of the components is written in
native codes , it is almost impossible for developers to debug the errors.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
163/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
SWT with Eclipse
z Swing
Swing components are all written in Java, drawing and emulating the new components like
Trees and Tables using AWT graphics calls, which is quite hard to get it exactly right.
Swing applications may be slower than native GUIs functions because of this reason
written every components in Java, although in the recent version of Swing (Java V1.4 and
1.5), Sun makes a great efforts to get the better performance and this disadvantage is
becoming less noticeable.
But still Swing takes time to learn, and it is sometimes too complex for common situations
z SWT
Rather than write the peers in native code, SWT uses a thin Java Native Interface (JNI) to
invoke code written in C. Therefore, Java code, similar to the AWT native-code peers, uses
calls to the native API for that platform to control the widgets. But the difference stays in
that Java class libraries of SWT differs from the platform and Java call is passed right on
through to the operating system realizing one to one mapping by way of .
Call Native
SWT for API (written Motif Manager
Linux C/C++) for
Linux
Therefore, SWT creates widgets by calling native libraries if some platforms support them,
otherwise the widget can be emulated created by Java codes. For example, Windows
provides Trees and Tables, so SWT's Java code calls the MFC/Win32 libraries to display
the trees and tables under Windows platform, while another platform that didn't provide
trees or tables, the Java code for that platform could draw them.
debugging the toolkit becomes easier since all of the logic added for SWT is written in
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
164/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
SWT with Eclipse
Java,
Since the SWT implementation is different for each platform, a platform specific SWT (JAR
file) must be distributed with each application.
The SWT .zip file can then be imported into your workspace. In the File menu, choose
Import and select the Existing Projects Into Workspace wizard.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
165/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
SWT with Eclipse
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
166/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
SWT with Eclipse
With the SWT project as a dependency, you can now benefit from Eclipse features such as
the Javadoc view and code assist.
Now you can run any main class in your project by selecting the class and then selecting
Run > Run As > Java Application (quoted from Eclipse SWT manual)
Check the Java Build Path of the projects tab and open the org.eclipse.swt tag. If no
native library location is selected, click Add button and set location path from Workspace…
as "org.eclipse.swt".
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
167/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
SWT with Eclipse
[SWTHelloWorld.java]
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
shell.setText("SWTHelloWorld");
label.pack();
shell.pack();
To make a GUI application with SWT, first you must create a display before creating any
windows, and you must dispose of the display when your shell is closed.
SWT window is displayed when the open() method of shell is called. Several event listners
or layout manager configurations should be set before the open() method.
(note) Do not forget that SWT uses Java Native Interface, which means that the java
garbage collection will not work for SWT widgets.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
170/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
SWT with Eclipse
A new instance of the widgets is constructed given its parent and a style value describing
its behavior and appearance. Usually two parameters are set in the constructor;
z Parent container
z Style bit
In the above case parent container is shell and style bit is Center which constant is defined
in the SWT class. So, Label will be displayed on the shell in the center location.
If there is no style;
Text text = new Text(shell, SWT.NULL)
[SWTEvent.java]
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
// Create Label
Label label1 = new Label(comp, SWT.NULL);
label1.setText("Specify the csv address File ");
// Create button
button = new Button(comp, SWT.NULL);
button.setText("search file..");
// Clicking the button, appears the file dialogue
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
getOpenFileName();
textBox.setText(fileName);
}
});
shell.open();
return shell;
}
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
172/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
SWT with Eclipse
/**
* @param args
*/
public static void main(String[] args) {
Display display = new Display();
SWTEvent swtEvent = new SWTEvent();
Shell shell = swtEvent.open(display);
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
Clicking the search file button, and appears the following file dialogue screen to select file
from the directory.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
173/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
SWT with Eclipse
The following code shows that the GridLayout style is set to shell.
shell.setLayout(new GridLayout(1, false));
3. Declare Composite
Composite is a control that can contain other controls such as button, label, etc, quite
similar as Container of AWT or JPanel of Swing.
The following code shows how to declare Composite;
// Generate a Composite to place widgets
Composite comp = new Composite(shell, SWT.NO_FOCUS);
GridData class is an associated layout data object to determine space, margin, and detail
style of the widgets inside the GridLayout.
new GridLayout(4,true)
This code shows that the data layout for GridLayout is 4 numbers of colomns, and "true"
shows if the columns have the same width.
The "horizontalAlignment" decides how the widget will be placed horizontally. By
GridData.FILL, the widget will be placed occupying entire column width of the grid. Once
you have defined the layout data, you have to set it to the GridData by setLayoutData()
method.
4. Event listener
The following code shows how to register event listener.
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
getOpenFileName();
textBox.setText(fileName);
}
});
Widget has several event listeners and the method name has the format of addXXX.
The addSelectionListener() method takes SelectionListener interface as its parameter. The
SelectionEvent class provides default implementations for the methods described by the
SelectionListener interface. You can take the SelectionAdapter class for the parameter to
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
175/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
SWT with Eclipse
override only the method that you want to define, in this case widgetSelected, which
happens when the control is selected. In the above program, when the button is clicked, the
file dialogue opens to select a file from some directory on the machine.
5. Thread issue
When the OS platform detects GUI events, places them in application event queues. As the
user clicks the mouse, types characters, the OS generates application GUI events, such as
mouse clicks, keystrokes, or window paint events. It determines which window and
application should receive each event and places it in the application's event queue.
This is executed under an event loop, where applications simply read the GUI events from
the queue and reacts accordingly. That is why long operations triggered by UI events
should be performed in a separate thread in order to allow the event loop thread to return
quickly and fetch the next event from the application's queue, Otherwise, a user should wait
without doing any reaction until the long operation event finishes and return the control to
the application.
exit
disposed?
event?
No Sleep
Yes
Process the
Event
If the process takes time,
the next event should wait
long time
z asyncExec(Runnable)
This is an asynchronous method of Display class that Causes the run() method of the
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
176/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
Visual Editor
The following code demonstrates the pattern for using these methods:
// execute some operation asynchronously in the other thread
display.asyncExec (new Runnable () {
public void run () {
// check if the user abandoned the operation
if (!myWindow.isDisposed())
someLongOperation ();
}
});
You have to create thread by way of asyncExec() method of Display class, which is a UI
thread class that is permitted to call UI threads. If you call directly from your class, Invalid
thread access of SWTException will occur.
The visual editor is based on the JavaBeans component model and supports visual
construction using the Standard Widget Toolkit (SWT), the Abstract Window Toolkit (AWT),
or Swing.
VE is written in pure Java and should run on all operating systems officially supported by
the Eclipse platform, both Windows and Linux (GTK and Motif).
http://download.eclipse.org/tools/ve/downloads/index.php.
You will also need to download the matching version of GEF and EMF for graphical
interface.
In our class we are going to install the following version;
Table 18 Software version for VE -
Software Version notes
OS Linux Suse 10.2
Java JDK1.5.10
Eclise Eclipse 3.2.1
VE VE 1.2.1
EMF EMF 2.2.0
GEF GEF3.2.1
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
179/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
Visual Editor
(3) Select the Standard Widget Toolkit (SWT) from Add Library window and click
Next button.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
180/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
Visual Editor
(4) Select IDE Platform and check "Include support for JFace library" and finish it.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
181/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
Visual Editor
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
182/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
Visual Editor
1. In the Java perspective, click File > New > others > java > Visual Class. The New Java
Visual Class wizard opens.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
183/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
Visual Editor
The New Java Visual Class windows opens. Set the following information to create a new
class.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
184/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
Visual Editor
2
3
4
5
6
7
8
10
11
12
13
14
2. In the Source Folder field, enter the workspace folder where the class will be saved. This
will default to your current project.
3. In the Package field, enter the name of the Java package where you want the visual
Java class to be packaged.
4. Ensure that the Enclosing type check box is cleared. Selecting this option creates an
inner class in another class that you specify, so no new visual class is created.
5. In the Name field, enter the name for the new Java visual class.
6. Select one of the following modifiers to specify access control for the class:
public - makes the class completely available to any other class that wants to use
it
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
185/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
Visual Editor
default - sets no modifier, making it available to any other class in the same
package
7. Optional: Select one of the following modifiers for the class:
abstract - indicates that the class will serve in a superclass role
final - indicates that the class cannot be subclassed
8. In the Style list, select the toolkit and visual element that you want your new visual class
to extend. For example, you can select SWT composite, or Swing JPanel.
9. The Superclass field displays the appropriate class name. If you select Other as the style,
you need to specify the superclass that you want to extend or accept the default
java.lang.Object. The java.lang.Object superclass can be used, for example, for a SWT
application that uses a SWT Shell.
10. Optional: To import and implement an additional interface in your new visual class, click
Add and select the interface, then click OK. The interfaces to be implemented are listed in
the Interfaces field. Repeat this step for each interface.
11.(Optional) public static void main(String[] args) - generates a stub main() method for
running the class as a Java application. For SWT applications, the visual editor also
generates the necessary display loop in the main method.
12. (Optional) Constructors from superclass - generates constructor stubs to initialize
methods inherited from the superclass.
13. (Optional) Inherited abstract methods - generates stubs for additional abstract methods
inherited from the superclass.
14. (Optional) Select Generate comments if you want the wizard to add comments to the
source code, as configured in the project properties.
Click Finish.
(Reference from VE Manual)
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
186/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
Visual Editor
Pallet
Graphical editor
Source editor
Property
editor
- Pallet
You can select SWT components, Swing components or AWT components from
the palet to draw in the graphical editor by drug and drop.
- Source editor
What you edit in the Graphical editor will be reflected in Java code in the source
editor. If you insert some controls or actions such as event, the corresponding source is
displayed and also you can directly modify the source code.
- Property editor
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
187/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
Visual Editor
All the widges that is defined in the Visual class will be displayed in the property
editor. Select the widget from the Graphical editor and set its properties such as size,
layout, color, font, etc, from this editor.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
188/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
Visual Editor
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
189/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
Exercise 11: Practice Programming Java GUI with SWT
1. Create a SWT project named "SWTPrj" and create the program named
"SWTEvent.java" according to the manual. Execute the program and check if the SWT
environment is correctly formed.
3. Create a Visual class named VEFileViewer.java. Create the program that shows the
following image using Visual editor.
4. Add Event proram in the "Search File" button. When it is clicked, open a file dialogue
window with "java" extension. Show the file name selected in the text box.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
190/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
Exercise 11: Practice Programming Java GUI with SWT
5. Add Event proram in the "File Load" button. If the file exists, display the content of the
file in the text area.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
191/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
Exercise 11: Practice Programming Java GUI with SWT
6. Change the above program to show the graphic image of ".jpg" file. You can use
"org.eclipse.swt.graphics.Image" to load image from a file, and
"org.eclipse.swt.widgets.Canvas" to paint the loaded the image to the Window.
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
192/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
Exercise 11: Practice Programming Java GUI with SWT
When the load button is clicked, image object is created by file. Then call the redraw()
method of canvas object; .jpg file
Register PaintListener of the Canvas. so that the PaintListener will be sent when a paint
event occurs for the control, which event occurs when the redraw() method of the canvas is
called. The "GC" is the class where all of the drawing capabilities that are supported by
SWT are located. The drawImage() draws the given image in the receiver at the specified
locations.
canvas.addPaintListener(new org.eclipse.swt.events.PaintListener()
{
public void paintControl(org.eclipse.swt.events.PaintEvent e) {
if (image!= null) {
e.gc.drawImage(image, 0, 0);
}
}});
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
193/198
Fundamental Programming (Java Basic)
Java GUI (II) <Day 6>
Exercise 11: Practice Programming Java GUI with SWT
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
194/198
Fundamental Programming (Java Basic)
Tables and Figures
Figures
11.4. Figures
11.5. Tables
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
195/198
Fundamental Programming (Java Basic)
Indexes
Keywords
Indexes
11.6. Keywords
concatenation, 33
conditional operator, 32
abstract, 65 constructor, 69
access modifier, 65
array, 48 do loop, 44
ArrayList, 55
assignment operator, 32
exception, 46
extends, 71
behavior, 64
blocked, 85
final, 65
cast, 30
class, 64
Comment, 16
comments, 213
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
196/198
Fundamental Programming (Java Basic)
Indexes
Keywords
List, 52
main, 11, 66
IDE, 18
Map, 53
if statement, 37
message, 64
IllegalMonitorStateException, 88
Metadata (Annotations), 128
implements, 72
method, 64, 68
import, 67
method modifier, 68
increment operator, 27
IndexOutOfBoundsException, 49
InetAddress, 107
Nested class, 116, 117
inheritance, 70
Non static member class, 116, 118
InputStream, 93, 108
notify(), 87
instance, 67
notifyAll(), 87
instanceof, 32
NullPointerException, 26
interface, 72
NumberFormatException, 61
IP Address, 106
Iterator, 53
object, 64
java.util package, 52
package, 16, 66
JIT, 12
polymorphism, 75
JVM, 12, 18, 50
port, 109
Primitive types, 22
PrintStream, 101
life cycle of a thread, 85
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
197/198
Fundamental Programming (Java Basic)
Indexes
Keywords
System.in, 97
System.out, 97
Reader, 96 System.out.println(), 16
readLine(), 98
Reference types, 21
return, 45 throws, 68
run(), 84 Top level class, 117
Runnable interface, 84
sleep(), 87
socket, 109
start(), 84 Varargs, 128
static, 65 variable, 21
static variable, 75
stop(), 87 wait(), 88
SVG, 241
Swing, 151
switch statement, 38
yield(), 86
SWT, 165
S-FS-C-1.0
Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar
198/198