demonstration of java jdk, netbeans, tomcat and java db

46
2014-11-08 1 02-An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 1 Object Oriented Programming and Internet Application Development Unit 2 An Internet Language: Java Basics Introduction to object-oriented programming Introduction to Java programming language Performing numeric operations and using the standard input/output Modeling objects by classes Control structures part one selection Control structures part two - repetition COMP S801 COMP S801 02 An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 2 Demonstration of Java JDK, NetBeans, Tomcat and Java DB Installation of Java Platform Java Development Kit (JDK), NetBeans (including Tomcat and JavaDB Derby) by referring to steps in the following document. file:///C:/Users/lc/Downloads/comps801_Installation%20of%20Java%20JD K%20NetBeans%20Tomcat%20JavaDB.pdf Using NetBeans Customize NetBeans configurations (Projects/Files/Services, Toolbar, Tab Size) Create a new Java project (Create a Java class and format source code, Run it, Close & Open project) Open existing project: download project TMA01Skeleton, MT801-Unit2 at this link, open them. Start and stop Tomcat, Java DB (will be used in later study units)

Upload: others

Post on 16-Oct-2021

24 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

1

02-An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 1

Object Oriented Programming and

Internet Application Development

Unit 2 An Internet Language: Java Basics

• Introduction to object-oriented programming

• Introduction to Java programming language

• Performing numeric operations and using the standard

input/output

• Modeling objects by classes

• Control structures – part one – selection

• Control structures – part two - repetition

CO

MP

S801

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 2

Demonstration of Java JDK,

NetBeans, Tomcat and Java DB • Installation of Java Platform Java Development Kit (JDK),

NetBeans (including Tomcat and JavaDB Derby) by referring to

steps in the following document.

• file:///C:/Users/lc/Downloads/comps801_Installation%20of%20Java%20JD

K%20NetBeans%20Tomcat%20JavaDB.pdf

• Using NetBeans

• Customize NetBeans configurations (Projects/Files/Services, Toolbar, Tab Size)

• Create a new Java project (Create a Java class and format source code, Run it, Close

& Open project)

• Open existing project: download project TMA01Skeleton, MT801-Unit2 at this link,

open them.

• Start and stop Tomcat, Java DB (will be used in later study units)

Page 2: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

2

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 3

Object-Oriented Programming • Analyze the problem by writing a program based on entities or

objects involved in the problem.

• Each object class (or entity) is characterized by its attributes (or

states, i.e. its data it possesses) and its behaviors (or operations).

• Object class, attribute (or state): noun in the problem statement

• Behavior (or operation): verb in the problem statement

Object class

example

Attributes (or states)

of the object class

Behaviors (or operations)

of the object class

Bank account Account number, account name,

balance, etc.

Withdraw, deposit, etc.

Human Eye color, hair color, height, weight, etc. Walk, talk, run, etc.

Car Brand, model, seat no, exterior color,

etc.

Start, stop, accelerate,

decelerate, etc.

CD Player Brand, color, etc. Play, pause, stop, forward,

backward, adjust volume,

etc.

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 4

Features of Object-Oriented Programming

• Some object classes consist of components which are replaceable,

extensible. Examples of components of object class are:

• These components are also object classes.

• Because they have also attributes and behaviors

• The relationship between the object class and its components is

“has-a” relationship.

• E.g. Car has battery, door, frame, etc.

Object class Components of the object class

CD Player Motor, disc, digital panel, digital-audio converter, etc.

Car Battery, door, frame, engine, gearbox, air-conditioner, steering system,

suspension system, wheels, tires, etc.

Computer Keyboard, monitor, CPU, memory block, hard disk, fan, etc.

Page 3: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

3

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 5

Benefits of Software Development

Using Object-Oriented Approach • To solve a problem easily, break down it by visualizing it as

manageable modules (or objects).

• The determined modules are extensible, replaceable and

reusable. By reusing existing modules, the productivity of

programmers and the reliability of software are improved. It

is possible to reuse modules developed by other software

developers.

• Java Software Development Kit (SDK) provides Java

developers with Java standard Application Programming

Interface (API) to re-use and extend. Java API has a standard

set of commonly used Java classes.

• Search ‘Java API’ in Google, e.g. see this link.

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 6

Classes and Objects

• Object classes (or classes) contains attribute and behaviors.

• Object classes can be tangible or intangible.

• Tangible: Car

• Intangible: Bank account

• Object instances (or objects) are examples of object classes.

• An object class (or Class) is a group of object instances (or objects).

• Examples

Object class (or Class) Object instance (or Object)

Bank account Your bank account, my bank account, etc.

Human You, me, etc.

Car Your BMW 320i, his Toyota Corolla, etc.

CD Player Your Sony CD player, his Panasonic CD player, etc.

Page 4: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

4

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 7

Messages and Methods

• Object classes’ behavior is modeled by method of Java classes

• 2 types of methods

• Class method: the method of object class

• Instance method: the method of object instance

• Object performs some operations (or behaviors) if it receives the

corresponding message.

• It is one-to-one mapping between message and object’s behavior. So the

name of message is the same as the name of behavior.

Unified

Modeling

Language

(UML)

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 8

Object Attributes and Instance Variables

• In real world, every object possesses its attributes.

• E.g. each bank account has an attribute “balance”.

• In Java

• An object of type Account has instance variable “balance”.

• One-to-one mapping between object attribute and instance variable.

Object

Reality

Attributes of the object Object

Java

Instance variable

Bank account Account number,

balance, etc.

BankAccount bc accountNumber, balance,

etc.

Human Eye color, hair color,

height, weight, etc.

Human h eyeColor, hairColor,

height, weight, etc.

Car Brand, model, seat no,

