My Selection Course

198
S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar 1/198 Fundamental Software Development Information and Communication Technology Training Institute, Union of Myanmar [Fundamental Programming (Java Basic)]

Transcript of My Selection Course

Page 1: My Selection Course

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

1/198

Fundamental Software Development

Information and Communication Technology

Training Institute, Union of Myanmar

[Fundamental Programming (Java Basic)]

Page 2: My Selection Course

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

2/198

Document History

Date Version By Remarks 27 Dec. 2006 0.01 Y. Shiraishi Draft version

Page 3: My Selection Course

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

3/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

Page 4: My Selection Course

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

4/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

Page 5: My Selection Course

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

5/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

Page 6: My Selection Course

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

6/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

Page 7: My Selection Course

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

7/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

Page 8: My Selection Course

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

8/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

Page 9: My Selection Course

Fundamental Programming (Java Basic) Concept of Java Language <Day1-1> Characteristic of Java Language

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

9/198

1. Concept of Java Language <Day1-1>

1.1. Characteristic of Java Language 1.1.1. What is object oriented language? Object oriented language is a program where objects are the principal building blocks. Each

object is a programming unit consisting of data and functionality.

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.

1.1.2. What is Java? Java, born during the principle of the '90s in the laboratories of Sun Microsystems, is an

object-oriented language that was developed especially for the Internet and other large

networks where different kinds of computer are connected together. It is compatible with

different operating system. Java is open source program that you can download free from

Sun Microsystems download site.

1.1.3. Characteristic of Java Language Object Oriented Language

Java language was designed with the policy of realizing the object oriented what C++

language can not succeed in. Therefore, the object oriented functionalities are included in

the language. .

Write Once, Run Anywhere This is a promise presented by Sun Microsystems about Java technology.

Java enables programs to be executed in every computer, regardless whether it is a

Mac, PC or UNIX based computer. This is because the programs are compiled to “byte

Page 10: My Selection Course

Fundamental Programming (Java Basic) Concept of Java Language <Day1-1> Characteristic of Java Language

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

10/198

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.”

JIT(Just In Time) compile and Byte Code

Traditionally a program is compiled to machine language statically before execution. But it

is required to recompile the program each time the platform changes. Interpreter is another

way to convert a program interpreting line by line to machine code at the time of execution.

But interpreter causes time loss at runtime due to translation. Java introduced Byte Code

and JIT (Just In Time) technology to resolve these problems. A program is converted to

Byte Code (not a machine code) by compiler. Byte Code is an intermediate code that

JVM(Java Virtual Machine) can read at runtime and converts to appropriate machine code

according to the hardware architecture by JIT compile technology. This enables Java

Language to be platform-independent and assure portability of the language.

Figure 1 Byte Code of JAVA

Robustness In Java language you can not manipulate directly memory pointer of the valuables, nor

describe memory assignments/release manually which is a characteristics of “C”

Language.

What you need is only to instantiate an object. The used memory which is not any more

referred in the program will be released by Garbage Collection. Garbage Collection looks

for used memory area and released automatically in your place when necessary, so that

programmers do not worry any more about memory assignments.

package ictti; public class HelloWorld { public static main (String arg[]){ System.out.println("HelloWorld") } }

Compile

Compile phase Execution phase

Machine Code BBHGWOEKK33KCM,CX/FR ………….

JVM Byte Code IL_0000: Idstr

Hello

World

Page 11: My Selection Course

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

11/198

1.2. Getting started with “HelloWorld” program 1.2.1. Download JDK from Sun site 1) Get the JDK of J2SE(Java 2 Standard Edition) from the next download page.

http://java.sun.com/javase/downloads/index.jsp

2) Select the JDK Version, e.g. “J2SE 5.0 Downloads”. Go to “Download file page” and

select your platform. For example, for Linux, select

- Linux RPM in self-extracting file (” jdk-1_5_0_11-linux-i586-rpm.bin”)

and download the file

3) From your machine set up the software. The package will be installed to the selected

directory.

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".

Figure 2 Download JDK from YaST

Page 12: My Selection Course

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

12/198

4) Accept to download JDK.

JDK directory structure JAVA_HOME

bin (Development tools, javac, java)

jre (run time environment)

lib (additional class libraries)

include (C header files)

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.

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.

� JAVA_HOME is an variable that is almost commonly used among JAVA application to

find out where the Java Home exists. It is recommended that the variable is not set as your

Environment Variable, but instead it is better to specify which version of JAVA should be

used by each application in the startup executable file. In our class JAVA_HOME is set as

an environment variable. You can check which Java is called as defaut by printenv

command;

printenv JAVA_HOME

� 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.

1.2.2. Create a program [HelloWorld.java] package ictti;

Page 13: My Selection Course

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

13/198

/* * 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.

{} (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.

public class HelloWorld

This sentence represents that this block is a class and the name of class is

“HelloWorld”. The class name should coincide with source file name. “public” means

that this class is accessible from any other classes.

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.

Page 14: My Selection Course

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

14/198

- “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.

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.

package ictti Package is a way of grouping classes. In the example the class HelloWorld is grouped

into the package named “ictti”.

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*/

1.2.3. How to compile? Compile in Java is to convert a source programs to Byte Code so that JVM can execute the

program at runtime.

The Java compiler (javac) is one of the development tools included in the JDK (Java

Development Kit) and is in charge of syntax analysis written in the source code files (with

“.java” extension). If it does not find errors in the code, it will generate files of compiled byte

code (with .class extension).

1) First open X terminal window.

2) In the terminal window change to the directory where your “HelloWorld.java” program is

saved.

3) Check that “HelloWorld.java” is really in the directory by typing “ls".

Page 15: My Selection Course

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

15/198

4) Compile the program typing

javac –d ./ HelloWorld.java

� "-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

5) If there is no error, HelloWorld.class file is created under the “ictti” directory.

1.2.4. How to execute? 1) “java” command execute compiled “.class” file. Type

java –classpath ./ ictti.HelloWorld

2) “Hello World” will be displayed in the teminal Window.

Figure 3 Execute HelloWorld.java

Page 16: My Selection Course

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

16/198

� 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.

1.2.5. HelloWorld with Eclipse Eclipse is an Open Source IDE(Integrated Development Environment), mostly provided in

Java, but the development language is independent and can be extended by plug-in for C,

C#, COBOL, PHP, RUBY, Perl, HTML, JSP, XML, etc. Eclipse includes an interactive

development environment: Java application and Web applications, compiler, debugger.

You can download free open source software from the following site that maches to your platform:

http://www.eclipse.org/downloads/index.php

Eclipse works in various platforms: Windows, Linux, Solaris, AIX, HP, and MAC.

Let’s see how we can create and execute a program using Eclipse in the exercise.

[Tips of Eclipse] If you save the source file, automatically the source code is compiled. The compile

error will be displayed in the Problems view.

If you put the cursor over some object, te javadoc will be displayed shortly.

PF4 will show you the hierarchy of the type.

By Ctrl + space the code assist works to complete the name of the class or variables.

You can set the JavaDoc location right clicking the rt.jar, so that in the javadoc view

appears more detail javadoc specification.

By "Ctrl + Shift + f", the source code will be formatted.

Page 17: My Selection Course

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

PF3 will open the Declation of the class, method or variable.

Refactoring functions; change method name, extract constant, extract method name,

etc.

Page 18: My Selection Course

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

1.3. Exercise 1: HelloWorld

1. Create a “HelloWorld” program from terminal window and execute it.

2. Create a “HelloWorld” program with Eclipse and execute it.

Page 19: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (I) <Day1-2> Variable data

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

19/198

2. Java Programming Grammar basics (I) <Day1-2>

2.1. Variable data 2.1.1. Variables A variable is an association of a name to a value, which can change in time. In other words

it is a name we put to certain data so we can refer to it later.

Now, let’s see an example of value assignation:

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 } }

The output of this program is obviously 5.

The Java programming language has two categories of data types: reference and

primitive type.

2.1.2. Reference types Reference types are class type, interface type and array type. Variables of the reference

types store references to objects.

Object myObject String myString

It is possible for two variables to reference the same objects.

Page 20: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (I) <Day1-2> Variable data

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

20/198

2.1.3. Primitive types Variable of primitive type contains a single value of the appropriate size and format

Table 1 Primitive types

�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.

Variable type Description

boolean 1 byte. True or false values

char 2 bytes. Unicode. Includes the ASCII code

byte 1 byte. Integer value between -128 and 127

short 2 bytes. Integer value between -32768 and 32767

int 4 bytes. Integer value between -2147483648 and 2147483647

long 8 bytes. Value between -9223372036854775808 and

9223372036854775807

float 4 bytes. From -3.402823e38 to -1.401298e-45 and from 1.401298e-45 to

3.402823e38

double 8 bytes. From -1.79769313486232e308 to -4.94065645841247e-324 and

from 4.94065645841247e-324 to 1.79769313486232e308

Page 21: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (I) <Day1-2> Variable data

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

21/198

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.

2.1.4. The scope of a variable A Block in a program affects the scope of variables. All the definitions of the variables are

valid inside a block which determines a scope of action or validity of the definition, even

inside of other included blocks.

[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 */ } }

Page 22: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (I) <Day1-2> Variable data

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

22/198

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,

2.1.5. Naming rules Variables, classes and methods names are referred as specifier. A valid specifier consists

of letters, digits, underscore (_) and currency symbol ($). The first character must not be a

digit, and, of course, we can't use any reserved keyword as a variable name.

[?] Which one is valid name?

counter // valid

$cost // valid

c/o // invalid

i_18n // valid

how-are-you // invalid

Saturday // valid

?

Page 23: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (I) <Day1-2> Variable data

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

23/198

CaMeL // valid

11thVariable // invalid

It's important to mention that all the identifiers are case sensitive, so the variable “foo”

is not the same as “Foo”.

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.

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.

The first letter should be alphabet letter, “$” or “_”.

2.1.6. Reserved Keywords The following is a list of reserved keywords which have a special meaning in Java we can't

use them as variable names.

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

From Sun Microsystems Language Specification

Page 24: My Selection Course

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

24/198

2.1.7. Escape Sequences Java language provides the special character escape sequence to represent special

characters such as backslash, newline or Unicode characters.

Table 2 Escape Sequences

Escape Sequences Description

\\ Backslash

\" Double quote

\' Single quote

\b Backspace

\f Form feed

\n Newline

\r Carriage return

\t Horizontal tab

\udddd Unicode Characters\udddd (where each d

represents a hexadecimal digit)

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 ! ~

Page 25: My Selection Course

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

25/198

Precedence Type of operators Operators

creation or cast new (type)expr

2 arithmetic * / %

3 arithmetic + -

4 shift << >> >>>

5 relational < > <= >= instanceof

6 equality == !=

7 bitwise AND &

8 bitwise exclusive OR ^

9 bitwise inclusive OR |

10 logical AND &&

11 logical OR ||

12 conditional ?:

13 assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

2.2.1. Arithmetic operators Arithmetic operators are used to express arithmetic expressions between variables and

constants.

(a + b) * 1.5 / c (a % b) - (4 * c)

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:

Table 4 arithmetic operators

Operator Use Description

+ op1 + op2 Adds op1 and op2 (it also concatenate strings)

- op1 - op2 Subtracts op1 from op2

* op1 * op2 Multiplies op1 by op2

/ op1 / op2 Divides op1 by op2

% op1 % op2 Computes the remainder of dividing op1 by op2

2.2.2. Increment and Decrement operators Java has the increment operator “++” and the decrement operator “--". The operator “++”

increases the variable to which it is applied, whereas the operator “--") reduces it in a unit.

Page 26: My Selection Course

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

26/198

Table 5 Increment and Decrement

Operator Use Description

++ op++ Increments op by 1; evaluates to the value of op before it was

incremented.

++ ++op Increments op by 1; evaluates to the value of op after it was

incremented.

-- op-- Decrements op by 1; evaluates to the value of op before it was

decremented.

-- --op Decrements op by 1; evaluates to the value of op after it was

decremented.

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.3. Bitwise complement Operator: The ~ operator performs bitwise inversion on integral types. If the type is smaller than int,

the type is converted to int and performed the operation. For example 11110000 will be

converted to 00001111.

The ! operator inverts the value of a boolean. The false will be converted to true. The true

will be converted to false.

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...

Page 27: My Selection Course

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

27/198

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) ); } }

The output is as follows;

a + b = 37 x + y = 33.4 a * x = 364.6 b / y = 1.1206328279499012

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

Page 28: My Selection Course

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

28/198

Data type of the result Data type of operands

int Neither operand is a long, float or double and at least one operand is

int.

long Neither operand is a float or double. At least one operand is long.

float Neither operand is a double. At least one operand is float.

double At least one operand is double.

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.

2.2.6. Relational operators Relational operators are used to compare two values and determine the relationship

between them. The result of these operators is always a boolean value (true or false)

according to if the considered relation is fulfilled or not. These operators are used very

frequently in the bifurcations and in the loops.

Table 7 Relational operators

Operator Use The result is true

> op1 > op2 if op1 is greater than op2

>= op1 >= op2 if op1 is greater or equal to op2

< op1 < op2 if op1 is minor than op2

<= op1 <= op2 if op1 is minor or equal to op2

== op1 == op2 if op1 is equal to op2

!= op1 != op2 if op1 is not equal to op2

[?] What does the following code print, true or false?

int x = 100; int y = 100; System.out.println(x == y); // prints true System.out.println(x != y); // prints false ?

Page 29: My Selection Course

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

System.out.println(x >= y); // prints true

2.2.7. Logical operators The logical operators are often used with relational operators to construct logical

expressions, combining logical values (true and/or false) or the results of the relational

operators. Note that operators such as “&&” or “||” does not evaluate the second operator

because it is no longer necessary (if both operands must be true and the first one is false,

we already know that the condition that both should be true is not going to fulfill). The single

operators “&” and “|” assures that both operands are always evaluated.

If ((x>=0) & method(y)) //(x>=0) and method(y) are always evaluated If ((x>=0) && method(y)) method(y) //is evaluated only when (x>=0) is true

