Sunteți pe pagina 1din 145

Principles of

Programming Languages

Review
Introduction to Java
Lecture outline (1)
● Java programming environment
● Basic program structure
● Variables and types
● Operations on primitive types
● Array
● String
● Enum

Duc L. M. FIT325 2
Lecture outline (2)
● Text input/output
● Flow of control
● Program development

Duc L. M. FIT325 3
1 Java programming environment

● Java programming language


● Java platform
● Java virtual machine (JVM)
● Java Application programming interface (API)

Duc L. M. FIT325 4
Brief history (1)
● Initial goal: to build software for networked
consumer devices, supporting:
● multiple host architectures
● secure delivery of software

Duc L. M. FIT325 5
Java platform
● A software-based
platform in which
Java programs
run
● Runs on top of
other hardware-
based platforms,
e.g. Windows,
Linux, etc.

Duc L. M. FIT325 6
Brief history (2)
● Similar in syntax to C/C++:
● but omits complex, confusing, unsafe features
● Supported by web browsers via extensions:
● Java programs are “embedded” in HTML pages
● Design and architecture decisions drew from
Eiffel, SmallTalk, Objective C, and Cedar/Mesa

Duc L. M. FIT325 7
Language features
● Simple, object oriented, familiar
● Robust and secure
● Architecture neutral and portable
● High performance
● Interpreted, threaded, and dynamic

Duc L. M. FIT325 8
Deploying a Java program

● The JVM
makes Java
programs
portable to
different
platforms

Duc L. M. FIT325 9
Java Application programming
interface (API)
● API is a collection of ready-made software
components that provide useful capabilities
● Grouped into libraries known as packages

Duc L. M. FIT325 10
2 Basic program structure

● What is it?
● Class
● Package

Duc L. M. FIT325 11
What is it?
● Physically, a program is a collection of one or
more .java files
● A .java file typically contains one class (but
more are possible)
● Logically, a program is a collection of classes
● Related classes are grouped into packages

Duc L. M. FIT325 12
Class
● A Java's language construct
● Defines the basic program units and data types
(later)
● A named container for program instructions:
● variables
● procedures (called methods)
● other classes
● Things defined in a class are called members
● with some exceptions (later)

Duc L. M. FIT325 13
Method main
● The executable method of a program
● A program typically has one main method
● defined in the main class
● other classes may also have this method
● Pre-defined header
public static void main(String[] args)

● argument args can be changed

Duc L. M. FIT325 14
Example: program Greeting.java
/**
* OVERVIEW: This is a basic Java program which prints a greeting
* message on the standard output console
*
* @author dmle
*
*/
// program (application) class
class Greeting {
/**
* The default method to be invoked from the command-line
* @param args input parameters
*/
public static void main(String[] args) {
// prints a greeting message to the standard output console
System.out.println("hello world!");
} // end main
} // end Greeting

Duc L. M. FIT325 15
Class
/**
* OVERVIEW: This is a basic Java program which prints a greeting
* message on the standard output console
*
* @author dmle
* The main class
*/
// program (application) class
class Greeting {
/**
* The default method to be invoked from the command-line
* @param args input parameters
*/
public static void main(String[] args) {
// prints a greeting message to the standard output console
System.out.println("hello world!");
} // end main
} // end Greeting

Duc L. M. FIT325 16
Method main
/**
* OVERVIEW: This is a basic Java program which prints a greeting
* message on the standard output console
*
* @author dmle
*
*/
// program (application) class
class Greeting { the main
/** method
* The default method to be invoked from the command-line
* @param args input parameters
*/
public static void main(String[] args) {
// prints a greeting message to the standard output console
System.out.println("hello world!");
} // end main
} // end Greeting

Duc L. M. FIT325 17
Documentation comments
/**
* OVERVIEW: This is a basic Java program which prints a greeting
* message on the standard output console
*
* @author dmle
*
*/
// program (application) class
class Greeting {
/**
Documentation
-type
* The default method to be invoked from the command-line
* @param args input parameters comments
*/
public static void main(String[] args) {
// prints a greeting message to the standard output console
System.out.println("hello world!");
} // end main
} // end Greeting

Duc L. M. FIT325 18
Single-line comments
/**
* OVERVIEW: This is a basic Java program which prints a greeting
* message on the standard output console
*
* @author dmle
* Single line
*/
// program (application) class
comments
class Greeting {
/**
* The default method to be invoked from the command-line
* @param args input parameters
*/
public static void main(String[] args) {
// prints a greeting message to the standard output console
System.out.println("hello world!");
} // end main
} // end Greeting