Exterior color, etc.

Car c brand, model, seatNo,

exteriorColor, etc.

CD Player Brand, color, etc. CDPlayer cd brand, color

Page 5: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

5

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 9

Java Programming Language

• An object-oriented programming language selected in this course

to implement the object oriented concepts.

• 5 phases of Java programming

• edit → compile → load → verify → execute

Phase Software used What happens?

Edit Editor e.g. NetBeans,

Notepad

Create Java source program. e.g. Welcome.java

Compile Compiler Generate Java bytecode, Welcome1.class from source

program, Welcome1.java by running “javac

Welcome1.java” to generate bytecode “Welcome1.class”

Load Class loader Load the bytecode into primary memory

Verify Bytecode verifier Ensure the bytecode is valid and do not violate Java’ s

security restrictions

Execute Java Virtual Machine

(JVM)

Execute the bytecode, “java Welcome1”

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 10

Java Virtual Machine (JVM)

• Java Virtual Machine (JVM) is part of the Java Development Kit

(JDK). It is a software application that simulates a computer but

hides the underlying operating system and hardware from the

programs that interacts with it.

• JVM is invoked by “java”.

• Achieve phase “load → verify → execute” by running “java

Welcome1”

• Write-once-run-everywhere

• Write a java program Welcome1.java and generate its bytecode

Welcome1.class once (e.g. in Windows).

• Welcome1.class can be run on any platform (e.g. in Unix,

Linux, Mac environment) without re-compiling it again.

Page 6: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

6

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 11

Welcome1.java in Unit 2 p.11

• Explanations of Fig 2.3

• Involve caller class, Welcome1 and called class, PrintStream.

• out is object instance of class, PrintStream.

• Welcome1 sends a message println() to PrintStream.

• Println() displays a message “Welcome to Java Programming” on the

standard output, i.e. console or screen.

• Message invocation mechanism

• Caller class Welcome1 sends a message println() with arguments “Welcome to

Java Programming” to called class PrintStream.

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 12

Naming Convention in Fig 2.3

• Convention of Fig 2.3

• Class name starts with uppercase letter. When class name has more than 1

words. Each word starts with a uppercase letter.

• E.g. Welcome1, PrintStream

• Object name starts with lowercase letter, like this objectName:ClassName

• E.g. out:PrintStream

• Message name starts with lowercase letter

Page 7: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

7

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 13

2 Types of Errors in Java Program

1. Syntax error: error reported by Java compiler during editing or

compilation.

• e.g. missing semicolon after each statement

• Analogy: English sentence has grammar and spelling rules.

• “I eat an epple” is wrong in spelling.

• “I eats an apple” is wrong in grammar.

2. Semantic error (or program bug, logic error): wrong in meaning of

the program. Java compiler will not find it.

• E.g. System.out.printf(“sum of 2 and 3 is %f\n”, 2 – 3);

• Analogy: wrong meaning in English sentence although there are no

grammar and spelling mistakes.

• E.g. “An apple eats me” is wrong in meaning.

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 14

Java Application Programming Interface

(API)

• Java API is a rich collection of existing classes and methods in the

Java class libraries.

• You can search class, its constructors, class and/or instance

methods defined in the API.

• Java JDK 7 API web site is at

• http://download.oracle.com/javase/7/docs/api/

• Try to search method println() of class PrintStream in the above

web site.

• As we cannot remember all classes and their methods defined in

the API, we need to search this web site from time to time.

Page 8: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

8

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 15

Steps of Object Manipulations

1. Object declaration

2. Object creation (or object instantiation)

3. Object initialization

4. Message sending

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 16

Object Declaration

• Declare an object of a particular class

• Syntax: <ClassName> <objectName>

• E.g. GradeBook myGradeBook;

Page 9: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

9

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 17

Object Creation (or Object Instantiation)

• Create an object of the class in the heap memory.

• Syntax

• new <ClassName>(<arguments>);

• Usually it combines the object initialization statement.

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 18

Object Initialization

• Assign an initial value of object reference to an object

reference variable.

• Syntax

• <objectName> = new <ClassName>(<arguments>);

• <ClassName> <objectName> = new <ClassName>(<arguments>);

• Example 1 (better approach)

• GradeBook myGradeBook = new GradeBook();

• Example 2 (clumsy approach but equivalent to Example 1)

• GradeBook myGradeBook;

• myGradeBook = new GradeBook();

Page 10: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

10

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 19

Object Creation Diagram Fig 2.4

• GradeBook myGradeBook = new GradeBook();

• Interpretations:

1. Check if heap memory has extra memory block to store an GradeBook

object.

2. If yes, return an object reference to the beginning address of this memory

block.

3. Assign the object reference to myGradeBook via assignment operator, =.

4. myGradeBook stores the object reference to the memory block for

GradeBook object.

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 20

Garbage Collection (GC)

• Examples:

• GradeBook myGradeBook;

• myGradeBook = new GradeBook(); // 1st GradeBook object

• myGradeBook = new GradeBook(); // 2nd GradeBook object

• Interpretations:

• myGradeBook first points to the 1st GradeBook object.

• myGradeBook then points to the 2nd GradeBook object. At any time,

myGradeBook can only refer to one object.

• The 1st GradeBook object is then lost as it is impossible to locate it again.

• The memory for the 1st GradeBook object will be released back to heap

memory by garbage collection process, i.e. garbage collector.

• Garbage collector regularly monitors heap memory, reclaims memory

occupied by objects that are no longer in use (i.e. objects has no object

reference on it).

Page 11: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

11

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 21

Sending Message

(or Calling a Method of an Object) • Syntax

• <objectName>.<methodName>(<arguments>);

• Example

• myGradeBook.displayMessage();