Table 8 Logical operators

Operator Name Use Result

&& AND op1 && op2 true if op1 and op2 are true. If op1 is false, op2 will

no be evaluated

|| OR op1 || op2 true if op1 or op2 are true. If op1 is true, op2 will

not be evaluated

! negation ! op true if op is false and false if op is true

& AND op1 & op2 true if op1 and op2 are true. Always evaluate op2

| OR op1 | op2 true if op1 or op2 are true. Always evaluate op2

^ XOR op1 ^ op2 true if op1 and op2 are different. op1 true and op2

false or vice versa.

[?] How about the following sample, it is true or false?

int x = 100; int y = 21; boolean b = x == 100 | y > 1000; //true boolean d = x == 55 ^ y < 33; //true

2.2.8. Bit manipulation operators Precedence Operator Description

2 ~ NOT (bitwise complement)

6 <<, >> Left-shift, Right-shift

6 >>> Right shift as if unsigned

?

Page 30: My Selection Course

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

Precedence Operator Description

9 & Bitwise AND

10 ^ Bitwise XOR

11 | Bitwise OR

0000 0000 0101 0100 ope1 (84)

0000 0001 0100 0111 ope2 (327)

0000 0000 0100 0100 ope1&ope2 (68)

0000 0001 0101 0111 ope1|ope2 (343)

0000 0001 0001 0011 ope1^ope2 (275)

1111 1110 1011 1000 ~ope2 (-328)

2.2.9. Shift operators << >> >>> Java also has a set of operators who act at a bits level. The bits operations are used

frequently to define signals or flags. The following is an example of 32 bits(integer) shift

manipulation to

0000 0000 0000 0000 0000 0000 0110 0011 initial value of x is 99

0000 0000 0000 0000 0000 0011 0001 1000 x<<3 (value is 792)

0000 0000 0000 0000 0000 0000 0000 1100 x>>6 (value is 12)

1111 1111 1111 1111 1111 1111 1001 1101 initial value is -99

1111 1111 1111 1111 1111 1111 1111 1001 y>>4 (value is -7)

0000 0000 0000 1111 1111 1111 1111 1111 y>>>12 (value is 1048575)

The sign of the value is filled in the ">>" operator. The ">>>" operator always fills with "0"

when it is shifted.

2.2.10. Assignment operators The assignment operators allow us to assign a value to a variable by equal operator (=).

The general form of the assignment statements with this operator is:

variable = expression;

int x = 100; //100 is assigned to x int x += 10; //same as int x = x + 10;

Page 31: My Selection Course

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

31/198

2.2.11. Instanceof operator The instanceof operator allows to know if an object belongs or not to a certain class. It is a

binary operator whose general form is,

objectName instanceof ClassName

and returns true or false according to if the object belongs or not to the class.

2.2.12. Conditional operator This operator “?”, taken from C/C++, allows making simple conditional bifurcations.

booleanExpression ? res1 : res2

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.

2.2.13. String of characters, concatenation operand (+) The operator plus (+) is also used to concatenate chains of characters. For example, to

write an amount with label and units this sentence can be used:

System.out.println("The total is "+ x + " units");

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.14. Operators precedence The order in which the operations are made is fundamental to determine the result of an

expression. For example, the result of “x/y*z” depends on which operator is made first.

Multiplicative operators have more priority than additive, just the same as arithmetic

calculation.

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

Page 32: My Selection Course

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

32/198

example:

// This line is a comment

int a=1; // Comment to the right of a sentence // we need the double slashes at the beginning of any new line

/* In this comment we can make a multiple line comment, we need to use the slash-asterisk to start, and the asterisk-slash to end the 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 .

Page 33: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (I) <Day1-2> Exercises2: Variables, operators

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

33/198

2.3. 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.

4. Execute the following program to see widening and cast of operators.

[OperatorsDemo.java] public class OperatorsDemo {

Page 34: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (I) <Day1-2> Exercises2: Variables, operators

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

34/198

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) ); int c = (int)x; System.out.println("c = " + c); } }

Page 35: My Selection Course

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

35/198

3. Java Programming Grammar basics (II) <Day2>

3.1. 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.

3.1.1. if, elseif and else statements This structure allows us to execute a set of sentences based on the value that has the

comparison expression (it is executed if the comparison expression has the value true). It

has the following general form:

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 */ }

We introduce an example using “if” to take decisions.

[GrammerIf.java] class GrammerIf { public static void main (String[] args) { if(args.length > 0){ System.out.println("Hello " + args[0]); }else{ System.out.println("You must pass a parameter!"); } } }

Page 36: My Selection Course

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

36/198

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.

3.1.2. switch statement Switch is an alternative to if, elseif and else bifurcation, when the same expression with

different values is compared.

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;] }

The more relevant characteristics of the switch bifurcation are:

1) Each sentence corresponds with an only value of expression. Ranges or conditions

cannot be set. Switch statement must be compared with integer values (smaller than 32

bits): byte, char, short, and int.

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.

char c = (char)(Math.random()*26+'a'); // Random generation of lowercase character System.out.println("The character "+c); switch (c) { case 'a': // compares with the character 'a' case 'e': // compares with the character 'e' case 'i': // compares with the character 'i' case 'o': // compares with the character 'o' case 'u': // compares with the character 'u'

System.out.println(" it's a vowel."); break;

Page 37: My Selection Course

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

37/198

default: System.out.println(" it's a consonant."); }

3.1.3. for loop The "for" statement is used when you need to execute a statement in multiple times.

[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.

To specify the parameter arguments in Eclipse,

1) Select the class you want to run.

2) Right click the mouse and select "Run As" -> "Run…"

Page 38: My Selection Course

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

Figure 4 How to set parameter arguments in Eclipse (I)

3) Select Srguments tag and set the Program arguments

Page 39: My Selection Course

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

39/198

Figure 5 How to set parameter arguments in Eclipse (II)

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]);

for (initialization, loop condition, step) { // code_block; }

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.

The order of actions in a “for” loop is the following:

1) initialization

Page 40: My Selection Course

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

40/198

2) check loop condition: if true perform 3) else 5)

3) execute code_block

4) goto 2).

5) continue with the next instruction after the code_block

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.

Page 41: My Selection Course

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

41/198

3.1.4. while loop In case we don't know how many times the loop is going to iterate, “while” loop is

convenient.

while(condition){ // check condition, if true, enter the block, // if not, jump to the end of it // code_block, do some stuff } // the block ends

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

Page 42: My Selection Course

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

42/198

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."); } } }

3.1.6. Branching Statements Java provides three branching statements that alter the standard flow of the program:

break, continue and return.

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;

Page 43: My Selection Course

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

43/198

boolean bl = true; while (bl) { if (i==5) { break; //Finish while loop when i equals with 5 } System.out.println(i); i++; } } }

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++; } } }

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.

Page 44: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (II) <Day2> Exception; try{...} catch {...} finally {...} block

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

44/198

3.2. 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.

3.2.1. Try, catch block The code within the try block is always checked by the system. If an abnormal situation

takes place, an exception is thrown consequently and the control moves to the catch block,

which handles the exceptional situation and decides what to do. Multiple catch blocks can

be included for each exception case, dealing with various types of exception. The finally

block, that is optional, is executed whatever type of error occurred or not (both normal case

and exceptional case execute the final block if it is described).

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.

Page 45: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (II) <Day2> Exception; try{...} catch {...} finally {...} block

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

45/198

} } // 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.

void method2() throws IOException, MyException { ... // Code that can throw the IOException and MyException exceptions ... } // End of method2

The following code shows the Exception at runtime.

[example of Runtime Exception] int i = 0, sum = 0; int[] count = new int[3]; try { for (;;) sum += count[i++]; }catch (IndexOutOfBoundsException e) { e.printStackTrace(); }

IndexOutOfBoundsException is caught when the index of the array exceeds.

printStackTrace() method sends the stack trace to the system console. A stack trace is la

list of method calls exception. It shows the line number and methods that causes the

exception.

[example of printStackTrace ]

java.lang.ArrayIndexOutOfBoundsException: 3

at Primitive.main(MyException.java:40)

Page 46: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (II) <Day2> Array

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

46/198

3.2.3. Throwing exception Exception can be created in the program using throw keyword. Once a throw statement is

executed, the method stops executing immediately, and the exception is passed back to

the caller method.

public void evokeException() throws FileNotFoundException{ try { readData ("CustomerList.txt"); catch (FileNotFoundException ex){ System.out.println("CustomerList not found"); throw ex; } }

The caller method must either declare or handle the exception.

… try{ evokeException(); }catch (Exception e){ System.out.println("The exception is caught because of " + e.getMessage(); ) } …

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

3.3.1. Characteristics of array Array is an object that can store multiple variables.

Elements should have the same type of valuable. For example all the elements are int

Variable1 Arr[0] Arr[1] Arr[2] Variable2 Variable3

Page 47: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (II) <Day2> Array

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

47/198

type if the array is declared as int. You can not mix int, double, long or String in the

same array.

An array is associated with “length” to see the array size, e.g.

Array_name.length

If you get access to an index bigger or smaller than the declared array size,

IndexOutOfBoundsException occurs.

Multidimensional array is accepted in Java.

The elements of an array can be accessed with an index that varies from o to length-1.

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.

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

Like all the objects, arrays are passed as arguments to the methods through reference.

3.3.2. Declaration of array Any of the following declaration formats.

type name[]; type[] name;

[Example] int counts[]; int[] counts[]; // same as int counts[]; String names[]; String[] names; // same as String names[]; Color[] myColor;

3.3.3. Array creation Array is created with size and allocated in the memory by “new” keyword. You must specify

the amount of storage you needs.

counts = new int[20]; names = new String[1000]; myColor = new Color[10];

3.3.4. Initialization primitive types You can set value of primitive type to each element of an array.

int[] counts={1,2,3};

or

int[] counts = new int[3];

Page 48: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (II) <Day2> Useful packages

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

48/198

counts[0] = 1; counts[1] = 2; counts[2] = 3;

To get access to each element, you can specify by index.

System.out.println(counts[0], counts[1], counts[2]);

3.3.5. Initialization of object type You will have to instantiate object for each element of an array.

Color[] myColor=new Color[10]; for (int i=0;i<10;i++ ){ myColor[i] = new Color();

[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 (...);

3.4. Useful packages Java standard library that comes with JVM provides a lot of utile packaged classes. It is

convenient to know some of them to be able to use when you need some functions.

3.4.1. String class java.lang.String class is oriented to handle string characters. There are following two ways

to declare string character.

1) Declaration of String object String str = "Hello"; String str = new String("Hello");

The difference between two declarations is that the first statement of the “Hello” object is

created only once. If there is other variable that declare “Hello”, the string is shared. In the

second statement always an object “Hello” is created. If you create twice, there are two

“Hello” strings in the memory.

Page 49: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (II) <Day2> Useful packages

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

49/198

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

To compare two objects, there is a method “equals()”.

String a1; boolean bl; a1 = new String(“Hello”); a2 = new String("Hello"); if (a1.equals(a2)){ bl = true; }else{ bl = false; } System.out.println(bl);

3) Convert from primitive type to String To convert primitive type to String, valueOf() method is provided.

String s1 = String.valueOf(12345); //convert int type to String

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

Table 9 Wrapper class and primitive type

Page 50: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (II) <Day2> Useful packages

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

50/198

� All the Wrapper class name start with capital letter.

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.

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.

List

Wrapper

class

Variable

type

Description

Boolean boolean 1 byte. True or false values

Char char 2 bytes. Unicode. Includes the ASCII code

Byte byte 1 byte. Integer value between -128 and 127

Short short 2 bytes. Integer value between -32768 and 32767

Integer int 4 bytes. Integer value between -2147483648 and 2147483647

Long long 8 bytes. Value between -9223372036854775808 and

9223372036854775807

Float float 4 bytes. From -3.402823e38 to -1.401298e-45 and from 1.401298e-45

to 3.402823e38

Double double 8 bytes. From -1.79769313486232e308 to -4.94065645841247e-324

and from 4.94065645841247e-324 to 1.79769313486232e308

Page 51: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (II) <Day2> Useful packages

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

51/198

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

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.

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.

Table 10 Iterator method

return method remarks

boolean hasNext() True if the iteration has more elements.

Object next() Returns next element

void remove() Removes element

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

Page 52: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (II) <Day2> Useful packages

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

52/198

HashMap hashMap = new HashMap(); // 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"); } // remove Lunch key hashMap.remove("Lunch"); // 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,

HashMap hm = new HashMap();

Page 53: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (II) <Day2> Useful packages

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

53/198

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); }

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.

[Difference between array and ArrayList] - Array can not resize dynamically while ArrayList can.

- Array defines one object type to store in the declaration while ArrayList can store any

object

[TestArrayListSample1.java] /* TestArrayList */ import java.util.ArrayList; public class TestArrayListSample1 { public static void main (String[] args) { // Instantiate ArrayList ArrayList arrayList = new ArrayList(); // Set values arrayList.add("Star cola"); arrayList.add("Myanmar beer"); arrayList.add("Alpin"); // Display the contents of ArrayList System.out.println("ArrayList contents: " + arrayList);

Page 54: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (II) <Day2> Useful packages

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

54/198

// 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)); // Get data size System.out.println("data size : " + arrayList.size()); // 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

Page 55: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (II) <Day2> Useful packages

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

55/198

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

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 {

Page 56: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (II) <Day2> Useful packages

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

56/198

public static void main(String[] args) { Date date1 = new Date(); long now = date1.getTime(); Date date2 = new Date(now + 1000); System.out.println("date1 is after date2? " + date1.after(date2)); System.out.println("date1 is before date2? " + date1.before(date2)); System.out.println("date1 is same as date2? " + date1.equals(date2)); System.out.println("date1 is after date2? " + date1.compareTo(date2));

System.out.println("date2 is after date1? " + date2.compareTo(date1)); } }

[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.

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

Page 57: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (II) <Day2> Useful packages

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

57/198

"/" + c1.get(Calendar.MONTH) + "/" + c1.get(Calendar.DATE)); } }