Duc L. M. FIT325 19
Print (1)
/**
* OVERVIEW: This is a basic Java program which prints a greeting
* message on the standard output console
*
* @author dmle
*
*/
// program (application) class
class Greeting {
/**
print statement:
* The default method to be invoked from the command-line
* @param args input parameters “hello world!”
*/
public static void main(String[] args) {
// prints a greeting message to the standard output console
System.out.println("hello world!");
} // end main
} // end Greeting

Duc L. M. FIT325 20
Print (2)
● Supported by three library methods:
● invoked upon the member out of class System
● System.out.println: output one line at a
time
● System.out.print: output (without linefeed
character)
● System.out.printf: formatted output (later)

Duc L. M. FIT325 21
Compile & run
source javac byte host
java
code code machine

Greeting.java Greeting.class
Greeting

javac
javac Greeting.java
Greeting.java java
java Greeting
Greeting

Compile Run/execute

Duc L. M. FIT325 22
DEMO
Greeting program
● Compile
● Run

Duc L. M. FIT325 23
Package
● Package is a group of related classes
● Helps organise large programs
● Follows a hierarchical package naming
scheme
● Java libraries are defined in packages:
– java.lang: available for use in all classes
– java.util: utility classes
– java.io: input/output
– etc.
Duc L. M. FIT325 24
Example: a program with packages
● app: the top-level package containing main
classes, e.g.:
– app.Main
● app.utils: the package containing utility
classes, e.g.:
– app.utils.Num

– app.utils.IntSet
● app.db: contains database-related classes
● etc...

Duc L. M. FIT325 25
Physical organisation of packages
app
Main.java
utils
Num.java
IntSet.java

db
...
...
Duc L. M. FIT325 26
import statment
● To refer to classes in other packages
● Not needed for java.lang
● Used with static to refer to methods and other
members
● static members only

Duc L. M. FIT325 27
Example

package app;

import app.utils.Num;
import app.utils.IntSet;
import app.db.*;
import static java.lang.System.*;

public class Main {


public static void main(String[] args) {
// code that use the imported classes
// output the results
out.println(...);
}
}

Duc L. M. FIT325 28
3 Variables and types

● Name
● Variables
● Primitive types
● Type safety
● Type conversion

Duc L. M. FIT325 29
Name
● (a.k.a identifier) Used to identify 'things':
● class, method, variable, etc.
● A sequence of one or more characters
● begin with a letter or '_'
● consists of letters, digits, and '_', but no reserved
words
● Letters are Unicode characters
● support English and other languages, incl.
Vietnamese
● Case sensitive
Duc L. M. FIT325 30
Name examples

N Hello World
n
rate class
x15 if
Greeting else
Chào while
Hello_World

Duc L. M. FIT325 31
Naming convention
● Guidelines for choosing names
● Class names: begin with upper case
● e.g. Greeting, etc.
● Other names: begin with lower case
● e.g. main, greet, message, etc.

Phrasal names: capitalise 1st letter of each
subsequent word
● e.g. class: SayGreeting; method: sayHello

Duc L. M. FIT325 32
Compound names
● Compound names are multiple names
separated by periods (.)
● Are qualified names for:
● classes in a package
● members of a class
class
● Example:
● java.lang.System variable
● System.out
method
● System.out.println

Duc L. M. FIT325 33
Variable
● A named location of the data manipulated by a
program
● Data can change over time
● Example:
president = "Barack Obama";

president
“Barack Obama”

Duc L. M. FIT325 34
Variable declaration

<type> <variable>;
● All variables must be declared with a type
● Java enforces this
● Two main types:
● primitive
● object (later)

Duc L. M. FIT325 35
Primitive types
● Numeric types:
● byte
● integral: short, int, long
● real: float, double
● Single characters:
● char
● Logical:
● boolean: true or false

Duc L. M. FIT325 36
Primitive type values
Type Size (bits) Value range
byte 8 [-27,27)
short 16 [-215,215)
int 32 [-231,231)
long 64 [-263,263)
float 32 single-precision IEEE 754
~ [-1038,1038]
double 64 double-precision IEEE 754
~ [−10308,10308]
char 16 '\u0000' to '\uffff'
Duc L. M. FIT325 37
Example: variable declarations

int counter; // a counter

float rate; // the interest rate

double rate; // double-precision

char c; // a character

boolean tf; // a boolean


Duc L. M. FIT325 38
Variable assignment

<variable> = <expression>;
● Variables must first be declared
● expression can be a value or an expression
● Variable assignment can be done
● at declaration or at any point thereafter
● Examples:
double rate = 0.07;
double principal;
principal = 1000;
Duc L. M. FIT325 39
Example (1)