• Calling the displayMessage () method of a GradeBook object

will output the message ‘Welcome to Java programming’.

• Analogy

• Electric circuit of CD player sends a ‘start’ message to the CD

motor.

• Electric circuit does not need to understand how motor works.

• Motor must understand the ‘start’ message, else it cannot spin.

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 22

Structure of Java Source File - Comment

• Java source file is a “.java” file that contains the Java source

program.

• Source file means that program under editing.

• Comments: English description used to explain the program.

• 3 type of comments

Comment type Example

Block comment or multi-line comment /* multi-line

comment */

Single-line comment // single-line comment

Javadoc comment /**

javadoc comment, javadoc will use this

comment to generate comment similar to

Java API documentation. For details, please

check Appendix M of textbook */

Page 12: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

12

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 23

Structure of Java Source Code - Package

• Classes are grouped into packages with the following purposes.

1. Class names can be defined in hierarchical way. E.g. To define student in

OUHK BA and OUHK ST schools, we can use ouhk.ba.Student and

ouhk.st.Student.

2. Classes in the same package are logically related. ouhk.st.Staff and

ouhk.st.Student are 2 classes in ouhk.st package. To use them, we can use

either method below.

• import ouhk.st.*; // method 1: import all classes in ouhk.st package

• import ouhk.st.Staff; // method 2: import 2 classes

import ouhk.st.Student;

3. Use of package resolves name conflict. E.g. ouhk.st.Staff and ouhk.ba.Staff

are 2 different classes defined in ouhk.st package and ouhk.ba package

respectively.

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 24

Structure of Java Source Code - import

• “import” statement lets compiler know that classes defined in other

package will be used in this program.

• Rules of “import” statements

1. Import statement must occur before any class definition in the source file.

2. The order of import statement is insignificant.

• import ouhk.st.Staff; // method 1: import Staff first

import ouhk.st.Student;

• import ouhk.st.Student; // method 2: import Student first

import ouhk.st.Staff; // same as method 1

3. The no. of import statements has no performance impact on the program.

• import ouhk.st.*; // method 1: import all classes in package ouhk.st

• import ouhk.st.Staff; // method 2: import 2 classes

import ouhk.st.Student;

4. Every program has an implicit (i.e. hidden) import, i.e. import java.lang.*;

Page 13: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

13

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 25

Structure of Java Source Code - class

• A Java source file (i.e. .java file) usually defines a single class.

• The class name must match the file name. E.g. Welcome1.java

must have a class named “Welcome1”.

• Syntax of defining a class

public class <ClassName> {

}

• Syntax of a method inside class

<modifier> <return type> <methodName>(<parameters>) {

<method body>

}

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 26

Structure of Java Source Code - main

• Main class

• Software application usually consists of many classes.

• Define one class as main class in NetBeans. This class is the first executing

class when clicking ‘run’ button.

• Main method

• The first method in the main class to run.

• Syntax of main() method

public static void main(String[] args) {

<method body>

}

• Remember main() method temporarily, its details will be explained

later on.

Page 14: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

14

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 27

Simple Input-Process-Output Programs

• Run HelloEveryone.java in project MT801-Unit2 in NetBeans

• Input statement, e.g. showInputDialog()

• Process statement, e.g. String greeting = “Hello, “ + name + “.”;

• Output statement, e.g. showMessageDialog()

• Terminate the program explicitly by System.exit(0).

• This method terminates the currently running Java Virtual

Machine.

• This method is only necessary if your program uses the

JOptionPane class for getting user entry or showing messages.

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 28

Data Types

• 2 data types are

• Primitive types: 8 built-in data types.

• Reference types: non-primitive types.

• Syntax of declaring a variable

• <data type> <variable name>;

• Variable’s data type is one of the following.

• Primitive type: e.g. int anInt;

• Reference type: e.g. String str;

Page 15: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

15

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 29

8 Primitive Types

• Usually, int is used for integer, double is used for real numbers.

• Blue primitive types are numeric types.

Primitive

type

Content Default value Memory size

required

Range

byte Integer 0 1 byte -27 to 27 - 1

short Integer 0 2 bytes -215 to 215 - 1

int Integer 0 4 bytes -231 to 231 - 1

long Integer 0L or 0l 8 bytes -263 to 263 – 1

float Real 0.0F or 0.0f 4 bytes Broader than long

double Real 0.0, 0.0D or 0.0d 8 bytes Broader than float

boolean False/True false Platform dependent false, true

char Character ‘\u0000’ 2 bytes ‘\u0000’ to ‘\uffff’

(or 0 to 65,535)

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 30

Variable Declaration and Initialization

• Syntax

• <data type> <variable name> = <initial value>;

• Examples

int value1 = 100; // value1 is primitive-type variable

int value2 = value1;

String message1 = "Hello"; // message1 is reference-type variable

String message2 = message1;

Page 16: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

16

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 31

3 Types of Operators

• Expression of 3 types of operators (see OperatorExample.java in my web site)

• Unary operator: either <operator><operand> or <operand><operator>

• Binary operator: <operand1> <operator> <operand2>

• Ternary operator: <operand1><operator><operand2><operator><operand3>

Operator type Operator Description Operator

Unary Sign, Increment, Decrement +, -, ++, --

Logical !

Binary Arithmetic +, -, *, /, %

Relational >, >=, <, <=, ==, !=

Logical (or conditional) &&, ||

Arithmetic/Assignment =, +=, -=, *=, /=, %=

Ternary If/else ?:

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 32

Arithmetic Operators

• Data type of arithmetic expression result is numeric types.

• *, /, % precede +, -.

Arithmetic

operators

Arithmetic expression examples

+ Addition: -2 + 3 is 1

- Subtraction: 2 – 5 is -3