[results] Calendar Instance;java.util.GregorianCalendar[time=1172978298260,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Tokyo",offset=32400000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2007,MONTH=2,WEEK_OF_YEAR=10,WEEK_OF_MONTH=2,DAY_OF_MONTH=4,DAY_OF_YEAR=63,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=0,HOUR_OF_DAY=12,MINUTE=18,SECOND=18,MILLISECOND=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.

� The first month of the year is JANUARY which starts from 0.

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

Page 58: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (II) <Day2> Useful packages

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

58/198

} }

[results]

year2007 month03 day04 2007/03/04

� Text can be quoted using single quotes (') to avoid interpretation.

Page 59: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (II) <Day2> Exercises3: Flow control, Arrays and Useful packages

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

59/198

3.5. Exercises3: Flow control, Arrays and Useful packages 1. Make a loop program following the instructions. Program name is TestLoop.java.

(1) Get a number parameter from command line.

(2) Check the parameter. If it is not set, print error message, e.g.

if (args.length==0){ System.out.println("Error. Please set command line parameter."); }

You can convert parameter String to integer type by;

int iParam = Integer.parseInt(args[0]);

(3) To check if it is not numerical, catch “NumberFormatException” and print error message,

e.g.

try{ }catch (NumberFormatException e){ System.out.println("NumberFormatException has occurred"); }

(4) Write loop statement that repeats printing message output for the number input by user,

e.g.

System.out.println("Loop index is " + i);

(5) If the parameter is greater than 10, print following message

System.out.println("The parameter is greater than 10. The program has finished");

(6) Execute the program. Try every case;

- No parameter case

- Alphabetical parameter case

- Parameter smaller than 10

- Parameter greater than 10

� 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);

Page 60: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (II) <Day2> Exercises3: Flow control, Arrays and Useful packages

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

60/198

2. Execute the following program to see false. Modify the program to be able to compare

the String object.

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

3. Create a program “TestArray.java” and follow the instructions.

(1) Make two arrays(Menu and Price) and store the following data for each array.

Menu table

Menu Price

Coffee 180

Tea 160

Juice 200

Ice cream 220

(2) Print all the data of two arrays.

4. Create a program “TestHashMap.java” and follow the instructions.

(1) Store the above data (MenuTable) in HashMap. The class HashMap is defined in the

java.util package. To use a class of some package insert the following line in the beginning

of your class.

import java.util.HashMap

(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.

5. Create a program “TestArrayList.java”. Store the menu string(Coffee, Tea…) of above

Page 61: My Selection Course

Fundamental Programming (Java Basic) Java Programming Grammar basics (II) <Day2> Exercises3: Flow control, Arrays and Useful packages

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

61/198

menu table and print out all. You can use iterator() method to get Iterator.

Page 62: My Selection Course

Fundamental Programming (Java Basic) Class and Object <Day3-1> What is an object?

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

62/198

4. Class and Object <Day3-1>

4.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.

A class--the basic building block of an object-oriented language such as Java--is a template

that describes the data and behavior associated with instances of that class. When you

instantiate a class you create an object that looks and feels like other instances of the same

Page 63: My Selection Course

Fundamental Programming (Java Basic) Class and Object <Day3-1> Class

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

63/198

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]

Access modifier; Access modifier indicates access level from other classes. One of “public”, “protected”,

“private” and default(not specified) is specified.

Table 12 Access modifier

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

Modifier Java Access

private private Only accessible within

the class

protected protected Accessible within

subclass and within the

package

public public Accessible from

anywhere

package Default(without

specifier)

Accessible within the

same package

Page 64: My Selection Course

Fundamental Programming (Java Basic) Class and Object <Day3-1> Class

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

64/198

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:

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

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

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.,

2) How to declare in a program package package_name

[Example code] package mm.ictti;

Page 65: My Selection Course

Fundamental Programming (Java Basic) Class and Object <Day3-1> Class

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

65/198

public class HelloWorld{ // Your class name with package is //mm.ictti.HelloWorld … }

� The declaration of package should be written in the first statement in a program.

� Package is not mandatory. But it is convenient to have it in a project.

� When a program is compiled, the directory structure of package is created.

For example, “mm.ictti.HelloWorld” class is stored to the file ;

“mm/ictti/HelloWorld.class” after compilation.

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.*

� import statement should be declared before class declaration.

package mm.ictti; import java.io.* public class HelloWorld { ………….. }

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.

How to code In Java you can create instances of a class using the keyword new.

Person person = new Person();

How to call method A message has four parts;

Page 66: My Selection Course

Fundamental Programming (Java Basic) Class and Object <Day3-1> Class

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

66/198

(1) Identity of the recipient object

(2) Code to be executed by the recipient

(3) Arguments for the code

(4) return value

The following statement is an example of calling a method ; int iSalary = person.calcSalary(5000); (4) (1) (2) (3)

How to declare method

[access modifier][method modifier] return_type method_name (parameter lists) [Exception]

[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

Page 67: My Selection Course

Fundamental Programming (Java Basic) Class and Object <Day3-1> Class

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

67/198

return iBaseSalary+ allowance; }

To call Person’s calcSalary;

public class MyClass{ Person person = new Person(); Int iSalary = person.calcSalary(5000); }

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.

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.

class Base extends Object { int iValue; Base (int value){ iValue = value; } � class MyClass extends Base{ MyClass(){ super(5); } �

- The keyword this is used to the object the method is called upon.

class MyClass { int value; MyClass (int value){ this.value = value;

Page 68: My Selection Course

Fundamental Programming (Java Basic) Class and Object <Day3-1> Class

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

68/198

} }

[Example code of multiple constructors] class President { int iBaseSalary; public President (int a_BaseSalary){ iBaseSalary = a_BaseSalary; } public President(){ iBaseSalary = 5000; } }

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.

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 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.

Page 69: My Selection Course

Fundamental Programming (Java Basic) Class and Object <Day3-1> Class

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

69/198

Figure 7 Inheritance

The super class contains variables and methods common to all of the subclasses.

How to code Use “extends” keyword in subclass.

4.2.7. Abstract class An abstract class is a class that is incomplete, or to be considered incomplete and is

intended only as a base class for other classes, by including the abstract modifier. An

abstract class can specify abstract methods that the subclass must implement. Abstract

class contains not only abstract method but also non-abstract methods with functionality.

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.

public void Dog extends Animal{ }

public void Animal{ int weight; void eat(){ ; // code for eating

} }

* The Dog class inherits “weight”

property and “eat()” method without

defining in its class.

Animal Machine

Copy machine Computer dog

Super

l

Sub classes

Page 70: My Selection Course

Fundamental Programming (Java Basic) Class and Object <Day3-1> Class

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

70/198

(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.

You should instantiate the implemented class;

Dog dog = new Dog(); //This is OK

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.

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.

public Dog extends Animal{ void eat(){ // you have to code here

} }

public abstract Animal{ int weight; abstract void eat(); }

*You have to implement “eat()”

method in the subclass.

Page 71: My Selection Course

Fundamental Programming (Java Basic) Class and Object <Day3-1> Class

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

71/198

� You can not instantiate interface or abstract class directly.

� In Java language, Multiple class inheritance is not allowed. But mult-level instance is

allowed. You can not extend more than one class by “extends” keyword. Instead you can

implement multiple interfaces.

� In the Javadoc, interface is expressed with italic style. You can see the examples in the

java.sql package, such as Connect or Statement.

[Why Interface?] 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.

public class Dog implements Animal{

public void eat(){ // you have to code here

} public void sleep(){

// you have to code here }

public void run(){ // you have to code here

}

}

public interface Animal {

public void eat();

public void sleep();

public void run();

}

*You have to implement “eat()”,

“sleep()”, run() methods in the subclass.

Page 72: My Selection Course

Fundamental Programming (Java Basic) Class and Object <Day3-1> Class

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

72/198

The following code shows how to get connection with DataBse.

try { Class.forName("com.mysql.jdbc.Driver"); String strURL = "jdbc:mysql://localhost/webapp"; Connection con = DriverManager.getConnection(strURL,"user", "pass"); System.out.println("connection succeeded."); }catch (SQLException e){ // error code }

The java.sql.Connection is an interface for the connection with database by way of JDBC.

Once Connection is obtained, you can manipulate the database according to java

specification. The way to connect database by way of JDBC may differ from each database

vendor but they should follow the specification of interface (the method name, parameter

list, return data type) defined in Java to be able to manipulate in Java programming.

Useful to use parameter data type When Interface is defined as parameter list of some method, all the implemented class

(subclass) can be passed as its parameter. This is quite useful to develop method setting

just interface without knowing the real implemented subclass which may develop someone

else.

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; } }

[President.java] (Child class)

Page 73: My Selection Course

Fundamental Programming (Java Basic) Class and Object <Day3-1> Class

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

73/198

class President extends Person { President (int a_BaseSalary) { // this is constructor. super(a_ BaseSalary); } public void calcSalary(){ // This is overriding method of

super �//class return iBaseSalary * 2 } }

[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(); /

� The method declared with final modifier can not be overridden.

� The method declared with private modifier can not be overridden by sub classes.

4.2.10. static variable A static variable is expressed with static keyword. It is also called as class valuable. A static

variable is accessible and shared from all the objects. It does not depend on each object

but on a class. In the memory a static variable is stored only in one place to be able to be

shared while an instance variable without static modifier is associated with its objects,

therefore an instance variable is stored in the object area in the memory.

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.

2) How to implement polymorphism? Define the same method name in different child classes and parent class.

Override the method

Inheritance allows overriding the parent’s method by redefining the same name of

Page 74: My Selection Course

Fundamental Programming (Java Basic) Class and Object <Day3-1> Class

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

74/198

method as parent class.

Create abstract class

Creating abstract class and implement the method in the child class.

Create Interface class

Creating interface class and implement the method in the child 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

public static void MyApp { public void main (String[] args){

CopyMachine cm=new CopyMachine(); printOut(cm); } static void printOut(Machine machine){ machine.print(); }

}

public class Machine{ public void print(){ }

}

public class CopyMachine extends Machine{ public void print(){ } }

public class Computer extends Machine{ public void print(){ }

} (Caller program)

Parent class

Child class Call "print” method of Machine class and get print result of CopyMachine.

Page 75: My Selection Course

Fundamental Programming (Java Basic) Class and Object <Day3-1> Exercise 4: Class programming

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

75/198

4.3. Exercise 4: Class programming

1. Fill the following table with ○ or × to indicate access control.

Table 13 access control

Access public protected private default

Accessible

within the class �

Accessible

within subclass

and within the

package

Accessible

within the same

package

Accessible from

anywhere �

2. Class programming exercise. Follow the instructions.

This is an exercise of Inheritance, Polymorphism, Overriding and Overloading using three

classes and one Interface

(1) Create a class “SalaryBase” without main() method.

(2) Create a method “calcSalary” that receives following parameters and returns int value.

int calcSalary(int iBase, int iFamily){}

(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.

Page 76: My Selection Course

Fundamental Programming (Java Basic) Class and Object <Day3-1> Exercise 4: Class programming

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

76/198

Figure 9 Relationship of MySalary and SalaryBase

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

Figure 10 Relationship of MySalary and 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)

MySalary SalaryBase

CalcSalary()

MySalary

SalaryBase

calcSalary()

SalaryEmployee

Page 77: My Selection Course

Fundamental Programming (Java Basic) Class and Object <Day3-1> Exercise 4: Class programming

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

77/198

Figure 11 Relationship with MySalary and SalaryPresident

(10) Create an Interface “InterfaceAllowance”. Create a public method “calcBonus” with the

following parameter and return type.

public int calcBonus(int iBase);

(11) Implement InterfaceAllowance in the SalaryEmployee class. Create a method as

follows;

public int calcBonus(int iBase){ return iBase * 3; }

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

Figure 12 RelationShip with MySalary and SalaryEmployee with interface

MySalary

<<Interface>> InterfaceAllowance calcBonus()

SalaryEmployee

calcBonus()

MySalary

SalaryBase

calcSalary()

SalaryPresident

calcSalary()

Page 78: My Selection Course

Fundamental Programming (Java Basic) Class and Object <Day3-1> Exercise 4: Class programming

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

78/198

(13) Try to instantiate InterfaceAllowance class. (You will fail.)

(14) Create a method in SalaryBase as follows;

int calcSalary(String strBase, String strFamily){ // Code here to change two parameters from String to int iBase and iFamily. return calcSalary( iBase, iFamily); }

(15) Call calcSalary of SalaryEmployee from MySalary by two string parameters.

(Overloading test)

?

Page 79: My Selection Course

Fundamental Programming (Java Basic) Thread <Day3-2> Thread Concept

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

79/198

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.

Figure 13 Multiprocess and Multithread

ProgramA ProgramA

ProgramB

Thread1

Thread2

ProgramB

MultiProcess Multithread

Page 80: My Selection Course

Fundamental Programming (Java Basic) Thread <Day3-2> Thread Concept

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

80/198

The difference between multiprocess and multithread is;

- multiprocess

Multiple processes such as application are executed simultaneously by

independent way, carry considerable state information, have separate address spaces, and

interact only through special inter-process communication mechanisms. if you can enjoy

listening music by media player, writing word processor and accesing to the Web site is

thanks to the multiprocess system.

- 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.

Figure 14 Thread and 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] 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

Proccess B Process A

Memory Memory

Thread Thread Thread

Page 81: My Selection Course

Fundamental Programming (Java Basic) Thread <Day3-2> Thread programming

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

81/198

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.

Better through put By multithreading it is possible to make good use of the wait time of CPU for devices that

take time to process. For example if all the files in the disk should be list up, by

multithreading system the disk accessing time can assign for other tasks since CPU will be

free.

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.

5.2. Thread programming 5.2.1. Thread creation. In Java there are two forms to create new threads;

Create a new class that inherits the java.lang.Thread class overloading the run()

method of this class.

Create a class that implements the java.lang.Runnable interface, which will declare the

run() method; later an object of Thread type is created passing the Runnable

implemented object reference as the argument to the constructor.

5.2.2. Thread creation inheriting from Thread class. [SimpleThread.java] public class SimpleThread extends Thread { // constructor public SimpleThread (String str) { super(str); } // run() method redefinition public void run() { for(int i=0; i<50; i++){ System.out.println("This is the thread : " + getName() + i); } }

Page 82: My Selection Course

Fundamental Programming (Java Basic) Thread <Day3-2> Thread programming

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

82/198

}

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.

5.2.3. Thread creation implementing the Runnable interface This second way requires creating a class that implements the Runnable interface. The

run() method is overridden to specify what to do in a thread. It is necessary to pass a

reference of the object of the class that implements Runnable to the constructor of the

Thread class. Later, when the start() method of thread is executed, the thread will call the

run() method defined in the Runnable implemented class. Next sample is the class that

implements the Runnable interface:

[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); }

Page 83: My Selection Course

Fundamental Programming (Java Basic) Thread <Day3-2> Thread programming

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

83/198

} }

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

5.2.4. Life cycle of a thread. Thread has four different states:

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.

Page 84: My Selection Course

Fundamental Programming (Java Basic) Thread <Day3-2> Thread programming

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

84/198

Figure 15 Thread's lifecycle

5.2.5. Call a new thread It is necessary to initiate the start() method. The start() method is in charge of calling the

run() method of the Thread class. In case of using a class that implements the Runnable

interface, just the same way, the start() method of the Thread class takes care to call to the

overridden run() method of Runnable implemented class

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.

start() wait()sleep()

run() ends

New

Dead

notify() notifyAll() end of sleep

Blocked Runnable

Page 85: My Selection Course

Fundamental Programming (Java Basic) Thread <Day3-2> Thread programming

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

85/198

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.

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.

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){ }

Page 86: My Selection Course

Fundamental Programming (Java Basic) Thread <Day3-2> Thread programming

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

86/198

� 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.

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:

public final void wait(long timeout) throws InterruptedException

public final void wait(long timeout, int nanos) throws

InterruptedException

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,.

Page 87: My Selection Course

Fundamental Programming (Java Basic) Thread <Day3-2> Thread programming

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

87/198

Thread1 Thread2

get x x=100 get x

x=x+10 x=x+10

x=110 x=110 x=110

Figure 16 Threads not synchronized

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

x=110 x=110 x=110

x=120

Figure 17 Synchronized threads

How to program

1) Set “synchronized” key to object

synchronized (this){ x=x+1; }

2) set synchronized to method