double rate = 0.07;


double principal = 1000;

rate
0.07

principal
1000

Duc L. M. FIT325 40
Example (2)

c = 'A'; // character A

c
'A'

tf = true; // or false

tf
true

Duc L. M. FIT325 41
Example: Interest.java (1)
/**
* This class implements a simple program that
* will compute the amount of interest that is
* earned on $17,000 invested at an interest
* rate of 0.07 for one year. The interest and
* the value of the investment after one year are
* printed to standard output.
*/
public class Interest {

// ... (body omitted) ...

} // end of class Interest

Duc L. M. FIT325 42
Interest.java (2)
public class Interest {
public static void main(String[] args) {
/* Declare the variables. */

double principal;
double rate;
double interest;

/* Do the computations. */

principal = 17000;
rate = 0.07;

// ... (code omitted) ...


} // end main()
} // end Interest

Duc L. M. FIT325 43
Type safety
● Java is strongly typed, providing type safety
through:
● type checking
● automatic object storage management
● array bounds checking
● Advantages:
● eliminate sources of run-time errors
● ensures security

Duc L. M. FIT325 44
Type checking
● Java files are type checked at compile time
● Variable assignments:
● type of value of expression must be compatible to
variable type
● Throws compile error if violated

Duc L. M. FIT325 45
Type conversion
● Values of compatible types can be converted
to each other:
ta va = vb; // vb has type tb
where ta is compatible with tb
● Implicit conversion: performed automatically if
ta is 'bigger' than tb
● Explicit conversion: must be performed by
programmer if ta is 'smaller' than tb

Duc L. M. FIT325 46
Implicit conversions
byte → short → int → long
char → int
(byte, short, char, int, long) → float →
double
● Examples:
int num = 65536;
long lg = num; // 65536
● Also applies to reference types (later)

Duc L. M. FIT325 47
Explicit conversions
● Values are truncated if bigger:
● Examples:
long num = 65536;
int n = (int) num; // 65536
short sh = (short) n; // 0

Duc L. M. FIT325 48
4
Operations on primitive
types
● Basic operators
● Arithmetic operators
● Increment/decrement operators
● Relational operators
● Boolean operators
● Assignment operator
● Operations in class java.lang.Math
● Operators are combined to form expressions
● Precedence rules
Duc L. M. FIT325 49
Arithmetic operators
● Four operators:
● addition (+)
● subtraction (-)
● multiplication (*)
● division (/)
● Modulus (%): takes the remainder
● Applicable to numeric and char types:
● char values are treated as integers

Duc L. M. FIT325 50
Example (1)

int b = 2;
int c = 13;
int a = b + c; // 15
a = b * c; // 26
a = c – b; // 11
a = c / b; // 6 (why?)

Duc L. M. FIT325 51
Example (2)

double rate = 0.07;


double principal = 17000d;
double interest = rate * principal;

rate
0.07 interest
1190.0
principal *
17000.0

Duc L. M. FIT325 52
Example (3)

double d = 1/2; // 0 (why?)

int c = 13;
char c1 = c * 5; // illegal (why?)
char c2 = c1 + 1; // illegal (why?)

Duc L. M. FIT325 53
Type conversion
● Implicit conversion is performed if input values
are of different types
● Result value has the same type as the inputs
● explicit conversion of input values is required if
result type differs

Duc L. M. FIT325 54
Example (3)

double d = 13d / 2; // 6.5

d = 1d / 2; // 0.5

int c = 13;
char c1 = (char) (c * 5); // A
char c2 = (char) (c1 + 1); // B

Duc L. M. FIT325 55
Increment/decrement operators
● Unary operators:
● increase by 1 (++)
● decrease by 1 (--)
● Can be used as pre- or post-fix
● Applicable to numeric and char types
● char values are treated as integers

Duc L. M. FIT325 56
Example

a++; // same as a = a + 1
++a;
a--; // same as a = a - 1
--a;

Duc L. M. FIT325 57
Relational operators
● Comparative operators that return boolean
values
a == b is a “equal to” b?
a != b is a “not equal to” b?
a < b is a “less than” b?
a <= b is a “less than or equal” to b?
a > b is a “greater than” b?
a >= b is a “greater than or equal to” b?

Duc L. M. FIT325 58
Boolean operators
● Logical operators:
● and (&)
● or (|)
● short-circuted and (&&)
● short-circuted or (||)
● not (!)
● Applicable to boolean types

Duc L. M. FIT325 59
Example

int a = 5;
int b = 3 * 2;
boolean tf = (a == b) && (a != 0);
tf = (a == b) & (a != 0);