* Multiplication: 2 * 3 is 6

/ Integer division: 3 / 2 is 1,

Floating point division: at least one is float

• 3/2.0, 3.0/2 or 3.0/2.0 is 1.5

• ((float)3) /2 or ((double)3)/2 is 1.5

% Modulus (or remainder): 3 % 2 is 1, 6 % 3 is

0

Page 17: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

17

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 33

Data Type of Arithmetic Expression Result

• For different combinations of operand types

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 34

Relational Operators

• Data type of relational expression result is boolean.

• Equality operator (==) Vs Assignment operator (=)

1. == is equality operator;

2. = is assignment operator.

Relational

Operators

Relational expression examples

> a > b is true if a is greater than b; false otherwise

< a < b is true if a is less than b; false otherwise

>= a >= b is true if a is greater than or equal to b; false otherwise

<= a <= b is true if a is less than or equal to b; false otherwise

== a == b is true if a is equal to b; false otherwise

!= a != b is true if a is not equal to b; false otherwise

Page 18: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

18

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 35

Logical (or Conditional) Operators

• Data type of logical expression is boolean.

• 2 logical values in Java are true and false.

Logical

Operators

Logical expression examples

&&

(i.e. AND)

a && b gives true only if both a and b are true.

||

(i.e. OR)

a || b gets false only if both a and b are false.

!

(i.e. NOT)

! a will negate the value of a.

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 36

Assignment/Arithmetic Operators

• Common ones are

Assignment/Arithmetic

Operator

Assignment/arithmetic expression examples

+= a += b equivalent to a = a + b

-= a -= b equivalent to a = a - b

*= a *= b equivalent to a = a * b

/= a /= b equivalent to a = a / b

%= a %= b equivalent to a = a % b

Page 19: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

19

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 37

Assignment/Arithmetic Operator - Advanced

• Syntax expr1 op= expr2

• Equivalent to expr1 = (expr1) op (expr2)

• Where expr1 and expr2 are expressions • op can be +, -, *, /, %;

• Right-hand side expression is in implicit parenthesis

• e.g. x *= y + 1 means x = x * (y + 1) rather than x = x * y + 1

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 38

Increment Operator (++)

• Increment operator (++)

– means that adds 1 to the operand.

– can only be applied to variables, e.g. (x+y)++ is illegal.

– 1. pre-increment: ++x

• Increment 1 to x, then use x. e.g.

int x = 0;

System.out.printf(“%d\n”, ++x); /* x = 0 + 1, then shows 1 */

System.out.printf(“%d\n”, ++x + 1); /* x = 1 + 1, then shows 3 */

– 2. post-increment: x++

• Use x, then increment 1 to x. e.g.

int x = 0;

System.out.printf(“%d\n”, x++); /* shows 0, then x = 0 + 1 */

System.out.printf(“%d\n”, x++ + 1); /* shows 2, then x = 1 + 1 */

Page 20: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

20

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 39

Decrement Operator (--)

• Decrement operator (--)

– means that subtracts 1 from the operand.

– can only be applied to variables, e.g. (x+y)-- is illegal.

– 1. pre-decrement: --x

• Decrement 1 from x, then use x. e.g.

int x = 3;

System.out.printf(“%d\n”, --x); /* x = 3 - 1, then shows 2 */

System.out.printf(“%d\n”, --x + 1); /* x = 2 - 1, then shows 2 */

– 2. post-decrement: x--

• Use x, then decrement 1 from x. e.g.

int x = 3;

System.out.printf(“%d\n”, x--); /* shows 3, then x = 3 - 1 */

System.out.printf(“%d\n”, x-- + 1); /* shows 3, then x = 2 - 1 */

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 40

Operator Execution Order, PARL

• Precedence and associativity of operators (partial)

Increasing precedence

Operators Associativity

() left to right

! ++ --

pre-increment & pre-decrement

right to left

* / % left to right

+ - left to right

< > <= >= left to right

== != left to right

&& || left to right

= += -= *= /= %= right to left

++ --

post-increment & post-decrement

left to right

Parentheses

Arithmetic

operators

Relational

operators

Logical operators

Page 21: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

21

CO

MP

S801

02-LoopsAndLogic http://learn.ouhk.edu.hk/~t430860 41

Operator Execution Order: Precedence

• Precedence rule

• applies when operators of different precedence occur in an

expression. e.g. if

int x = 3, y = 3;

• List the order of execution and final value of y - ++x / 2

Order of execution is

1: ++x /* as pre-increment precedes / and - */

2: ++x / 2 /* as / precedes - */

3: y - ++x /2

• Final value is 1, you can use the following statement to verify the final

value of given expression.

System.out.printf("Final value=%d\n", y - ++x / 2);

CO

MP

S801

02-LoopsAndLogic http://learn.ouhk.edu.hk/

~t430860

42

Operator Execution Order: Associativity

• Associativity rule

• applies when operators of the same precedence occur in an

expression. e.g. if

int x = 3, y = 3;

• List the order of execution and final value of 2 expressions

Expression x + y – 2 x += y = 2

Order of

execution

1. x + y

2. x + y – 2

1. y = 2

2. x += y

Final value 4 (as left to right for + and -) 5 (as right to left for += and =)

Page 22: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

22

CO

MP

S801

02-LoopsAndLogic http://learn.ouhk.edu.hk/

~t430860

43

Operator Execution Order: Order of Evaluation

• Order of evaluation

• Java, C# defines left-to-right order of evaluation

• In C, order of evaluation is implementation dependent.

• List the order of execution and final value of this statement

int x = (1+2)>(3+4);

Assumption Left-to-right order

of evaluation

Right-to-left order

of evaluation

Order of

execution

1. (1+2)