void synchronized calc(){ x=x+1; }

Example of synchronized with wait method [WaitTest.java] public class WaitTest implements Runnable {

get x

x=x+10

x=120

Page 88: My Selection Course

Fundamental Programming (Java Basic) Thread <Day3-2> Thread programming

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

88/198

public synchronized void run() { try { System.out.println(" WaitTest will wait"); wait(); //wait until notify() is called System.out.println(" WaitTest has awaked"); } catch (InterruptedException e) { e.printStackTrace(); } } }

[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"); } }

[The result of execution]

MyThreadClass starts

WaitTest will start

WaitTest will wait

WaitTest has awaked

MyThreadClass ends

Page 89: My Selection Course

Fundamental Programming (Java Basic) Thread <Day3-2> Exercise 5: Thread

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

89/198

5.3. Exercise 5: Thread

1. Write a program SimpleThread.java in the textbook. Create a class MyThread1.java

and run the two SimpleThread.

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(); } }

Page 90: My Selection Course

Fundamental Programming (Java Basic) Input and Output Stream <Day4-1> Input and Output of Data

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

90/198

6. Input and Output Stream <Day4-1>

6.1. Input and Output of Data Java has java.io package for input and output of data manipulation. Stream class is the

principal concept for managing 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.

Figure 18 – Stream of I/O

6.1.2. java.io package The javio.io package contains the necessary classes for the communication of the program

with outside. This package principally operates two different types of data: byte and text.

File

Byte Stream

Keyboard

Monitor

Network

Page 91: My Selection Course

Fundamental Programming (Java Basic) Input and Output Stream <Day4-1> Input and Output of Data

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

91/198

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.

InputStream(abstract class) This is the superclass of all classes representing an input stream of bytes.

public abstract int read() throws IOException

Reads the next byte of data from the input stream. The value byte is returned as an int in

the range 0 to 255. If no byte is available because the end of the stream has been reached,

the value -1 is returned.

� The read() method throws IOException. It is necessary to catch the exception or throws

to the caller program.

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.

FileInputStream (extends InputStream) A FileInputStream obtains input bytes from a file in a file system. FileInputStream is meant

for reading streams of raw bytes such as image data. For reading streams of characters,

consider using FileReader

public FileInputStream(String name) throws FileNotFoundException

Creates a FileInputStream by opening a connection to an actual file, the file named by the

path name in the file system.

If the named file does not exist, is a directory rather than a regular file, or for some other

reason cannot be opened for reading then a FileNotFoundException is thrown.

� The read() method throws FileNotFoundException. It is necessary to catch the exception

or throws to the caller program.

FileOutputStream(extends OutputStream) A file output stream is an output stream for writing data to a File. Whether or not a file is

Page 92: My Selection Course

Fundamental Programming (Java Basic) Input and Output Stream <Day4-1> Input and Output of Data

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

92/198

available or may be created depends upon the underlying platform.

public FileOutputStream(String name) throws FileNotFoundException

Creates an output file stream to write to the file with the specified name.

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.

Reader (abstract)

Abstract class for reading character streams. The read() method will be implemented in

subclass returning char charcter by int.

public int read() throws IOException

Read a single character.

Writer (abstract)

Abstract class for writing to character streams.

public void write(int c) throws IOException

Write a single character.

InputStreamReader (extends Reader)

An InputStreamReader is a bridge from byte streams to character streams: It reads bytes

and decodes them into characters using a specified charset, which means to convert

between Unicode character streams and byte streams of non-Unicode text..

Page 93: My Selection Course

Fundamental Programming (Java Basic) Input and Output Stream <Day4-1> Input and Output of Data

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

93/198

Figure 19 - InputStreamReader

public InputStreamReader(InputStream in)

Create an InputStreamReader that uses the default charset.

public InputStreamReader(InputStream in, String charsetName)

Create an InputStreamReader that uses the named charset.

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");

OutputStreamWriter (extends Writer)

An OutputStreamWriter is a bridge from character streams to byte streams: Characters

written to it are encoded into bytes using a specified charset.

Figure 20 OutputStreamReader

public OutputStreamWriter(OutputStream out)

OutputStreamReader non (Java) Unicode bytes

InputStreamReader (Java)Unicode characters

(Java)Unicode characters

non (Java)Unicode bytes

Page 94: My Selection Course

Fundamental Programming (Java Basic) Input and Output Stream <Day4-1> Input and Output of Data

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

94/198

Create an OutputStreamWriter that uses the default character encoding.

public OutputStreamWriter(OutputStream out, String charsetName)

Create an OutputStreamWriter that uses the named charset.

FileReader (extends InputStreamReader)

Convenience class for reading character files. The constructors of this class assume that

the default character encoding and the default byte-buffer size are acceptable.

public FileReader(String fileName) throws FileNotFoundException

FileWriter (extends OutputStreamWriter)

Convenience class for writing character files. The constructors of this class assume that the

default character encoding and the default byte-buffer size are acceptable.

public FileWriter(String fileName) throws IOException

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.

� . A buffer is a space of intermediate memory between outside and program. When a

data is required to process in CPU a consecutive data is stored into the memory from the

disc as buffer. This way to read consecutive data at once is more effective than to read one

byte data.

Page 95: My Selection Course

Fundamental Programming (Java Basic) Input and Output Stream <Day4-1> Standard input and output (keyboard and screen)

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

95/198

6.2. Standard input and output (keyboard and screen) In Java, the entrance from keyboard and the exit to screen are regulated through the class

System. This class belongs to the java.lang package. Icttiontains, among others, three

static objects.

System.in: Object of the InputStream class prepared to receive data from the

standard input of the system (generally the keyboard)

System.out: Object of the PrintStream class that will print the data to the standard

output of the system (normally associated with the screen).

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.

6.2.1. Write to console. In order to print in the screen the methods System.out.print() and System.out.println() are

used. They are the first methods that any programmer learns. They can print values written

directly in the code or in any other type of primitive variable of Java.

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.

6.2.2. Read from console 1) Read by byte

Page 96: My Selection Course

Fundamental Programming (Java Basic) Input and Output Stream <Day4-1> Standard input and output (keyboard and screen)

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

96/198

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.

2) Read one line by buffer

In order to facilitate the keyboard reading it is possible to read a whole line with a single

order if the BufferedReader is used. The String readLine() which belongs to

BufferedReader reads all the characters until it finds a ' \n' or a ' \r' and gives back them like

a String (without including neither ‘\n’ nor ‘\r'). This method can also throw

java.io.Exception.

try{ InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); // or in a single line: BufferedReader br2 = new BufferedReader( new InputStreamReader(System.in)); String phrase = br2.readLine(); // The line is read with a

// single call } catch(IOException e){ // write exception case }

� readLine() of BufferedReader returns String type. The conversion from int to String is

Page 97: My Selection Course

Fundamental Programming (Java Basic) Input and Output Stream <Day4-1> Reading a file

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

97/198

performed.

6.3. Reading a file 6.3.1. Byte code file The FileInputStream class (extending InputStream) allows reading bytes in files.

public static void main(String[] args) { BufferedInputStream bis; BufferedOutputStream bos; int iData; try { bis = new BufferedInputStream( new FileInputStream("/usr/share/eclipse")); bos = new BufferedOutputStream( new FileOutputStream("myBinary.bin")); while ((iData = bis.read()) != -1) { // System.out.print(iData + "\t"); bos.write(iData); } bis.close(); bos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }

6.3.2. Text file For text files it is preferable to apply FileReader (descends of Reader) (it derives from

Reader class).

FileReader fr1 = new FileReader("file.txt");

It’s equivalent to:

File f = new File("file.txt"); FileReader fr2 = new FileReader(f);

� If they do not find the indicated file, the constructors of FileReader and FileInputStream

can launch the java.io.FileNotFoundException.

Page 98: My Selection Course

Fundamental Programming (Java Basic) Input and Output Stream <Day4-1> Writing to a file

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

98/198

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); } } }

6.4. Writing to a file 6.4.1. Byte code file The FileOutputStream class (extending OutputStream) allows writing bytes in files.

Page 99: My Selection Course

Fundamental Programming (Java Basic) Input and Output Stream <Day4-1> Writing to a file

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

99/198

6.4.2. Text file To write to a text file FileWriter that derives from Writer class is used.

� The constructors of FileWriter and FileOutputStream can launch a java.io.IOException. If

they do not find the file indicated, they create it. By default, these two classes begin to write

data in the beginning of the file. In order to append to the file, the second value is used with

the value true.

FileWriter fw = new FileWriter("file.txt", true);

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();

Page 100: My Selection Course

Fundamental Programming (Java Basic) Input and Output Stream <Day4-1> File class

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

100/198

} 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.

6.5. File class An object of the File class can represent a file or directory. It has the following constructors:

File(String name)

File(String dir, String name);

File(File dir, String name);

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

Page 101: My Selection Course

Fundamental Programming (Java Basic) Input and Output Stream <Day4-1> File class

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

101/198

this abstract pathname

String getPath() Converts this abstract pathname into a pathname

string.

boolean isDirectory() Tests whether the file specified by this abstract

pathname is a directory.

boolean isFile() Tests whether the file specified by this abstract

pathname is a normal file. String[] list()

boolean mkdir() Creates a directory named by this abstract

pathname.