Duc L. M. FIT325 60
Assignment operator
● Assignment (=) is actually an operator
● Given two variables a, b whose types are
assignment compatible:
(a = b) == b; // true
● Variants:
(a += b) // (a = a + b)
(a -= b) // (a = a - b)
(a *= b) // (a = a * b)
(a /= b) // (a = a / b)
(a
Duc L. M.
%= b) // (aFIT325= a % b) 61
Others
● Unary +, -
● create possitive and negative values
● e.g: +1, -1, ...
● Type cast (or type conversion) is an operator:
● e.g: (int) a;

Duc L. M. FIT325 62
Precedence rules (1)
● Operators used in an expression obey
precedence rules
++, --, !, unary + and -, type-cast
*, /, % H
eval. order
L R
+, - (w/ exceptions)

precedence order
<, <=, >, >=
==, !=
&&
||
L
=, +=, -=, *=, /=, %=
Duc L. M. FIT325 63
Precedence rules (2)
● Top to bottom: higher (H) to lower (L)
precedence
● higher means “evaluated first”
● Operators on same row (with no parentheses):
● exceptions: unary and assignment are evaluated
right (R) to left (L)
● others: evaluate left (L) to right (R)

Duc L. M. FIT325 64
Class java.lang.Math
● Methods are basic maths functions on numeric
types
● Some useful methods:
Math.abs(x) = |x|
Math.pow(x,y) = xy
Math.floor(x) = y, s.t y is integer /\ |x – y| < 1
● returned as double
Math.random() = y in [0.0,1.0)
● randomly chosen
Duc L. M. FIT325 65
Interest.java (3)
public class Interest {
public static void main(String[] args) {
/* Declare the variables. */

double principal;
double rate;
double interest;

/* Do the computations. */

principal = 17000;
rate = 0.07;
interest = principal * rate;

principal = principal + interest;

Duc L. M. FIT325 66
Interest.java (4)

/* Output the results. */

System.out.print("The interest earned is $");


System.out.println(interest);
System.out.print("The value of the investment
after one year is $");
System.out.println(principal);

} // end main()
} // end Interest

Duc L. M. FIT325 67
5 Array

● What is it?
● Declaration
● Initialisation
● Operations on arrays

Duc L. M. FIT325 68
What is it?
● A basic data structure
● A sequence of data elements of the same type
● Elements are accessed by index
● starting from 0
● Array itself is considered a type
● element type is the base type
● Array-typed variable is a reference to the array
● see reference type later

Duc L. M. FIT325 69
Array declaration

<base-type>[] <variable>;
OR
<base-type> <variable>[];
● Examples:
int[] ids; //array of integers
float[] rates; //array of reals
char[] chars; //array of characters
boolean tfs[]; //array of booleans

Duc L. M. FIT325 70
Array initialisation

<base-type>[] <variable> =
{<v1>,...<vn>};
<variable> = new <base-type>[]
{<v1>,...<vn>};
● Same rule as for variable assignment
● Examples:
int[] ids = {1,2};
ids = new int[] {3,4};

Duc L. M. FIT325 71
An array variable

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


array
ids (object)
a reference to

1
2
3

Duc L. M. FIT325 72
Operations on array
● Given an array: a
● get element at a given index (idx):
a[idx]
● get the number of elements:
a.length
● Often manipulated in a loop (later)

Duc L. M. FIT325 73
Array example

int[] ids = {1,2};


int e1 = ids[0]; // first element
int l = ids.length; // num elements
int l = ids[l-1]; // last element

Duc L. M. FIT325 74
6 String

● What is it?
● Declaration & initialisation
● Operations on strings

Duc L. M. FIT325 75
What is it?
● Conceptually, a string is a sequence of
characters
● Internally, Java uses char array to represent a
string
● String is defined as a class, used as a type:
● see reference type (later)
● Immutable type:
● cannot change the content of a string
● a new string is created for every modification

Duc L. M. FIT325 76
Declaration & initialisation

String president = "Barrack Obama";

String message = "hello world";

String a = "A";

Duc L. M. FIT325 77
A String variable

String president = "Barrack Obama";

String
president (object)
a reference to

"Barrack Obama"

Duc L. M. FIT325 78
Operations on strings (1)
● Concatenation:
s3 = s1 + s2
● Get number of characters:
int l = s1.length()
● Get a character at a position idx:
char c = s1.charAt(idx)
● Get a sub-string from positions n to m-1:
s2 = s1.substring(n,m)

Duc L. M. FIT325 79
Operations on strings (2)
● Get the position of a substring:
s1.indexOf(s2)
● Case conversions:
s2 = s1.toLowerCase()
s2 = s1.toUpperCase()
● Trim:
s2 = s1.trim()

Duc L. M. FIT325 80
7 Enum

● What is it?
● Example

Duc L. M. FIT325 81
What is it?
● An enumerated type, consisting of a fixed list of
values
● Values are named constants:
● considered as members and can be accessed
using (.)
● Has a user-specifiable name
● Definition:
enum <name> { <v1>,...,<vn> }
● defined as a class member

Duc L. M. FIT325 82
Example

enum Season { Defined as


SPRING, a class
member
SUMMER,
FALL,
WINTER
}
...
Season vacation = Season.SUMMER;

Duc L. M. FIT325 83
Summary
● Java defines a program as a collection of classes
● A class is a named container for program instructions
● Variables must be declared with a type
● Primitive types include numeric, char and boolean
● with various supported operators
● An array is a sequence of elements of the same type
● String is a sequence of characters, defined as a class,
used as a type
● An enumerated type can be defined over a fixed set of
values

Duc L. M. FIT325 84
8 Text input and output

● Console input
● Console output
● Formatted output
● Text file output

Duc L. M. FIT325 85
Console input
● To read user input on the standard input
● typically the command line
● Defined as methods getlnX() in library
userlib.TextIO:
● getlnInt(): read an int
● getlnDouble: read a double
● getlnBoolean: read a boolean
● getlnChar: read a character
● getlnWord: read one word, returned as String
● getln: read one line, returned as String
Duc L. M. FIT325 86
Console input (2)
● TextIO.getX() are the same except reading
multiple values
● Use import static statement to refer to the
methods directly
import static userlib.TextIO.*;

Duc L. M. FIT325 87
Example: Interest2.java (1)
package t1;

import static userlib.TextIO.*;

/**
* This class implements a simple program that will
* ... (omitted)...
*/
public class Interest2 {

public static void main(String[] args) {

// ... omitted ...

} // end main()
} // end Interest2

Duc L. M. FIT325 88
Example: Interest2.java (2)
/**
* ...omitted...
*/
public class Interest2 {

public static void main(String[] args) {

double principal; // The value of the investment.


double rate; // The annual interest rate.
double interest; // The interest earned during the year.

put("Enter the initial investment: "); // TextIO.put()


principal = getlnDouble(); // TextIO.getlnDouble()

put("Enter the annual interest rate (decimal, ...): ");


rate = getlnDouble();

interest = principal * rate; // Compute this year's interest.


principal = principal + interest; // Add it to principal.

put("The value of the investment after one year is $");


putln(principal);
} // end main()
} // end Interest2

Duc L. M. FIT325 89
Console output
● Java provides three methods:
● System.out.println
● System.out.print
● System.out.printf
● TextIO provides three equivalent methods:
● putln for println
● put for print
● putf for printf

Duc L. M. FIT325 90
Example: Interest2.java (3)
/**
* ...omitted...
*/
public class Interest2 {

public static void main(String[] args) {

double principal; // The value of the investment.


double rate; // The annual interest rate.
double interest; // The interest earned during the year.

put("Enter the initial investment: "); // TextIO.put()


principal = getlnDouble(); // TextIO.getlnDouble()

put("Enter the annual interest rate (decimal, ...): ");


rate = getlnDouble();

interest = principal * rate; // Compute this year's interest.


principal = principal + interest; // Add it to principal.

put("The value of the investment after one year is $");


putln(principal);
} // end main()
} // end Interest2

Duc L. M. FIT325 91
Formatted output

System.out.printf(<format
string>,<v1>,...<vn>)
● Format string: texts (optional) and one or more
format specifiers, one per argument

Duc L. M. FIT325 92
Example

String s = "price is: ";


System.out.printf("%n");
System.out.printf(s);

System.out.printf("%s", s);

// on the same line as above


double price = 19.8d;
System.out.printf("%6.2f", price);
Duc L. M. FIT325 93
Format specifier
● Specifies the format of one output argument
● Basic syntax: %[arg_index$][l][m.n]c
%: the format marker
arg_index: the argument index
l: (optional) flag (e.g. output alignment)
m: (optional) the field width or number of spaces
used for output
n: (optional) the number of digits after the decimal
point
c: the conversion character
Duc L. M. FIT325 94
Conversion characters
d: decimal integer
f: fixed-point floating point
e: E-notation floating point
g: general floating point
s: string
c: character
b: boolean
%: percentage
n: line break

Duc L. M. FIT325 95
Text file output
● Supported by TextIO.writeFile(<file
name>)
● redirect output to file instead of to console
● To prompt for file name:
● TextIO.writeUserSelectedFile()
● To go back to console output:
● TextIO.writeStandardOutput()

Duc L. M. FIT325 96
Example: CreateProfile.java (1)
import static userlib.TextIO.*;

public class CreateProfile {

public static void main(String[] args) {

String name; // The user's name.


String email; // The user's email address.
double salary; // the user's yearly salary.
String favColor; // The user's favorite color.

putln("Good Afternoon! This program will create");


putln("your profile file, if you will just answer");
putln("a few simple questions.");
putln();

Duc L. M. FIT325 97
Example: CreateProfile.java (2)

/* Gather responses from the user. */ try putf


put("What is your name? ");
name = getln();
put("What is your email address? ");
email = getln();
put("What is your yearly income? ");
salary = getlnDouble();
put("What is your favorite color? ");
favColor = getln();

Duc L. M. FIT325 98
Example: CreateProfile.java (3)

/* Write the user's information to file profile.txt. */


try putf
writeFile("profile.txt"); // subsequent output goes to file
putln("Name: " + name);
putln("Email: " + email);
putln("Favorite Color: " + favColor);
putf("Yearly Income: %,1.2f%n", salary);
// comma in %,1.2f adds separators between groups of digits.

/* Print a final message to standard output. */

writeStandardOutput();
putln("Thank you. Your profile has been written to
profile.txt.");
} // end main
} // end CreateProfile

Duc L. M. FIT325 99
9 Flow of control

● What is it?
● Types of flow control

Duc L. M. FIT325 100


What is it?
● Instructions that control the flow of execution
● Written using some form of structured
statement
● involves groups of instructions

Duc L. M. FIT325 101


Types of flow control
● Block
● Conditional
● Loop: while, for

Duc L. M. FIT325 102


Block

{
<statements>
}
● A simplest form of grouping:
● statements is a sequence of statements
● may be empty
● A Java method body is a block
● Treated as a single statement
● May contain variables local to the block
Duc L. M. FIT325 103
Examples
String ans = "to be or not to be";
{
System.out.print("The answer is ");
System.out.println(ans);
}

int x = 2;
int y = 3;
{ // This block exchanges the values of x and y
int temp; // A temporary variable for use in this block.
temp = x; // Save a copy of the value of x in temp.
x = y; // Copy the value of y into x.
y = temp; // Copy the value of temp into y.
}

Duc L. M. FIT325 104


Conditional
● A.k.a branching or decision
● chooses an action depending on whether some
condition is true or false
● Action is a block of statements
● Condition is a boolean expression
● Two conditional statements:
● if
● switch

Duc L. M. FIT325 105


if statement (1)
if (<boolean-expression-1>) { condition
<statements-1>
action
} else if (<boolean-expression-2>) {
<statements-2>
. . .
} else if (<boolean_expression_n>) {
<statements-n>
} else {
<statements-for-all-other-possibilities>
}

Duc L. M. FIT325 106


if statement (2)
● Exactly one action is executed or none at all:
● conditions are tested in order
● no further conditions are tested if one is found true
● no action is executed if no condition is true
● the if block is required
● else if and else blocks are optional
● braces may be omitted for single-statement
blocks
● nesting: actions may be other if statements
Duc L. M. FIT325 107
Example
int hour = 17;
String name = "Duc";
if (hour < 12) {
System.out.println("Good morning " + name);
} else if (hour >= 12 && hour < 18) {
System.out.println("Good afternoon " + name);
} else {
System.out.println("Good evening " + name);
}

Duc L. M. FIT325 108


switch statement (1)
● A type of if statement whose:
● boolean expressions involve numeric or String
values
● values must be one of: byte, short, int, char,
String
● Each branch is labelled using case statement
● the else branch is labelled default
● To stop further evaluations of other cases
requires a break statement

Duc L. M. FIT325 109


switch statement (2)
switch (<expression>) {
case <contant-1>:
<statements-1> does not stop
break; evaluating of other
. . . cases if omitted
case <contant-n>:
<statements-n>
break;
default:
<statements-for-all-other-possibilities>
}
Duc L. M. FIT325 110
Example
switch (n) { // (Assume n is an integer variable.)
case 1:
System.out.println("The number is 1.");
break;
case 2:
case 4:
case 8:
System.out.println("The number is 2, 4, or 8.");
System.out.println("(That's a power of 2!)");
break;
case 3:
case 6:
case 9:
System.out.println("The number is 3, 6, or 9.");
System.out.println("(That's a multiple of 3!)");
break;
case 5:
System.out.println("The number is 5.");
break;
default:
System.out.println("The number is 7 or is outside the range 1 to 9.");
Duc L. M. FIT325 111
Loop
● Repeat a sequence of instructions
● Three loop statements:
● while
● do
● for

Duc L. M. FIT325 112


while statement (1)

while (<boolean-expression>) {
<statements>
condition
} body
● body is executed if condition is true
● the first time
● each time thereafter
● loop is not executed if condition is false first
time
● loop ends when body causes condition to
become
Duc L. M.
false FIT325 113
while statement (2)
● prime the loop:
● condition is set up to make sense the first time
● each execution of body is called a loop
iteration

Duc L. M. FIT325 114


Example: ComputeAverage (partial)
put("Enter your first positive integer: ");
inputNumber = getlnInt(); prime the loop

while (inputNumber != 0) {
sum += inputNumber; // Add inputNumber to running sum.
count++; // Count the input by adding 1 to count.
put("Enter your next positive integer, or 0 to end: ");
inputNumber = getlnInt();
set up for next
}
iteration

Duc L. M. FIT325 115


do...while statement

do {
<statements>
} while (<boolean-expression>);
● similar to while loop except the while part is
moved to end
● body is executed at least one
● can be converted to while loop and vice versa

Duc L. M. FIT325 116


Conversion (1)
● while
<doSomething>
while (<boolean-expression>) {
<doSomething>
}
● to do...while
if (<boolean-expression>) {
do {
<doSomething>
} while (<boolean-expression>);
}
Duc L. M. FIT325 117
Conversion (2)
● do...while
do {
<doSomething>
} while (<boolean-expression>);
● to while
<doSomething>
while (<boolean-expression>) {
<doSomething>
}
Duc L. M. FIT325 118
for statement (1)
for (<initialisation>; <boolean-expression>; <update>)
{
<statements>
}
● is similar to the while loop in this form:
<initialisation>
while (<boolean-expression>) {
<statements>
<update>
}
Duc L. M. FIT325 119
for statement (2)
● initialisation is executed once before the loop
● condition is evaluated before each iteration
● update is performed at the end of each iteration
● update the loop variable(s) involved in the condition
● any of the above can be empty:
● empty condition means true or infinite loop

Duc L. M. FIT325 120


Example

put("Enter your first positive integer: ");

for (inputNumber = getlnInt(); inputNumber != 0;


inputNumber = getlnInt()) {
sum += inputNumber; // Add inputNumber to running sum.
count++; // Count the input by adding 1 to count.
put("Enter your next positive integer, or 0 to end: ");
}
loop variable

Duc L. M. FIT325 121


Counting loop
for (<var> = <min>; <var> <= <max>; <var>++) {
<statements>
}
● A most common application of for statement
● Loop variable is integral within a range
[min,max]
● condition may use the '<' operator for range
[min,max)
● Update is increment
● alternative: decrement, and var assignment
Duc L. M. FIT325 122
Example
put("Enter how many numbers you will use: ");
count = getlnInt();

/* Read and process the user's input. */


for (int i = 1; i <= count; i++) {
putf("Enter positive integer #%d: ", i);
inputNumber = getlnInt();
sum += inputNumber; // Add inputNumber to sum.
}

Duc L. M. FIT325 123


Multi-variable counting loops
● Two or more loop variables are used
● Example:
for (int i = 1, j = 10; i <= 10; i++, j--) {
putf("%5d", i);
putf("%5d%n", j);
}

What does this loop do ?

Duc L. M. FIT325 124


Nested for loops
● for loops can be nested in multiple levels
● but hard to understand more than 3 levels
● Can also nest different types of loops
● while inside for, etc.
● Example:
Print in order the characters of the alphabet
that appear in a user-specified string.

Duc L. M. FIT325 125


Example: ListLetters (partial)
putln("Please type in a line of text.");
str = getln();
str = str.toUpperCase();

putf("Your input contains these letters:%n%4s","");


for (letter = 'A'; letter <= 'Z'; letter++) {
int i; // Position of a character in str.
for (i = 0; i < str.length(); i++) {
if (letter == str.charAt(i)) {
putf("%-2s",letter); // left-justified,width 2
count++;
break;
}
}
} Duc L. M. FIT325 126
break and continue
● Applicable to all three loop types
● break: end a current loop
● the inner-most containing loop if nested
● continue: end the current iteration and start
the next one
● Can be used with loop labels (esp. in a nested
loop):
break <loop-label>
continue <loop-label>

Duc L. M. FIT325 127


Example: ListLetters (partial) (2)
putln("Please type in a line of text.");
str = getln();
str = str.toUpperCase();

putf("Your input contains these letters:%n%4s","");


OUTER: for (letter = 'A'; letter <= 'Z'; letter++) {
int i; // Position of a character in str.
for (i = 0; i < str.length(); i++) {
if (letter == str.charAt(i)) {
putf("%-2s",letter); // left-justified,width 2
count++;
continue OUTER;
}
}
} Duc L. M. FIT325 128
for each loop
for (<type> <var> : <elements>) {
<statements>
}
● applied to structural types, e.g. enum, array,
list, etc.
● an enhanced for loop
● picks out each of the elements of the data
structure at a time
● the loop variable points to the current element
● the element is processed in the body
Duc L. M. FIT325 129
Example: array

String[] seasons = {"SPRING", "SUMMER",


"FALL", "WINTER"};
int idx = 0;
for ( String s: seasons ) {
putf("%s is a season number %d%n", s, idx);
idx++;
}

What does this loop do ?

Duc L. M. FIT325 130


Example: enum
● Applied to the array of elements of an enum
● elements are retrieved using Enum.values()
static enum Season {
SPRING,
SUMMER,
FALL,
WINTER}
public static void main(String[] args) {
int idx;
for ( Season s: Season.values() ) {
idx = s.ordinal();
putf("%s is a season number %d%n", s, idx);
}
}Duc L. M. FIT325 131
10 Program development

● Decomposition
● Abstraction

Duc L. M. FIT325 132


Decomposition
● The process of dividing a large problem into
smaller ones
● the “divide and rule” principle
● Goal: decompose a program into smaller
ones that interact in simple and well-defined
ways

Duc L. M. FIT325 133


Decomposition criteria
● Each subproblem:
● is at the same level of detail
● can be solved independently
● The subproblems' solutions can be combined
to solve the original problem
● The combined solution is expressed in the
form of algorithm

Duc L. M. FIT325 134


Example: print letters (1)

Print
Print in
in order
order the
the characters
characters of
of the
the alphabet
alphabet that
that
appear
appear in in aa user-specified
user-specified string.
string.

Process user string to


Get the user
find characters and
string
print them in order

combine

Get the user string


Process user string to find characters and print them in order
Duc L. M. FIT325 135
Example (2)
···

Process user string to


Get the user
find characters and
string
print them in order

Read the user for each alphabet character c


Ask user for
response if c appears in s
string input
(→ s) print c

for each alphabet character c


for each character r in s
if c equals r
print c
Duc L. M. FIT325 136
Example (3)

Print
Print in
in order
order the
the characters
characters of
of the
the alphabet
alphabet that
that
appear
appear in in aa user-specified
user-specified string.
string.

Ask user for string input


Let s be the user response
for each alphabet character c
for each character r in s
if c equals r
print c
Can we decompose further ?
Duc L. M. FIT325 137
Benefits of decomposition
● eases problem solving
● eases group work
● eases program maintenance
● eases understanding

Duc L. M. FIT325 138


Abstraction
● Abstraction: to look at a problem at some
level of detail
● consider some details, but ignore others
● Goal: to find the abstraction(s) suitable for
each level of decompositional detail
● abstractions are classes and/or methods

Duc L. M. FIT325 139


Example: what abstractions? (1)
···

Process user string to


Get the user
find characters and
string ? print them in order

class ListLetters
method ListLetters.main
? ?

method getString method processString

or wait for further refinements

Duc L. M. FIT325 140


Example: what abstractions? (2)
···

Process user string to


Get the user
find characters and
string
print them in order

Read the user ···


Ask user for
response
string input
(→ s)
? Nil
? method TextIO.getln
? for each alphabet character c
for each character r in s
method TextIO.putln if c equals r
print c
Duc L. M. FIT325 141
Two solutions
● Single-method:
● use one method ListLetters.main
● Multiple-method:
● use three methods: ListLetters.main,
getString and processString
● Which solution?
● depends on other constraints
● e.g. response time (how fast?), ease of update, etc.

Duc L. M. FIT325 142


Solution 1: single-method

as before...

Duc L. M. FIT325 143


Solution 2: multi-method (partial)
public class ListLetters2 {

public static void main(String[] args) {

String str = getString();

str = str.toUpperCase();

processString(str);

} // end main()
}

Duc L. M. FIT325 144


Summary
● Text input/output allows a program to read
(display) string literals from (to) standard input
(output) and text files
● Flow of control includes block, branching, and
loops, which can be combined in various ways
● Problem solving concepts include
decomposition and abstraction
● a problem may have one or more solutions,
expressed in the form of algorithms

Duc L. M. FIT325 145

S-ar putea să vă placă și