2. (3+4)

3. (1+2)>(3+4)

4. x = (1+2)>(3+4)

1. (3+4)

2. (1+2)

3. (1+2)>(3+4)

4. x = (1+2)>(3+4)

Final value 0 0

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 44

Identifier

• Identifier is used to identify Java entity. It can be the following:

• Package

• Class

• Interface

• Method (instance method, class method)

• Variable (local variable, instance variable, class variable)

• Constant (local constant, instance constant, class constant)

• Identifier

• Must compose of letters, digits, underscore (_) and dollar sign ($).

• Can only start with letter, underscore (_) or dollar sign ($).

• Cannot contain white space (i.e. space, tab or <Enter>).

• Case-sensitive.

• Cannot be Java keyword (e.g. int, if, new, for, while, etc.)

Page 23: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

23

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 45

Identifier Naming Convention

• Use meaningful names for identifiers as far as possible.

Identifier Naming convention Naming examples for identifier

Package Use noun, lowercase java.lang

Class Use noun, uppercase letter for 1st

character of each word

SavingAccount

Interface ditto ditto

Method Use verb, lowercase except 1st

letter of 2nd words onwards

getInterestAmount()

Variable Use noun, same naming rule as

method.

curentHangSengIndex

Constant Use uppercase with underscore to

separate words

MINIMUM_BALANCE

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 46

Identifier Examples on Variables

• The following valid and invalid identifier examples are the same

for other identifiers such as package, class, etc..

Valid identifier examples Invalid identifier examples

int anIntVar; int anInt-Var; // - inside

char _charVar1; char 1stCharVar;

// digit as 1st letter

boolean aBool; boolean a Bool;

// space in variable name

float aFloat;

float afloat;

float int, case;

// int and case are keywords

Page 24: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

24

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 47

Numeric Computations with Math class

• java.lang.Math class defines many common mathematical

functions and 2 constants. Note: no need to import this

class. Do you know why? Answer: in “import” slide.

• To access methods and constants in Math class, use either

method below. <Class method name> and <class

constant> means static ones.

• Math.<class method name>(<arguments>)

• Math.<class constant>

• See MathExample.java in my web site.

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 48

Define Constant by Keyword ‘final’

• Use ‘final’ keyword in different context to define a read-

only entity that cannot be changed later.

Different types of

constants

Constant examples

Class constant: one

per class

public class Account {

// class constant

public static final double MIN_BAL = 1000.00;

// instance constant

private final double MORTGAGE_INTEREST = 0.05;

// parameter constant and local constant

public void getX(final float p) {

final int x = 1;

}

}

Instance constant: one

per object instance

Local constant or

parameter constant:

inside method

Page 25: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

25

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 49

Standard Input/Output

• Summarized below

• Example

• Standard output: OperatorExample.java and MathExample.java in project

COMPS801Unit2ExamplesBy430860

• Standard input: HelloConsole.java in project MT801-Unit2

Description Associated class

constant

Data type of class

constant

Standard

output

Screen output java.lang.System.out iava.io.PrintStream

Pre-created

Standard

input

Keyboard input or

console input

java.lang.System.in java.io.InputStream

Pre-created

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 50

Standard Output Methods

– print(), println() and printf() • 3 equivalent program segments to display “x=10” on screen.

• Explanations

• println(): print stuff and a new line afterwards.

• +: string concatenation if involves string.

• printf(): print stuff in formatted manner.

• %d: one format string, means decimal integer.

• \n: one escape sequence, means new line.

Program segment 1 Program segment 2 Program segment 3 int i = 10;

System.out.print(“x=“);

System.out.print(x);

System.out.println();

int i = 10;

System.out.println(“x=“+x);

int i = 10;

System.out.printf(“x=%d\n“,x);

Page 26: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

26

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 51

Format String in printf()

• Refer to http://download.oracle.com/javase/7/docs/api/, select

printf() in PrintStream class, and then select “Format String

syntax”.

• Common format string examples, the above URL has full list.

Format string Example Example output

%d System.out.printf(“%d”, 10); 10

%f System.out.printf(“%f”, 1.225); 1.225000

%.2f System.out.printf(“%.2f”, 1.225); 1.23

%c or %C System.out.printf(“%c, %C”, ‘h’, ‘h’); h, H

%b or %B System.out.printf(“%b, %B”, true, true); true, TRUE

%s or %S System.out.printf(“%s, %S”, “Hi”, “Hi”); Hi, HI

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 52

Escape Sequence in println() or printf()

• Escape sequence is \ <character>

• Denote special character that cannot be typed as text

• Common escape sequences

Escape sequence Meaning

\n newline, move the cursor to the leftmost position of the

next line

\r carriage return, move the cursor to the leftmost position of

the current line

\t horizontal tab, usually 8 spaces

\\ backslash

Page 27: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

27

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 53

java.util.Scanner for Input

• To wait user input through standard input, we can use methods

defined in class java.util.Scanner.

• Methods of Scanner class in Table 2.4 in Unit 2 p.36

• Example HelloConsole.java in project MT801-Unit.

• Example

import java.util.Scanner;

Scanner input = new Scanner(System.in);

System.out.print(“Enter your name: “);

String name = input.nextLine();

System.out.println(“Your name is “ + name);

// Output will be “Your name is Peter Wong” if the “Peter Wong” is inputted

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 54

Select Class or Object?

• Recap: a class is a group of objects.

• Selection criteria of class or object: Unit 2 p.42

• <visi>: visibility that can be public, protected, default or private

Select class Select object

When Attributes: same value for all objects

Behaviors: same value for all objects

Attributes: different value for different objects

Behaviors: different behaviors for different objects

Syntax // class variable to model attribute