[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

Page 102: My Selection Course

Fundamental Programming (Java Basic) Input and Output Stream <Day4-1> Exercise 6: I/O programming

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

102/198

6.6. Exercise 6: I/O programming

1. Create a program "TestWriteFile.java" that writes to a file "TestFile.txt" of your home

directory. Write the following three data to the file.

[TestFile.txt] Coffee Tea Juice

2. Create a program "TestReadFile.java" that reads the file "TestFile.txt" and print out all

the data to the console.

3. Create a program "TestConsole.java". Follow the instructions.

(1) Display message to the console to input the data for menu (e.g. "coffee", "tea",

"ice cream", etc).

(2) Get the data from console. When "quit" is input to the console, finish the program.

(3) Write the data obtained from console to a file “TestConsole.txt” of your home

directory.

(4) Execute “TestConsole” and input any data. Input “quit” to finish the program.

Check the file “TestConsole.txt” if the input data are stored correctly.

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.

Page 103: My Selection Course

Fundamental Programming (Java Basic) Network <Day4-1> TCP/IP

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

103/198

7. Network <Day4-1>

7.1. TCP/IP

7.1.1. Basic of TCP/IP The Transmission Control Protocol/Internet Protocol (TCP/IP) is the de facto standard

communication protocol used for client/server conversation over a network.

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.2. TCP/IP Layer Model Although the OSI (Open Systems Interconnection) model is widely used and often cited as

the standard, TCP/IP protocol has been used by most network devices. TCP/IP is designed

around a simple four-layer scheme. It does omit some features found under the OSI model.

Also it combines the features of some adjacent OSI layers and splits other layers apart.

The four network layers defined by TCP/IP model are as follows.

Table 15 Layer’s Examples

Layer TCP Layer TCP/IP suite

7 - Application HTTP, SMTP, SNMP, FTP, Telnet, NTP

6 - Presentation

5 - Session

Application

4 - Transport Transport TCP, UDP, ,

3 - Network Internet IP, ICMP,

Page 104: My Selection Course

Fundamental Programming (Java Basic) Network <Day4-1> Network programming with Java

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

104/198

Layer TCP Layer TCP/IP suite

2 - Data Link

1 - Physical

Network

Interface

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

Address

Size of Network

Part of Address

in Bits

Size of Host

Part of Address

in Bits

Default Mask for

Each Class of

Network

A 8 24 255.0.0.0

B 16 16 255.255.0.0

C 24 8 255.255.255.0

7.1.4. Subnet Masks Subnet masks are usually referred to net masks. They are used by TCP/IP to show which

part of an IP address is the network portion and which part is the host. For a pure Class A

network the netmask would be 255.0.0.0, for a Class B network the netmask would be

255.255.0.0, and for a Class C network the netmask would be 255.255.255.0. Netmasks

can also be used to deviate from the standard classes. By using customized netmasks, you

can subnet your network to fit your needs. For example, your network has a single Class C

address assigned to it. You have a need to subnet your network. Although this is not usual

in a normal Class C subnet mask, you can change the mask to break your network into

subnets.

7.2. Network programming with Java Java has standard library for network communication in the java.net package. This

Page 105: My Selection Course

Fundamental Programming (Java Basic) Network <Day4-1> Network programming with Java

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

105/198

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.

7.2.1. Internet resources The most important data about Internet resources on the network are IP address and host

name. “java.net” package has InetAddress class that works to obtain the host machine

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

7.2.2. URL resources URL (Uniform Resource Locator) represents the global address of resources in the Internet.

Page 106: My Selection Course

Fundamental Programming (Java Basic) Network <Day4-1> Network programming with Java

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

106/198

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.*; public class URLFile { static String c_strURL=" http://192.168.0.2/index.html"; public static void main(String[] args) { try { URL url = new URL(c_strURL); BufferedReader bf = new BufferedReader( new InputStreamReader(url.openStream())); String strLine; while((strLine=bf.readLine())!=null){ System.out.println(strLine); } }catch( IOException e ){ System.err.println( e.getMessage() ); } } }

As you see, since Java has all the function necessary for network connection in the

java.net package, you can make network communication program quite easy.

7.2.3. Client and Server program In the communication between programs, client-server model is widely applied. In this

model server is the program that is running and waiting for some requirement from client.

When the server accepts the client requirement, the connection between two programs is

established. Web server is an example of this model. To make server-client model, two

classes are designed: One for server and another for client.

Page 107: My Selection Course

Fundamental Programming (Java Basic) Network <Day4-1> Network programming with Java

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

107/198

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

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 { /** Port number for communication with host */ public static final int PORT = 1069; public static void main ( String args[] ) { try { //Socket socket = new Socket( "127.0.0.1", PORT);

Socket Socket Connection

Page 108: My Selection Course

Fundamental Programming (Java Basic) Network <Day4-1> Network programming with Java

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

108/198

Socket socket = new Socket(args[0], PORT); BufferedReader br = new BufferedReader(new InputStreamReader( socket.getInputStream() ) ); String strLine; while( ( strLine = br.readLine() ) != null ) System.out.println( strLine ); br.close(); socket.close(); } catch( ArrayIndexOutOfBoundsException e ) { System.err.println("Usage:java HostAddress hostname"); System.exit(-1); } catch( UnknownHostException e ) { System.err.println( "Host not found" ); System.exit(-1); } catch( SocketException e ) { System.err.println("Socket Error"); System.exit(-1); } catch( IOException e ) { System.err.println("IO Error"); System.exit(-1); } } }

- 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.*;

Page 109: My Selection Course

Fundamental Programming (Java Basic) Network <Day4-1> Network programming with Java

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

109/198

public class SocketServer { /** Port number for communication with client */ public static final int PORT = 1069; public static String c_strHello="Hello, You are connecting with "; public static void main ( String args[] ) { try { ServerSocket serverSocket = new ServerSocket( PORT ); while( true ) { Socket socket = serverSocket.accept(); String strHostName = socket.getInetAddress().getHostName(); Date date = new Date(); c_strHello += strHostName + " at " + date.toString(); System.out.println( c_strHello ); // send message to the client PrintWriter pw = new PrintWriter( new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))); pw.println(c_strHello); pw.close(); } }catch( SocketException e ) { System.err.println("Socket Error"); System.exit(-1); } catch( IOException e ) { System.err.println("IO Error"); System.exit(-1); } } }

- 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

Page 110: My Selection Course

Fundamental Programming (Java Basic) Network <Day4-1> Network programming with Java

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

110/198

accept another client requirement.

[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"

Page 111: My Selection Course

Fundamental Programming (Java Basic) Network <Day4-1> Exercise 7: Network Programming

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

111/198

7.3. Exercise 7: Network Programming 1. Write a program "HostInfo.java" in the textbook and check how the Internet Resources

are obtained by the InetAddress class.

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.

3. Write two programs "SocketClient.java" and "SocketServe.javar" in the textbook. Check

how the client-server program works in your own machine. Also check if the socket

communication is possible with your classmates on the different machine.

� 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

Figure 22 YaST Control Center

3) Select "Allowed Services". Click "Advanced…" button to set Additional allowed

Page 112: My Selection Course

Fundamental Programming (Java Basic) Network <Day4-1> Exercise 7: Network Programming

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

112/198

Ports.

4) Set the port number you want to open.

Figure 23 Firewall Configuration

5. Go to "Next" to confirm the settings.

4. Create two programs "SocketClientSendReceive.java" and

"SocketServerSendReceive.java". Client Socket will require some file to the server

which will send you back its content. Follow the instructions;

[SocketClientSendReceive.java] 1) Get from console the following parameter arguments;

- Host address of Server

- Port of Server

- File name which content you want to receive from server.

2) Connect to the server with the required Host address and port of Server.

3) Send the file name to the server.

4) Read the content of the file sent back from the server and print out to the console the

Page 113: My Selection Course

Fundamental Programming (Java Basic) Network <Day4-1> Exercise 7: Network Programming

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

113/198

content of the file.

5) close the socket connection.

[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.

Figure 24 Socket Send Receive Program

1) Open Socket 127.0.0.1:1070

2) Connect to the server

3) Send file name

5) Send back the content of "Hello.html"

6) Read the file content sent back from the server and Print out.

4) Read the file content.

Hello.htm

7) Close the connection.

Client Server

7) Close the connection.

Page 114: My Selection Course

Fundamental Programming (Java Basic) Nested Classes <Day 4-2> Nested Classes

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

114/198

8. Nested Classes <Day 4-2>

8.1. Nested Classes Java supports class nesting; the Java compiler allows one class to appear inside another

class. Nested class may be defined since the class is only used by one other class.

The classes are classified as follows;

├ Top level classes │ ├ Nested class ├ Inner class │ ├ Local class ( = Local Inner Classes ) │ ├ Non static member class │ └ Anonymous inner class └ static nested class

[Example of classes] class TopLevelClass { // Top level class static class StaticInnerClass {} // static inner class class InnerClass {} // Non static member class

static { class StaticInitializerLocalClass {} // Local class } static void staticMethod() { class StaticMethodLocalClass {} // Local class Runnable AnonymousClassInstance = new Runnable() { // Anonymous class public void run() {} }; } void method() { class MethodLocalClass {} // Local class } }

Page 115: My Selection Course

Fundamental Programming (Java Basic) Nested Classes <Day 4-2> Nested Classes

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

115/198

[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.

8.1.1. Top level class Top level class is not nested, but possibly sharing the same *.java file. The first class name

should concide with the file name.

[ClassOne.java] class ClassOne { } class ClassTwo }

8.1.2. Nested class Nested class means that there is a class inside a class, just like Russian dolls. It refers to

either static or inner class.

class Outer { void someOuterMethod(){ } public class Inner { void someInnerMethod(){ } } static class StaticInnerClass { void someStaticInnerMethod() } }

Page 116: My Selection Course

Fundamental Programming (Java Basic) Nested Classes <Day 4-2> Nested Classes

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

116/198

8.1.3. Non static member class Non static nested classes are always allocated in conjunction with some particular instance

of the outer class object.

class Outer { void someOuterMethod(){ } // the following is the non static inner class public class Inner { void someInnerMethod(){ } } public void someAnotherOuterMethod(){ // you can instantiate Inner directly Inner in = new Inner(); in.someInnerMethod(); } /* * Note that the main method is static. You need to instantiate the * the own class */ public static void main(String[] args) { Outer outer = new Outer(); Outer.Inner in = outer.new Inner(); in. someInnerMethod(); } }

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.

Page 117: My Selection Course

Fundamental Programming (Java Basic) Nested Classes <Day 4-2> Nested Classes

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

117/198

- 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 (); } } }

[example of private inner class] class Outer { // the following inner class is declared as private private class Inner { } Inner in = new Inner(); // OK if called from inside } 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.

8.1.4. static nested class static nested classes have the marking static and are allocated independently of any

particular outer class object

class Outer {

Page 118: My Selection Course

Fundamental Programming (Java Basic) Nested Classes <Day 4-2> Nested Classes

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

118/198

public static class InnerStatic { void someInnerMethod(){ } } void someOuterMethod(){ InnerStatic inner = new InnerStatic(); inner.someInnerMethod(); } /* * Note that although the main method is static, You do not need * to instantiate the own class */ public static void main(String[] args) { InnerStatic inner1 = new InnerStatic(); inner1.someInnerMethod(); } } /* * if you call from outside */ class Another { public void AnotherClassMethod(){ Outer.InnerStatic outer1 = new Outer.InnerStatic(); outer1.someInnerMethod (); } }

To instantiate a new nested static from inside the outer class;

InnerStatic ns = new InnerStatic ();

To instantiate a new nested static from outside the outer class

Outer.InnerStatic ns = new Outer.InnerStatic ();

[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.

Page 119: My Selection Course

Fundamental Programming (Java Basic) Nested Classes <Day 4-2> Nested Classes

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

119/198

[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.

8.1.5. Local inner class Local inner class is a named inner class defined in the middle of a method.

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; public class NestedLocal extends JFrame { /** * @param args */ public static void main(String[] args) { NestedLocal myAnonymous = new NestedLocal(); myAnonymous.pack(); myAnonymous.setVisible(true); } public NestedLocal() { super("NestedAnonymous"); class MyListener implements ActionListener{ public void actionPerformed(ActionEvent e){ System.out.println("click"); } } JButton button = new JButton("click"); button.addActionListener( new MyListener()); getContentPane().add(button); } }

The class that is interested in processing an action event especially in GUI application has

the following procedures;

6) implements the ActionListener interface.

Page 120: My Selection Course

Fundamental Programming (Java Basic) Nested Classes <Day 4-2> Nested Classes

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

120/198

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"); } }

Then MyListener is generated as a parameter of addActionListener to register action event

of button.

button.addActionListener( new MyListener());

[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.

Page 121: My Selection Course

Fundamental Programming (Java Basic) Nested Classes <Day 4-2> Nested Classes

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

121/198

8.1.6. anonymous inner class Anonymous inner class is an unnamed inner class defined in the middle of a method. This

class does not have the class name nor "class" keyword.

[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; public class NestedAnonymous extends 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); } }

Page 122: My Selection Course

Fundamental Programming (Java Basic) Nested Classes <Day 4-2> Nested Classes

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

122/198

The addWindwListener() is the method of java.awt.Window that needs parameter of

WindowAdapter (abstract class) implemented class. it adds the specified window listener to

receive window events from this window. In this case the anonymous class is created to

override the windowClosing() method of WindowAdapter abstract class.

addWindowListener( new WindowAdapter(){ public void windowClosing(WindowEvent we){ System.exit(0); } });

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!"); } });

Executing the NestedAnonymous.class the following window appears;

;

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

Page 123: My Selection Course

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

separately since it is not worthy.

- When you want to change the behavior of some class, but just locally without necessity to

be called in other case, you can use anonymous class to override the method.

[example] // change the behavior of ArrayList ArrayList list = new ArrayList() { public boolean add(Object o){ remove(o); System.out.println("The element duplicated"); return super.add(o); } }

Page 124: My Selection Course

Fundamental Programming (Java Basic) Nested Classes <Day 4-2> Exercise 8 Nested Classes

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

124/198

8.2. Exercise 8 Nested Classes

1. Execute "NestedAnonymous.java" on your machine. Explain what kind of inner class is

used there and how.

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

Page 125: My Selection Course

Fundamental Programming (Java Basic) J2SE5.0 New features <Day 4-2> Exercise 8 Nested Classes

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

125/198

9. J2SE5.0 New features <Day 4-2> The J2SE5.0 contains new features and enhancements in many functional areas. Some of

the new Java Language comprises the Ease of Development theme. The changes include

generic types, metadata, autoboxing, an enhanced for loop, enumerated types, static

import, C style formatted input/output, variable arguments.

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>();

Enhanced for Loop This new loop process eliminates the troublesome of iterators and index variables when

iterating over collections and arrays.

for (Integer integer : list) { }

Autoboxing/Unboxing This facility eliminates the drudgery of manual conversion between primitive types (such as

int) and wrapper types (such as Integer).

Figure 25 - Autoboxing/Unboxing

Typesafe Enums This flexible object-oriented enumerated type facility allows you to create enumerated types

100 Integer(100)

Autoboxing

Unboxing

Page 126: My Selection Course

Fundamental Programming (Java Basic) J2SE5.0 New features <Day 4-2> Generics

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

126/198

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 }

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++) { } } testVarargs ("one", "two");

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.*; getContentPane().add(new JPanel(), CENTER);

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.

Let's see some of the important new features.

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

Page 127: My Selection Course

Fundamental Programming (Java Basic) J2SE5.0 New features <Day 4-2> Generics

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

127/198

with ClassCastException.

[C91PrevProgram.java] import java.util.HashMap; /** * Display the contents of HashMap using previous function. */ public class C91PrevProgram { public static void main(String[] args) { HashMap map = new HashMap(); map.put("one","one"); map.put("two","two"); // you have to cast the type from object to String String s1 = (String)map.get("one"); String s2 = (String)map.get("two"); System.out.println("s1 : " + s1 + ",s2 : " + s2 ); } }

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 { public static void main(String[] args) { // Declare the type of key and value of HashMap HashMap<String,String> map = new HashMap<String,String>();

Page 128: My Selection Course

Fundamental Programming (Java Basic) J2SE5.0 New features <Day 4-2> Generics

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

128/198

map.put("one","one"); map.put("two","two"); // Now you do not have to cast the type String s1 = map.get("one"); String s2 = map.get("two"); System.out.println("s1 : " + s1 + ",s2 : " + s2 ); } }

The differences with the previous function are:

The parameters of HashMap map were (object,object). In the new feature, if you specify

the parameter type as;

HashMap<String,String> map = new HashMap<String,String>();

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 { public static void main(String[] args) { HashMap<String,String> map = new HashMap<String,String>(); 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! System.out.println("s1 : " + s1 + ",s2 : " + s2 + ",i : " + i ); } }

Page 129: My Selection Course

Fundamental Programming (Java Basic) J2SE5.0 New features <Day 4-2> Generics

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

129/198

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

[How to create a class with parameter] You can create your own generic types with multiple dynamic data.

[C91GenericsParameter.java] public class C91GenericsParameter<T> { protected T t; public C91GenericsParameter (T t) { this.t = t; } public T getParam() { return t; } public void setParam(T arg) { t = arg; } }

To call your generics type class;

[C91GenericsParameterMain] public class C91GenericsParameterMain { /** * 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()); // call generics with Integer C91GenericsParameter<Integer> genInt = new

Page 130: My Selection Course

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

130/198

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.

9.2. For each sentence This enhanced for loop statement provide the new loop function while the elements exist,

quite similar to the for … each of Basic, or foreach of C# language.

9.2.1. What's new The next program shows previous style with for loop

[ForPrevious.java] import java.util.Iterator; import java.util.List; import java.util.ArrayList; public class ForPrevious { /** * For loop with previous style */ public static void main(String[] args) { List list = new ArrayList(); for (int i = 0; i < 10; i++) { list.add(new Integer(i)); } for (Iterator it = list.iterator(); it.hasNext();) { // you need the casting of object to Integer type

Page 131: My Selection Course

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

131/198

Integer integer = (Integer) it.next(); System.out.println(integer); } } }

The result is

0 1 2 3 4 5 6 7 8 9

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; public class ForGenerics { public static void main(String[] args) { // you need to specify the type for List class List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { list.add(new Integer(i)); } // you need to specify the type for Iterator class for (Iterator<Integer> it = list.iterator(); it.hasNext();) { // now you do not need to cast from object to Integer Integer integer = it.next(); System.out.println(integer); } }

Page 132: My Selection Course

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

}

Using extended for statement [ForExtended.java] import java.util.Iterator; import java.util.List; import java.util.ArrayList; public class ForExtended { public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { list.add(new Integer(i)); } // Here you can use the new feature of for statement for (Integer integer : list) { System.out.println(integer); } } }

The format of extended for each sentence is ;

for (FormalParameter : Expression) statement;

In FormalParameter some variable is described with its data type.

In Expression, the variable of the collection or array is described.

The above program also uses generics to declare ArrayList with Integer parameter. The for

statement specifies the data type of Integer for FormalParameter in stead of Object type.

9.2.2. Which object is target of For each The objects that Implement iterable interface allow an object to be the target of the

"foreach" statement such as;

- ArrayList

- Vector

- LinkedList

- TreeSet

Page 133: My Selection Course

Fundamental Programming (Java Basic) J2SE5.0 New features <Day 4-2> Enum

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

133/198

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; int iZero = ZERO; //OK int iOne = 1; //OK but unknown if it is ONE int iFive = 5; //Compile OK but unknown if the number // is defined in the class

The enum type of C/C++ is like;

typedef enum {ZERO, ONE, TWO, THREE, FOUR} number; number zero = ZERO; //OK number one = 1; //OK but unknown if it is ONE number five = 5; //Compile OK but unknown if the number // is defined in the class

Now in the new feature of Java, we can define the references as follows:

modifier enum type name {identifier, identifier,…}

9.3.1. example of enum [EnumNumber.java] /** * Example of enum function * */ public enum EnumNumber { ONE, TWO, THREE, FOUR, FIVE } class EnumExample { private EnumNumber number; private int iNum; public EnumExample(int iNum, EnumNumber number) {

Page 134: My Selection Course

Fundamental Programming (Java Basic) J2SE5.0 New features <Day 4-2> Enum

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

134/198

this.iNum = iNum; this.number = number; } public String toString() { return number + "=" + iNum; } public static void main(String[] args) { EnumExample enum1 = new EnumExample(1, EnumNumber.ONE); EnumExample enum2 = new EnumExample(2, EnumNumber.TWO); EnumExample enum3 = new EnumExample(3, EnumNumber.THREE); System.out.println(enum1); System.out.println(enum2); System.out.println(enum3); } }

[Results] ONE=1 TWO=2 THREE=3

� EnumExample.java has toString() method that is used with System.out.println() method;

9.3.2. benefits of enum Type safe so the error will be found not at the moment of run time but compiler informs

you type error.

You can use in switch statement

9.3.3. example of enum with switch statement Usually the switch statement permits only integer primitive type such as int or char. But the

enum type can be used for switch statement.

[EnumSwitch.java] /** * Enum sample with Switch statement * */ public static void main(String[] args) {

Page 135: My Selection Course

Fundamental Programming (Java Basic) J2SE5.0 New features <Day 4-2> Enum

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

135/198

EnumNumber num = EnumNumber.ONE; 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 result is obviously;

The number is 1

� 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.

9.3.4. Example of enum with for statement You can use extended for statement by way of values() method which returns each value in

the array.

[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

Page 136: My Selection Course

Fundamental Programming (Java Basic) J2SE5.0 New features <Day 4-2> Boxing/unboxing

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

136/198

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.

9.4.1. What's new What we needed in the previous version is;

int iNum = new Integer(10).intValue();

Integer integerNum = new Integer(iNum + 1);

Now we can omit the conversion method as follows;

int iNum = new Integer(10); //Integer type to int

Integer integerNum = iNum + 1; //int primitive type to Integer

Autoboxing means the automatic conversion from primitive type to wrapper class.

Auto-Unboxing means the automatic conversion from wrapper to primitive type.

9.4.2. How to use Collections can only hold object references, so you have to box primitive values into the

appropriate wrapper class (which is Integer in the case of int). When you take the object out

of the collection, you get the Integer that you put in; if you need an int, you must unbox the

Integer using the intValue method.

List<Integer> list = new ArrayList<Integer>(); list.add(new Integer(10));

With autoboxing function the above coding will be;

List<Integer> list = new ArrayList<Integer>(); list.add(10);

Page 137: My Selection Course

Fundamental Programming (Java Basic) J2SE5.0 New features <Day 4-2> Exercise 9: J2SE5.0 New features

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

137/198

9.5. 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;

public class PreviousFeatureArrayList {

public static void main (String[] args) {

// Instantiate ArrayList

ArrayList arrayList = new ArrayList();

// Set values

arrayList.add("a");

arrayList.add("b");

arrayList.add("c");

// Display the contents of ArrayList

Iterator it= arrayList.iterator();

while (it.hasNext()){

System.out.println("ArrayList contents: " + it.next());

}

}

}

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;

Page 138: My Selection Course

Fundamental Programming (Java Basic) J2SE5.0 New features <Day 4-2> Exercise 9: J2SE5.0 New features

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

138/198

public class PreviousFeatureHashMap {

public static void main(String[] args) {

HashMap hm = new HashMap();

hm.put("abc", new Integer(111));

hm.put("def", new Integer(222));

Iterator it = hm.keySet().iterator();

while (it.hasNext()) {

String strKey = (String) it.next();

int iValue = ((Integer) hm.get(strKey)).intValue();

System.out.println(strKey + "," + iValue);

}

}

}

3. Let's create an enum program that outputs the following results.

[Results of output]

One is 1 Two is 2 Three is 3 Four is 4 Five is 5

Fill the following two boxes to print out the above results.

[NewFeatureEnumNumber.java] public class NewFeatureEnumNumber { public enum Number { One(1),Two(2),Three(3),Four(4),Five(5); int iNum; // constructor. Set the parameter value to instance value. Number (int iNum){ this.iNum = iNum; } // output; One is 1 Two is 2 Three is 3 ... public String toString(){ return name() + " is " + iNum; } } public static void main(String[] args) {

Page 139: My Selection Course

Fundamental Programming (Java Basic) J2SE5.0 New features <Day 4-2> Exercise 9: J2SE5.0 New features

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

139/198

// for loop to output all the content of Number

for (Number num: Number.values()){ System.out.println(num); } } }

(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);

You have to create a constructor that accepts the int parameter.

Page 140: My Selection Course

Fundamental Programming (Java Basic) Java GUI (I) <Day 5> AWT

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

140/198

10. Java GUI (I) <Day 5>

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.

10.1.2. What is AWT AWT stands for Abstract Window Toolkit. The AWT is part of the core Java Foundation

Classes (JFC) -- the standard API for providing graphical user interfaces (GUIs) for Java

programs.

A class library contains the GUI such as display of window, button, graphic, etc. It is

included in the core Java package of java.awt.

From Java 1.2 another GUI toolkit called Swing was included. Swing is used more

popularly now for GUI toolkit.

[characteristics] 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.

Applet You can use AWT functions inside the Applet

Basic container components are provided The AWT was designed to provide a common set of tools for graphical user interface

design that work on a variety of platforms.

AWT components The AWT consists of components, both container and non-container ones (eg. Button,

Checkbox, Choice, ...) Container components (eg. Frame, Dialog, Window, Panel)

Page 141: My Selection Course

Fundamental Programming (Java Basic) Java GUI (I) <Day 5> AWT

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

141/198

control the layout of other components. As containers are themselves components, they

can be placed inside other containers.

Java core library it comes standard with Java technology. This means you do not need to install it.

10.1.3. Sample programs 1. Display just the frame

Figure 26 Display Frame with AWT

[AWTFrameTest.java] import java.awt.Frame; public class AWTFrameTest extends Frame { /** * Display just Frame using AWT */ private static final long serialVersionUID = 1L; public static void main(String [] args) { new AWTFrameTest(); } AWTFrameTest() { super("AWTFrameTest"); setSize(200, 100); //show(); // Java1.4 setVisible(true); // Java1.5 } }

• Import java.awt.Frame

[windowXP] [Linux Suse 10.2]

Page 142: My Selection Course

Fundamental Programming (Java Basic) Java GUI (I) <Day 5> AWT

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

142/198

• 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

Figure 27 - Display Button with AWT

[AWTButtonTest.java] import java.awt.Button; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class AWTButtonTest extends Frame { /** * Display button using AWT */ public static void main(String [] args) { new AWTButtonTest(); } AWTButtonTest() { super("AWTButtonTest"); setSize(200, 100); setLayout(new FlowLayout()); Button b1 = new Button("OK");

[windowXP] [Linux Suse 10.2]

Page 143: My Selection Course

Fundamental Programming (Java Basic) Java GUI (I) <Day 5> AWT

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

143/198

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); } });

addWindowListener() is a method of java.awt.Window, which requires

java.awt.event.WindowListener class as its parameter. This method adds the specified

window listener to receive window events from this window. You need to indicate the end of

the program by clicking the window's title bar button or by pull down menu, then close

command is sent to the windowClosing() method of WindowListener.

WindowListener is an interface where some 7 methods are declared. If you implement the

WindowListener directly to your Frame, you need to implement all the methods. To avoid it,

java.awt.event.WindowAdapter class is prepared which already implements all the methods

of WindowListener interface method. What you need is just to override the method you

want, in this case windowClosing() method.

Note that nested anonymous class is used to override the windowClosing() method of

WindowAdapter class.

Also you can declare a named class to reuse the process.

import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class MyExitWindowClosing extends WindowAdapter { public void windowClosing(WindowEvent evt) { System.exit(0); } }

Page 144: My Selection Course

Fundamental Programming (Java Basic) Java GUI (I) <Day 5> AWT

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

144/198

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

Figure 28 - Display Label with AWT

[AWTLabelTest.java] import java.awt.FlowLayout; import java.awt.Frame; import java.awt.Label; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class AWTLabelTest extends Frame { /** * Display label using AWT */ private static final long serialVersionUID = 1L; public static void main(String [] args) { new AWTLabelTest(); } AWTLabelTest() { super("LabelTest"); setSize(200, 100); setLayout(new FlowLayout()); Label l1 = new Label("This is label test");

[windowXP] [Linux Suse 10.2]

Page 145: My Selection Course

Fundamental Programming (Java Basic) Java GUI (I) <Day 5> AWT

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

145/198

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 TextField

TextField t1 = new TextField("Hello World!!");

CheckBox

Checkbox c1 = new Checkbox("OK?");

5. Event programming Clicking the button, appears the text “Hello”.

Figure 29 - Event programming with AWT

[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;

[windowXP] [Linux Suse 10.2]

Page 146: My Selection Course

Fundamental Programming (Java Basic) Java GUI (I) <Day 5> AWT

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

146/198

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); // Register action listener button.addActionListener(this); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); // set adequate window size pack(); // show the window //show(); //java1.4 setVisible(true); //java1.5 } /** * This method is called when the action event happens *

Page 147: My Selection Course

Fundamental Programming (Java Basic) Java GUI (I) <Day 5> AWT

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

147/198

*/ 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; public class AWTEventTestAnonymous extends Frame { /** * Event program of AWT using anonymous class

Page 148: My Selection Course

Fundamental Programming (Java Basic) Java GUI (I) <Day 5> AWT

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

148/198

*/ 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); // Register action listener using anonymous class button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { label.setText("Hello");; } }); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); // set the preferred size pack(); // show the window //show(); // Java1.4 setVisible(true); // Java1.5 } public static void main(String[] args) { new AWTEventTestAnonymous(); } }

Note that you do not have to implement separately the ActionListener interface.

Page 149: My Selection Course

Fundamental Programming (Java Basic) Java GUI (I) <Day 5> Swing

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

149/198

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] 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.

Programable Look and feel Each component's look (appearance) and feel (how it reacts to input events) is controlled

by a separate and dynamically replaceable implementation. This allows the look and feel of

all or part of a Swing-based GUI to change. you can get any supported look and feel on any

platform.

Swing has more sophisticated components than AWT Swing's components are far more extensive than that supplied by AWT. For example,

Swing provides the additional components such as tree, LayoutManagers, and events. For

controls, radio button, password field, slider, combo box, table, progress bar are added

which makes possible to create sophisticated window application.

Written entirely in Java Since they are written in pure Java, they run the same on all platforms, unlike the AWT

which is tied to the underlying platform's windowing system.

10.2.2. Why another GUI in the same java? [Problems of AWT]

primitive components AWT is a very simple tool kit with limited GUI components, layout managers, and events.

This is because Sun Microsystems decided to use a lowest-common denominator (LCD)

Page 150: My Selection Course

Fundamental Programming (Java Basic) Java GUI (I) <Day 5> Swing

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

150/198

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

Different look and feel Since AWT depended on host GUI peer controls to implement the GUI, the GUI looked and

-- more importantly -- behaved differently on different hosts. This resulted in a "write once,

run everywhere" (WORE) situation, which was less than satisfactory.

10.2.3. Sample programs of Swing 1. Display just the frame

Figure 30 - Swing Frame Test

[SwingFrameTest.java] import javax.swing.JFrame; public class SwingFrameTest extends JFrame { /** * Display just Frame with Swing */ public static void main(String [] args) { new SwingFrameTest(); } SwingFrameTest() { super("SwingFrameTest"); setSize(200, 100); //show(); setVisible(true); }

[windowXP] [Linux Suse 10.2]

Page 151: My Selection Course

Fundamental Programming (Java Basic) Java GUI (I) <Day 5> Swing

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

151/198

}

• 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

Figure 31 - Swing Button Test

[SwingButtonTest.java]

import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; public class SwingButtonTest extends JFrame { /** * Display button with Swing */ public static void main(String[] args) { new SwingButtonTest(); }

SwingButtonTest() { super("SwingButtonTest"); setSize(200, 100); // set layout of the components(center) getContentPane().setLayout(new FlowLayout());

[windowXP] [Linux Suse 10.2]

Page 152: My Selection Course

Fundamental Programming (Java Basic) Java GUI (I) <Day 5> Swing

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

152/198

// 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); } }

Swing has basically three components;

Top level container (such as JFrame) This is a basic component for main window.

Middle container (such as JPanel) This is a container to locate components

Controls (JLable, JButton, etc) Each GUI components such as button or label.

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.

Figure 32 - Location of components

The JFrame has various Panes as shown in the figure. The Content Pane is used to put

Top level container(JFrame)

Middle container

button Label

Middle container (JPanel)

Label

Page 153: My Selection Course

Fundamental Programming (Java Basic) Java GUI (I) <Day 5> Swing

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

153/198

various controls. To get the Cntent Pane of the JFrame, getContent() method is called.

Figure 33 - Pane of JFrame (from Sun Microsystems API Document)

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());

The button is created and added to the container.

JButton b1 = new JButton("OK"); getContentPane().add(b1);

4. Event programming Clicking the button appears the text “Hello”.

Figure 34 - Swing Test Event

[SwingTestEvent.java] import java.awt.GridLayout; import java.awt.event.ActionEvent;

[windowXP] [Linux Suse 10.2]

Page 154: My Selection Course

Fundamental Programming (Java Basic) Java GUI (I) <Day 5> Swing

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

154/198

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; public class SwingEventTest extends JFrame implements ActionListener { /** * Clickng the button, appears Hello with Swing */ 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); // Register action listener button.addActionListener(this); // Window Close event setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); //show(); setVisible(true); } public void actionPerformed(ActionEvent e) { // Event if (e.getSource().equals(button)) { label.setText("Hello");

Page 155: My Selection Course

Fundamental Programming (Java Basic) Java GUI (I) <Day 5> Swing

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

155/198

} } public static void main(String[] args) { new SwingEventTest(); } }

10.2.4. Pluggable Look and Feel 1. Look and Feel The architecture of Swing provides "look and feel" (L&F) of your application's GUI. "Look"

refers to the appearance of GUI widgets (more formally, JComponents) and "feel" refers to

the way the widgets behave.

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.

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

CDE/Motif

Look and Feel of X Window System.

The name of Look and Feel : com.sun.java.swing.plaf.motif.MotifLookAndFeel

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

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

Page 156: My Selection Course

Fundamental Programming (Java Basic) Java GUI (I) <Day 5> Swing

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

156/198

� 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.WindowsLookAndFeel"); 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; public class SwingTestLookFeel extends JFrame { /** * Change look and feel dinamically */ private static final long serialVersionUID = 1L; JButton btnHello; JButton btnLookFeel; JLabel label; public SwingTestLookFeel() { super("SwingEventTest"); setSize(500, 200);

Page 157: My Selection Course

Fundamental Programming (Java Basic) Java GUI (I) <Day 5> Swing

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

157/198

getContentPane().setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; // Create button to display hello btnHello = new JButton("name of L&F is "); getContentPane().add(btnHello); // Register action listener using anonymous class btnHello.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { label.setText(UIManager.getLookAndFeel().toString()); } }); // Change look and feel to motif btnLookFeel = new JButton("Change to motif"); getContentPane().add(btnLookFeel); // Register action listener using anonymous class btnLookFeel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { changeLookFeel(); } }); // Create label label = new JLabel(""); c.gridwidth = 2; c.gridx = 0; c.gridy = 1; label.setHorizontalAlignment(JLabel.CENTER); getContentPane().add(label, c); // Window Close event addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); setVisible(true); } // change the look and feel to Motif public void changeLookFeel() { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.Motif

Page 158: My Selection Course

Fundamental Programming (Java Basic) Java GUI (I) <Day 5> Swing

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

158/198

LookAndFeel"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (UnsupportedLookAndFeelException e) { e.printStackTrace(); } SwingUtilities.updateComponentTreeUI(this); } public static void main(String[] args) { new SwingTestLookFeel(); } }

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.MotifLookAndFeel");

The following code shows how to set the GridBagLayout for the Container.

getContentPane().setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL;

GridBagLayout is a sophisticated, flexible layout manager. It aligns components by placing

them within a grid of cells, allowing some components to span more than one cell.

The following figure is after clicking the left button to display the name of current look and

feel.

Figure 35 - Test Look and Feel of Metal

Page 159: My Selection Course

Fundamental Programming (Java Basic) Java GUI (I) <Day 5> Swing

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

159/198

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.

Figure 36 - Test look and feel of Motif

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; public class SwingButtonTestDecoration extends JFrame { /** * Display button with Swing with Window Decoration */ private static final long serialVersionUID = 1L; public static void main(String[] args) { // Set Window Decoration of look and feel JFrame.setDefaultLookAndFeelDecorated(true); new SwingButtonTestLookFeel(); }

Page 160: My Selection Course

Fundamental Programming (Java Basic) Java GUI (I) <Day 5> Swing

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

160/198

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); } }

(note) The method setDefaultLookAndFeelDecorated () is static of the JFrame class.

(note) The method should be called before the Frame is generated.

Figure 37 - Swing Window Decoration of Look and Feel

[windowXP] [Linux Suse 10.2]

Page 161: My Selection Course

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

10.3. Exercise 10: AWT and Swing

1. Write a program "AWTEventTest.java" and "SwingEventTest.java" in the textbook.

Compare how they are displayed on your machine. If you have Microsoft Window

environment, also compare the display in each environment.

2. Write a program named "SwingExerciseLookFeel.java" that displays the different look

and feel when the radio button is selected as shown in the next figure.

Figure 38 - Display Look & Feel

� You can use javax.swing.JRadioButton to create radio button.

� You can use javax.swing.ButtonGroup to put all the radio buttons in a group.

[example]

// Create check box group ButtonGroup group = new ButtonGroup(); group.add(metalButton);

Page 162: My Selection Course

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

162/198

11. Java GUI (II) <Day 6>

11.1. SWT with Eclipse 11.1.1. What is SWT SWT (Standard Widget Toolkit) is a completely independent Graphical User Interface (GUI)

toolkit from IBM. It is created for their new Eclipse Integrated Development Environment (IDE) and now maintained by the Eclipse Foundation. SWT delivers native widget

functionality for the Eclipse platform in an operating system's independent manner.

[characteristics] 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/

use native components SWT call native API by way of JNI(Java Native Interface). It works quite quick and

light.

Platform native look and feel The platform native look and feel is provided since SWT calls OS native API to draw.

Not pure Java Since SWT uses JNI, it is not pure Java, which requires the common library to execute in

each platform. Almost main platform such as Windows, Linux, Solaris, Aix, HP-UX Mac are

supported.

11.1.2. Why SWT IBM began work on SWT, because Swing was still immature and sometimes the following

problems were found;

- Swing is slow

- Swing starts slow

- Swing is not native looking enough

- Swing is too complicated

Page 163: My Selection Course

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

163/198

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:

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.

Figure 39 - The AWT Way

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.

JRE for Windows

JRE for Linux

Java Core

Library

Motif Manager

Window Manager

(MFC, Win32, etc)

Native Peer

code(C/C++)

for Linux

Native Peer

code(C/C++)

for Windows

Page 164: My Selection Course

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

164/198

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

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 .

Figure 40 The SWT Way

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

SWT for

Linux

Motif Manager

Window Manager

(MFC, Win32, etc)

Call Native API (written C/C++) for Linux

Call Native API (written in C/C++) for Windows

SWT for

Windows

Page 165: My Selection Course

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

165/198

Java,

Since the SWT implementation is different for each platform, a platform specific SWT (JAR

file) must be distributed with each application.

11.1.3. How to install (Quoted From Eclipse SWT Manual) First, download the .zip of SWT for your platform from the SWT homepage

http://www.eclipse.org/swt/. For Linux you can select swt-3.2.1-gtk-linux-x86.zip.

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.

Figure 41 Import SWT in Eclipse Direct the wizard to the location where you downloaded the .zip file. This will create a

project called org.eclipse.swt in your workspace.

Page 166: My Selection Course

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

Figure 42 Import SWT zip in Eclipse

Your Java projects can then add the SWT project as a dependency. Open the properties

dialog of your Java project by clicking the right button of the mouse, and on the Java Build

Path page, include the org.eclipse.swt project.

Page 167: My Selection Course

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

167/198

Figure 43 Set SWT to Build Path in 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".

Page 168: My Selection Course

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

168/198

Figure 44 Set SWT Native Library in Eclipse

11.1.4. HelloWorld SWT application The next program displays "SWTHello World" in the label and explains the basic structure

of SWT programming.

[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; public class SWTHelloWorld { public static void main(String[] args) { // (1) Construct display Display display = new Display(); // (2) Create Shell Shell shell = new Shell(display); // Set title of the window

Page 169: My Selection Course

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

169/198

shell.setText("SWTHelloWorld"); // Create Label to display the message Label label = new Label(shell, SWT.CENTER); label.setText("Hello world from SWT"); label.pack(); shell.pack(); // (3) Display shell shell.open(); // (4) Event loop while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } // (5) dispose of Display display.dispose(); } }

(1) Construct Display The Display serves as a bridge for the connection between SWT and the underlying

platform's operating system. The information of the platform event loop and control

communication between the UI thread and other threads.will be acquired by way of this

class

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.

(2) Create Shell A Shell is widget to draw a "window" managed by the OS platform window manager. Top

level shells are created as a child of the display passing the display parameter. Using the

Also there is secondary shells which are created as a child of another shell. These windows

are typically used as dialog windows or other transient windows that only exist in the

context of another window.

(3) Display Shell

Page 170: My Selection Course

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

170/198

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.

(4) Event loop readAndDispatch() method of the Display class reads an event from the operating system's

event queue, dispatches it appropriately, and returns true if there is potentially more work to

do, or false if the caller can sleep until another event is placed on the event queue. The

sleep() method causes the user-interface thread to sleep (that is, to be put in a state where

it does not consume CPU cycles) until an event is received or it is otherwise awakened.

Generally the event loop is executed until the window is closed to read and notify the

message from the window. You can describe the same code in any program.

(5) Dispose of Display SWT requires that you explicitly free any OS resources that you have allocated. In SWT,

the Widget.dispose() method is used to free resources associated with a particular toolkit

object.

In this case You are required to call dispose() method for Display object once you create it.

If not, some memory leek problem may occur.

(note) Do not forget that SWT uses Java Native Interface, which means that the java

garbage collection will not work for SWT widgets.

[The result of SWTHelloWorld]

Figure 45 - HelloWorld with SWT

The following code shows how to create Label control;

// Create Label to display the message Label label = new Label(shell, SWT.CENTER);

[windowXP] [Linux Suse 10.2]

Page 171: My Selection Course

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

171/198

label.setText("Hello world from SWT");

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;

Parent container

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.

You can use the style bit with OR(" | ") ;

Text text = new Text(shell, SWT.BORDER | SWT.V_SCROLL)

If there is no style;

Text text = new Text(shell, SWT.NULL)

11.1.5. Sample program of SWT 1. Example program The following example shows how to put widgets on the composite and how to code Event

programming in SWT. If the button is clicked, appears a file dialogue screen and you can

choose a file from a directory.

[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; public class SWTEvent { private Shell shell; private Text textBox;

Page 172: My Selection Course

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

172/198

private Button button; private String fileName; // extension for file dialogue private final String[] EXTENSIONS = { "*.csv", "*" }; public Shell open(Display display) { shell = new Shell(display); shell.setText("SWTEvent"); shell.setLayout(new GridLayout(1, false)); // Generate a Composite to place widgets Composite comp = new Composite(shell, SWT.NO_FOCUS); comp.setLayout(new GridLayout(4, true)); GridData gridData = new GridData(); gridData.horizontalAlignment = SWT.FILL; gridData.verticalAlignment = SWT.FILL; comp.setLayoutData(gridData); // Create Label Label label1 = new Label(comp, SWT.NULL); label1.setText("Specify the csv address File "); // Create Text Box textBox = new Text(comp, SWT.SINGLE | SWT.BORDER); textBox.setText(""); GridData textGrid = new GridData(); textGrid.horizontalAlignment = GridData.FILL; textGrid.horizontalSpan = 2; textBox.setLayoutData(textGrid); // 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; }

Page 173: My Selection Course

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

173/198

// Open file dialogue private void getOpenFileName() { FileDialog openDialog = new FileDialog(shell, SWT.OPEN); openDialog.setFilterExtensions(EXTENSIONS); fileName = openDialog.open(); } /** * @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(); } }

The result of SWTEvent.java;

Figure 46 - SWT Event program

Clicking the search file button, and appears the following file dialogue screen to select file

from the directory.

Page 174: My Selection Course

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

174/198

Figure 47 - File dialogue 2. Define Layouts SWT has the standard layouts to determine the style of widgets;

Table 17 - Layouts of SWT Layouts Purpose

FillLayout Lays out controls in a single row or column, forcing them to be the same size.

FormLayout Configure the left, top, right and bottom edges of each child by using FormAttachments. Possible to configure complex layout.

GridLayout Positions the children by rows and columns in a grid. The most popular layout.

RowLayout Places the children simply either in horizontal rows or vertical columns.

The following code shows that the GridLayout style is set to shell.

shell.setLayout(new GridLayout(1, false));

The GridLayout takes the following parameters;

GridLayout(int numColumns, boolean makeColumnsEqualWidth)

The "numColums" decides the number of columns, and "makeColumnsEqualWidth"

determines whether or not the columns should be forced to have the same width.

[Running the Example Launcher] You can run the examples of SWT from Eclipse's Window menu. Select Show View >

Other. In the Show View dialog, expand "SWT Layouts" to see the Layout examples.

Page 175: My Selection Course

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

175/198

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

The following code shows the layout of the Composite;

// Generate a Composite to place widgets Composite comp = new Composite(shell, SWT.NO_FOCUS); comp.setLayout(new GridLayout(4, true)); GridData gridData = new GridData(); gridData.horizontalAlignment = SWT.FILL; gridData.verticalAlignment = SWT.FILL; comp.setLayoutData(gridData);

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

Page 176: My Selection Course

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

176/198

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.

Figure 48 SWT event loop

asyncExec(Runnable)

This is an asynchronous method of Display class that Causes the run() method of the

disposed?

event?

Process the Event

Sleep

exit

No

Yes

If the process takes time, the next event should wait long time

Page 177: My Selection Course

Fundamental Programming (Java Basic) Java GUI (II) <Day 6> Visual Editor

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

177/198

Runnable to be invoked by the user-interface thread. It should be used when the

application needs to perform some UI operations asynchronously without depending upon

the operations to be completed before the next processing. For example, a background

thread that updates a progress indicator or redraws a window could request the update

asynchronously and continue with its processing.

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.

11.2. Visual Editor 11.2.1. What is Visual Editor The Visual Editor is an open source graphical editor that helps you design applications that

have a graphical user interface (GUI). The provided components allow for visually editing

java classes, in particular visual classes. The java component is integrated with the Eclipse

java graphical editor so that changes in either are reflected between them immediately.

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

11.2.2. How to download and install VE 1. Download software you can download the version of VE that matches your installation of Eclipse from

Page 178: My Selection Course

Fundamental Programming (Java Basic) Java GUI (II) <Day 6> Visual Editor

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

178/198

http://download.eclipse.org/tools/ve/downloads/index.php.

Figure 49 Download Visual Editor

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

2. Install Software manually Exit Eclipse and unzip into the directory that eclipse is installed into. For example, if you

have Eclipse application installed into "/usr/share/eclipse/", you would unzip the

Page 179: My Selection Course

Fundamental Programming (Java Basic) Java GUI (II) <Day 6> Visual Editor

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

179/198

downloaded zip file into "/usr/share/eclipse/ ".

Restart Eclipse. Go to Help->About Eclipse Platform->Feature Details. Check if everything

is installed.

3. Install Software by Update Manager You can also download necessary software through Update Manager if you have Internet

connection as explained in the VE FAQ;

1) Go to Help->Software Updates->Find and Install...

2) Select the Search for New features to install... and hit the Next button

3) Click on New Remote Site... button, and add this site (name it VE):

http://update.eclipse.org/tools/ve/updates/1.0

4) Click on New Remote Site... button, and add this site (name it EMF):

http://update.eclipse.org/tools/emf/updates

5) Click on New Remote Site... button, and add this site (name it Old Eclipse):

http://update.eclipse.org/updates/3.0

6) Select VE, EMF, and Old Eclipse, and Hit Finish

7) Select the mirrors to use as they are asked for

8) Expand the tree VE->VE->Visual Editor SDK 1.2, and hit the checkbox on it

9) Expand EMF tree, EMF->EMF SDK 2.2.0->EMF SDK 2.2.0 and hit the checkbox on it

10) Expand Old Eclipse->GEF 3.2->Graphical Editing Framework 3.2 and hit the checkbox

on it

11) Hit Next, accept the licenses, hit Next, hit Finish

11.2.3. How to create project 1)Create a Java project.