<visi> static <data type> <vaName>;

// class method to model behavior

<visi> static <return type>

<methodName(<arguments) {

}

// instance variable to model attribute

<visi> <data type> <varName>;

// instance method to model behavior

<visi> <return type>

<methodName>(<arguments>) {

}

Example See jang.lang.Math in Java JDK 7 API

documentation URL

CurrencyCalculator.java in project MT801-Unit2

Page 28: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

28

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 55

Visibility (or Access Control)

• Now just focus on private and public mentioned in Unit 2 p.43.

• Public variable and methods: can be accessed anywhere

• Private variable and methods: can only be accessed within the

class.

• Visibility details mentioned in Unit 3 p.34 to p.36.

Visibility Same class Same package Subclass Anywhere

public Yes Yes Yes Yes

protected Yes Yes Yes No

default Yes Yes No No

private Yes No No No

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 56

Accessor (or Getter) and

Mutator (or Setter) Methods • Accessor method: a public instance method that gets value from a private data

member (I.e. private instance variable). Name is get<variableName>

• Mutator method: a public instance method that sets value into a private data

member (I.e. private instance variable). Name is set<variableName>

• Accessor method and mutator method usually comes in pairs. But if the data

member is read-only or write-only, it will have only accessor method or mutator

method.

• Example below. See also CurrencyCalculator.java in project MT801-Unit2.

public class Student {

private String studentId; // private data member

// Accessor method

public String getStudentId() { return this.studentId; }

// Mutator method

public String setStudentId(String studentId) { this.studentId = studentId; }

}

Page 29: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

29

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 57

Information Hiding and Encapsulation

• Information hiding refers to the states that are internal to an object

that are also inaccessible from the outside world.

• E.g. private data member “studentId” in previous slide, can only be

accessed via accessor and mutator methods.

• Encapsulation concerns hiding how the object performs its

operations but exposing what necessary operations could perform

to outside world.

• E.g. Public accessor and mutator methods of “studentId” in previous

slide. Other classes can use getStudentId() and setStudentId() but has

no concern how the implementation details of these 2 methods.

• Realize information hiding and encapsulation by marking

• Data members and internal methods as private

• Necessary methods that are called by other objects as public

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 58

Steps of Object Creation

(or Object Instantiation) • Steps of executing CurrencyCalculator1 cc = new CurrencyCalculator1(1.2);

1. Allocate memory space from heap memory for the new object.

2. Default initialization: a class variable and/or an instance

variable are initialized to 0 or null.

• exhangeRate is initialized to 0.0.

3. Explicit initialization: instance variable is initialized to its initial

value.

• exchangeRate has no initial value. Hence its value remains 0.0.

4. Execute constructor

• exchangeRate is changed to 1.2.

5. Return a reference to the new object in the heap memory.

• cc gets the reference to new object in the heap memory.

cc

A new object

in heap

Page 30: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

30

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 59

Default Initialization for

Class Variable and Instance Variable • Default value is assigned to class variable and instance variable

only based on their data types.

• Local variable must be explicitly initialized before use.

Data type Default value for class variable or instance variable

byte (byte) 0

short (short) 0

int 0

long (long) 0

float 0.0F

double 0.0

boolean false

char ‘\u0000’

Reference type null

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 60

Constructor (or Class Constructor) - I

• Syntax

<visibility> <ClassName> (<arguments>) {

}

• Notes:

• Usually <visibility> is public.

• No return type, hence no return value for the constructor.

• Statements in constructor are executed when this statement

is executed.

• new <ClassName>(<arguments>);

• See CurrencyCalculator1.java in project MT801-Unit2.

Page 31: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

31

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 61

Constructor (or Class Constructor) - II

• If the class has no constructor, the following default constructor is created

implicitly.

public <ClassName> () {

}

• If a class has its own constructor(s), it will have no default constructor. Hence,

CurrencyCalculator1.java has no default constructor. I.e. calling “new

CurrencyCalculator1()” will fail.

• See Borrower1.java in project MT801-Unit2. A Borrower1 object can be

created in either way below.

• new Borrower1();

• new Borrower1(10);

• A constructor can invoke another one, see Borrower2.java in project MT801-

Unit2.

• Keyword “this” refers to the current executing object.

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 62

Data Member, Local Variable and

Parameter • Digest Table 2.5 on comparison of data members, local

variable and parameters in Unit 2 p.51.

• Digest means that you can use your own language to

describe the table content.

• Data member: initialized automatically when created

• Instance variable (or member variable): exist for as long as

the object exists.

• Class variable (or static variable): created when the class is

loaded and continue to exist for as long as the class is loaded.

• Local variable (automatic, temporary or stack variable)

• Defined inside a method.

• Must be explicitly initialized.

Page 32: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

32

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 63

Scope of Variables - I

• Scope of a variable: the range of statements where the variable

could be read or updated.

• Example

public double getForeignForDollar(double dollar) {

fee = exchangeRate - feeRate;

amount = dollar * fee;

double amount, fee; //the third statement

return amount;

}

• Scope of parameter dollar is from the first statement to end of the

method, indicated by red arrow range.

• Scope of variable amount, fee goes from the third statement to end

of this method, indicated by blue arrow range.

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 64

Scope of Variables - II

• Parameter cannot use the same name as local variable.

• Why?

• Can define a local variable of the same name more than

once in the same method.

• e.g. TestLocalVars.java in project MT801-Unit2.

Page 33: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

33

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 65

Parameter Passing with Pass-by-value

• Pass-by-value mechanism means that parameter values

are copied from caller method to the called method.

• Value change in parameter value in the called method

will never change the parameter in the caller method.

• See ParameterPassing.java in project

COMPS801Unit2ExamplesBy430860

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 66