2) Add SWT to the build path of Java project

(1) Select the project and open the property window right clicking the mouse.

(2) Select Java Build path in the left panel of the property window. Select Library

tag from the right Window and click "Add Library".

Page 180: My Selection Course

Fundamental Programming (Java Basic) Java GUI (II) <Day 6> Visual Editor

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

180/198

Figure 50 Create VE Project;Set Build Path for SWT

(3) Select the Standard Widget Toolkit (SWT) from Add Library window and click

Next button.

Page 181: My Selection Course

Fundamental Programming (Java Basic) Java GUI (II) <Day 6> Visual Editor

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

181/198

Figure 51 Create VE Project;Add Library of SWT

(4) Select IDE Platform and check "Include support for JFace library" and finish it.

Page 182: My Selection Course

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

Figure 52 Create VE Project;SWT Library Options

The SWT library is included in the Java Build Path libraries.

Page 183: My Selection Course

Fundamental Programming (Java Basic) Java GUI (II) <Day 6> Visual Editor

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

183/198

Figure 53 Create VE Project;SWT Build Path completed

11.2.4. How to create a Visual Editor class The wizard generates new visual classes based on a few quick selections.

To create a new Java visual class for use in the visual editor for Java:

1. In the Java perspective, click File > New > others > java > Visual Class. The New Java