Keyword “this”

• Keyword “this” denotes the object that executes the

statement.

• Fig 2.15 Adder.java in Unit 2 p.54 shows examples on

“this”.

• If a method is called without the dot operator,

<methodName>(<arguments>);

• It is equivalent to

this.<methodName>(<arguments>);

Page 34: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

34

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 67

Mark Local Variable and Parameter as

Unchangeable (or Read-only)

• By adding keyword “final” in front of local variable and

parameter.

• Example public void addAndShow(final int x, final int y) {

final int sum = x + y;

showResult(sum);

}

• Adding “final” to ensure that local variable and

parameter will not be accidentally changed during

method execution.

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 68

Method Overloading

• To define overloaded methods, you need to define the

methods with different argument lists in terms of the

number of parameters and/or parameter types.

• See NumberAdder.java in project MT801-Unit2.

Page 35: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

35

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 69

Manipulating Objects with Methods

• Call a method with an object reference as

• Argument of the method using pass-by-value

mechanism. E.g. CurrencyCalculator calculator = new CurrencyCalculator();

...

System.out.println(calculator);

• Return value of the method <modifiers> <class type> <method name>(<arguments>) {

<statements>

}

• Objects can be created in <statements> and use “return”

statement to pass it to the caller method.

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 70

3 Basic Control Structures of Program

• Every program consists of a combination of the

following 3 control structures.

1. Sequence: statements are executed one by one in

sequence.

2. Selection (if/else, switch/case): select one path out

of 2 or more to execute.

3. Repetition (for, while, do/while, nested loop): a

block of code is executed for multiple times.

Page 36: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

36

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 71

Selection – if/else

• In English, you may say “If the green person traffic light is on, I

cross the road; otherwise I wait”.

• select one out of 2 paths based on the condition result.

• Java uses “if/else” to simulate the above selection.

• See CurrencyCalculator1.java in project MT801-Unit2.

if (<boolean condition>) {

// <boolean condition> is true

<then-statement block>

}

else {

// <boolean expression> is false

<else-statement block>

}

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 72

Selection – Nested if/else

• Used to select one out of multiple paths.

• See ControlStructure.java in project

COMPS801Unit2ExamplesBy430860

• Example if (var == <value 1>) {

... // block1

} else if (var == <value 2>) {

... // block2

} else if (var == <value 3>) {

... // block3

} else {

... // block-else

}

Page 37: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

37

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 73

Selection – Ternary Operator, ?:

• Syntax: condition ? expr1 : expr2 • Equivalent to

if (condition) /* () is required for if */ expr1 else expr2

• Example

z = a > b ? a : b; /* (a > b) is unnecessary */ /* z is assigned to the maximum of a and b */

• Personal feeling on if-else Vs ternary operator

• if-else is more readable when compared with this ternary operator.

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 74

Selection – switch/case

• Used to select one out of multiple paths.

• See ControlStructure.java in project

COMPS801Unit2ExamplesBy430860

• Syntax switch (<Integral or String expression>) {

case <label_1>:

<case body 1>;

break; /* control jumps to statement block A */

...

case <label_n>:

<case body n>;

break; /* control jumps to statement block A */

default:

<handle unmatched cases>

}

Statement block A;

Page 38: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

38

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 75

Selection – switch/case Syntax Notes

• Colon should be used after every case and default.

• If break is omitted, the following case will be executed as

well. This is called fall-through. Falling-through cases, if

used carelessly, may be disastrous.

• The label_1, …, label_n (i.e. only char, byte,

short, int, long, string are acceptable) in case-

part can only be integral constants or string literals. They

cannot be floating-point numbers.

• Exact match is used for switch case.

• case and default clause can occur in any order.

• switch can be nested with another switch and/or if-

else.

• <String expression> available from JDK 7 or later.

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 76

Selection – if/else Vs switch/case

• Limitations of switch • only integral values or string literals can be used in case

clauses. • the condition in switch is implicitly equality.

• Converting switch to if-else? • all switch structures can be re-written as if-else

structures.

• Converting if-else to switch? • not all if-else structures can be re-written to switch

structures because of limitations of switch. • e.g. if (a > 1.2) cannot be converted to switch.

Page 39: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

39

CO

MP

S801

02-LoopsAndLogic http://learn.ouhk.edu.hk/~t430860 77

Repetition - while

• Syntax initialization; /* initialize the loop condition */

while (<boolean condition>) {

<statement block T>; /* execute block T when expression is true */

update <boolean condition>; /* update the loop condition */

}

<statement block A>; /* executed block A when condition is false */

• Explanations • condition is evaluated before statement block T is executed.

• statement block T is executed as long as condition is true. If condition is false, statement block A will be executed.

• If (condition) is always true, the statement block A will be executed forever. That is, infinite loop occurs. Then the computer will hang up.

CO

MP

S801

02-LoopsAndLogic http://learn.ouhk.edu.hk/~t430860 78

Repetition - Example of while loop

• Program fragment to find the sum of 1 to 10. int sum = 0;

int j = 1; /* loop condition initialization */

while (j <= 10) {

sum += j; /* executed when (j <= 10) is true */

j++; /* varies the loop condition */

}

System.out.printf("sum=%d\n",sum); /* executed when j = 11 */

• Notes • sum += j; and j++; are executed for 10 times. When j becomes

11, (j <= 10) is false, then the loop is exited.

• while (j <= 11) is executed for 11 times.

• What will be result if j++ is omitted? Infinite loop!

• What will be the final value of sum if it is not initialized to 0?

Page 40: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

40

CO

MP

S801

02-LoopsAndLogic http://learn.ouhk.edu.hk/

~t430860

79

Repetition - for

• Syntax for (initialization; <boolean condition>; update) {

<statement block T> /* execute block T when condition is true */

}

<statement block A>; /* execute block A when condition is false */

• Execution sequence of for structure is the same as the

while structure.

• Notes

• Semi-colon, ';' is used to separate 3 parts in for structure.

• initialization and increment can contain multiple statements. But

<boolean expression> can have at most 1 statement.

• If initialization or increment has multiple statements, comma is used to

separate these statements.

CO

MP

S801

02-LoopsAndLogic http://learn.ouhk.edu.hk/~t430860 80

Repetition – Example 1 of for loop

• Program fragment to find the sum of 1 to 10

int sum;

int j;

for (sum = 0, j = 1; j <= 10; j++) {

sum += j; /* executed when (j <= 10) is true */

}

System.out.printf("sum=%d\n",sum); /* executed when j = 11 */

• Notes

• The initialization consists of 2 statements that are separated

by comma.

• This program fragment is equivalent to example of while structure

in previous slides.

Page 41: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

41

CO

MP

S801

02-LoopsAndLogic http://learn.ouhk.edu.hk/~t430860 81

Repetition – Example 2 of for loop

• Use for-loop to print “A C E G”

public static void main(String[] args) {

char c;

for (c=‘A’; c <‘H’; c+=2) {

System.out.printf(“%c “, c);

}

}

CO

MP

S801

02-LoopsAndLogic http://learn.ouhk.edu.hk/~t430860 82

Repetition -for Vs while

• Observations

• Sequence of evaluations in ‘for’ loop is i, c, s, u, c, s, u

, … provided condition c is true.

for (i; c; u) {

s;

}

• Every ‘for’ loop can be replaced by a ‘while’ loop (and

vise versa) because the above ‘for’ can be converted to

i;

while (c) {

s;

u;

}

Page 42: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

42

CO

MP

S801

02-LoopsAndLogic http://learn.ouhk.edu.hk/~t430860 83

Repetition – do/while

• Syntax initialization; /* initialize the loop condition */

do {

<statement block T>; /* execute block T at least once */

update <boolean condition>; /* update the condition */

} while (<boolean condition>);

<statement block A>; /* execute block A when condition is false */

• Notes • condition is evaluated after statement block T is

executed.

• statement block T is executed as least once.

CO

MP

S801

02-LoopsAndLogic http://learn.ouhk.edu.hk/~t430860 84

Repetition - Example of do/while loop

• Program fragment to find the sum of 1 to 10 int sum = 0;

int j = 1;

do {

sum += j;

j++;

} while (j <= 10);

System.out.printf("sum=%d\n",sum); /* executed when j = 11 */

• Notes

• This program fragment is equivalent to example of while

structure in previous slides.

Page 43: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

43

CO

MP

S801

02-LoopsAndLogic http://learn.ouhk.edu.hk/

~t430860

85

Repetition - while/for Vs do/while

• while structure or for structure

• If the condition is false at the beginning, the loop is NOT

entered.

• do-while structure

• Even if the condition is false at the beginning, the loop is

entered at least once.

CO

MP

S801

02-LoopsAndLogic http://learn.ouhk.edu.hk/~t430860 86

Repetition - break and continue

• Keyword break and continue act as modifiers

for repetition structure, for, while and do-

while.

• Statement break; when executed, will

• exit the immediate surrounding loop.

• Statement continue; when executed, will

• skip the statements behind keyword continue, and

then perform the next iteration of the loop.

Page 44: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

44

CO

MP

S801

02-LoopsAndLogic http://learn.ouhk.edu.hk/~t430860 87

Repetition - Example of break

public static void main(String[] args) {

int x;

for (x = 1; x <= 10; x++) {

if (x == 5)

break; /* exit the loop when x==5 */

System.out.printf("%d ", x);

}

System.out.printf("\nExit loop at x == %d\n",x);

}

• The program output is

1 2 3 4

Exit loop at x == 5

CO

MP

S801

02-LoopsAndLogic http://learn.ouhk.edu.hk/~t430860 88

Repetition - Example of continue

public static void main(String[] args) {

for (int x = 1; x <= 10; x++) {

if (x == 5)

continue; /* skip remaining when x == 5 */

System.out.printf("%d ", x);

}

System.out.printf("\nSkip printing the value 5\n");

}

• The program output is

1 2 3 4 6 7 8 9 10

Skip printing the value 5

Page 45: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

45

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 89

Repetition – Nested Loops

• Repetition construct: for, while, do/while can be nested.

• To make program readable, nested level had better to be

kept not greater than 3.

• Example of using nested for-loops to print a size-3

square of #. public static void main(String[] args) {

for (int y=0; y<3; y++) {

for (int x=0; x<3; x++)

System.out.print(“#”);

System.out.println(); // jump to next line

}

}

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 90

Java Reference - Java Language Tutorial

• Tutorial Web site http://download.oracle.com/javase/tutorial/java/index.html

• Tutorials cover the following topics

• Object-Oriented Programming Concepts

• Language Basics

• Class and Objects

• Interface and Inheritance

• Numbers and Strings

• Generics

• Packages

• Exercises and answers available for each topic.

Page 46: Demonstration of Java JDK, NetBeans, Tomcat and Java DB

2014-11-08

46

CO

MP

S801

02 – An Internet Language: Java Basics http://learn.ouhk.edu.hk/~t430860 91

Java Reference – Project Perform Java

• Written by course coordinator Dr Andrew Lui.

• Target readers are Java beginners.

• Available for download at

http://learn.ouhk.edu.hk/~mt258/performjava/PerformFra

me.htm

• Click “Exercise” at the top

• Several perform Java exercises and solutions there.

• Will use some time of Surgery session to discuss some

perform Java topics.