Visual Class wizard opens.

Page 184: My Selection Course

Fundamental Programming (Java Basic) Java GUI (II) <Day 6> Visual Editor

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

184/198

Figure 54 Create VE Class

The New Java Visual Class windows opens. Set the following information to create a new

class.

Page 185: My Selection Course

Fundamental Programming (Java Basic) Java GUI (II) <Day 6> Visual Editor

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

185/198

Figure 55 Create VE Class; New Java Visual Class

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

2

3

4 5

10

9

8

76

13

11

12

14

Page 186: My Selection Course

Fundamental Programming (Java Basic) Java GUI (II) <Day 6> Visual Editor

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

186/198

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)

The following visual editor will be displayed;

Page 187: My Selection Course

Fundamental Programming (Java Basic) Java GUI (II) <Day 6> Visual Editor

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

187/198

Figure 56 Create VE Class; Editor

The VE is composed of the following views;

- Graphical editor You can edit graphically the widgets in this panel. Select the Widgets from the

pallet and place them in this editor. Right clicking the mouse, the popup menu for that

widget will appear. You can select "event" -> "widgetSelected" to define the behavior of the

event.

- 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

Graphical editor

Source editor

Property editor

Pallet

Page 188: My Selection Course

Fundamental Programming (Java Basic) Java GUI (II) <Day 6> Visual Editor

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

188/198

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.

How to open the existing java class with Visual editor;

If you have not made the visual editor for Java the default editor for .java files, you can still

open Java classes in the visual editor.

To open an existing Java class in the visual editor for Java:

1. In the Package Explorer view of the Java perspective, select the .java source file

for the class that you want to edit in the visual editor.

2 Right-click and select Open With > Visual Editor from the pop-up menu. The

workbench remembers your editor choice for this file until you choose a different editor.

How to run a Visual Class;

You can create any Visual Class selecting the syle in the new Visual Class. For Example if

you select "Composite", a class that inherits Composite class will be created. You can run it

as Java Beans right-clicking the java file -> "Run As" -> "Java Bean".

Page 189: My Selection Course

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

Figure 57 Create VE Class; How to run Visual Class

Page 190: My Selection Course

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

190/198

11.3. 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.

2. Create a VE project named VEPrg.

3. Create a Visual class named VEFileViewer.java. Create the program that shows the

following image using Visual editor.

Figure 58 Exercise 3 of Visual Class

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.

Page 191: My Selection Course

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

191/198

Figure 59 Exercise 4 of Visual Class

5. Add Event proram in the "File Load" button. If the file exists, display the content of the

file in the text area.

Page 192: My Selection Course

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

192/198

Figure 60 Exercise 5 of Visual Class

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.

Page 193: My Selection Course

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

193/198

Figure 61 Exercise 6 of Visual Editor � Create Canvas control to show the content of .jpg file.

� When the load button is clicked, image object is created by file. Then call the redraw()

method of canvas object;

image = new Image(sShell.getDisplay(),strFilename); canvas.redraw();

� 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); } }});

Canvas

.jpg file

Page 194: My Selection Course

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

Page 195: My Selection Course

Fundamental Programming (Java Basic) Tables and Figures Figures

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

195/198

Tables and Figures

11.4. Figures

11.5. Tables

Table 1 Primitive types ................................................................................................20

Table 2 Escape Sequences.........................................................................................24

Table 3 operators ........................................................................................................24

Table 4 arithmetic operators ........................................................................................25

Table 5 Increment and Decrement ..............................................................................26

Table 6 Widening.........................................................................................................27

Table 7 Relational operators........................................................................................28

Table 8 Logical operators ............................................................................................29

Table 9 Wrapper class and primitive type....................................................................49

Table 10 Iterator method .............................................................................................51

Table 11 - Time standard.............................................................................................55

Table 11 Access modifier ............................................................................................63

Table 12 access control...............................................................................................75

Table 13 Methods of File class (from Sun Microsystems Java API documentation)..100

Table 14 Layer’s Examples .......................................................................................103

Table 15 Class A, B, and C Networks: Network and Host Parts and Default Masks .104

Table 16 - Layouts of SWT........................................................................................174

Table 17 Software version for VE -............................................................................178

Page 196: My Selection Course

Fundamental Programming (Java Basic) Indexes Keywords

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

196/198

Indexes

11.6. Keywords

abstract, 65

abstract class, 71

access modifier, 65

anonymous inner class, 123

Arithmetic operator, 27

array, 48

ArrayList, 55

assignment operator, 32

asyncExec, 179

Autoboxing/Unboxing, 127

AWT, 142

behavior, 64

blocked, 85

Boxing/unboxing, 138

break, 44

BufferedReader, 96, 98, 100

BufferedWriter, 101

Byte Code, 12

cast, 30

class, 64

classpath, 18

Collection, 52

comment, 33

Comment, 16

comments, 213

concatenation, 33

conditional operator, 32

constructor, 69

continue, 45

decrement operator, 27

do loop, 44

Eclipse, 18, 246

element, 208

Enhanced for Loop, 127

exception, 46

extends, 71

File, 102

File.separator, 102

FileInputStream, 99

FileOutputStream, 100

FileWriter, 100

final, 65

For each, 132

Garbage Collection, 12

Generics, 127, 128, 129

GUI, 142

Page 197: My Selection Course

Fundamental Programming (Java Basic) Indexes Keywords

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

197/198

HashMap, 53

HTTP, 108

IDE, 18

if statement, 37

IllegalMonitorStateException, 88

implements, 72

import, 67

increment operator, 27

IndexOutOfBoundsException, 49

InetAddress, 107

inheritance, 70

InputStream, 93, 108

instance, 67

instanceof, 32

interface, 72

IP Address, 106

Iterator, 53

java.io package, 92

java.io.Exception, 98

java.io.FileNotFoundException, 99

java.lang package, 97

java.lang.Runnable, 83

java.lang.Thread, 83

java.net, 109

java.net package, 106

java.util package, 52

JIT, 12

JVM, 12, 18, 50

life cycle of a thread, 85

List, 52

Local inner class, 121, 122

logical operator, 30

main, 11, 66

Map, 53

message, 64

Metadata (Annotations), 128

method, 64, 68

method modifier, 68

Nested class, 116, 117

Non static member class, 116, 118

notify(), 87

notifyAll(), 87

NullPointerException, 26

NumberFormatException, 61

object, 64

object oriented language, 11

Operator, 26

operators precedence, 33

OSI, 105

OutputStream, 93

overloading, 70

overriding, 74

package, 16, 66

polymorphism, 75

port, 109

Primitive types, 22

PrintStream, 101

Page 198: My Selection Course

Fundamental Programming (Java Basic) Indexes Keywords

S-FS-C-1.0 Fundamental Programming (Java Basic) – ICTTI, Union of Myanmar

198/198

PrintWriter, 101

property, 64

Reader, 96

readLine(), 98

Reference types, 21

relational operator, 30

Reserved Keywords, 25

return, 45

run(), 84

runnable, 85

Runnable interface, 84

shift operator, 32

sleep(), 87

socket, 109

start(), 84

static, 65

Static Import, 128

static nested class, 118, 119, 120

static variable, 75

stop(), 87

stream, 92

Subnet Masks, 106

super(), 74, 84

suspend(), 87

SVG, 241

Swing, 151

switch statement, 38

SWT, 165

synchronization, 88

System.err, 97

System.in, 97

System.out, 97

System.out.println(), 16

TCP/IP, 105

thread, 81

throws, 68

Top level class, 117

Typesafe Enums, 127

UnknownHostException, 107, 110

URL, 107

Varargs, 128

variable, 21

Visual Editor, 180

wait(), 88

while loop, 43

widening, 28

Writer, 96, 100

yield(), 86