Documente Academic
Documente Profesional
Documente Cultură
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
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)
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.*;
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
char c; // a character
<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)
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 {
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;
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)
rate
0.07 interest
1190.0
principal *
17000.0
Duc L. M. FIT325 52
Example (3)
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)
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;
Duc L. M. FIT325 66
Interest.java (4)
} // 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
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
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 a = "A";
Duc L. M. FIT325 77
A String variable
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
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;
/**
* This class implements a simple program that will
* ... (omitted)...
*/
public class Interest2 {
} // end main()
} // end Interest2
Duc L. M. FIT325 88
Example: Interest2.java (2)
/**
* ...omitted...
*/
public class 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 {
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
System.out.printf("%s", s);
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.*;
Duc L. M. FIT325 97
Example: CreateProfile.java (2)
Duc L. M. FIT325 98
Example: CreateProfile.java (3)
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
{
<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.
}
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
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
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
● Decomposition
● Abstraction
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.
combine
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.
class ListLetters
method ListLetters.main
? ?
as before...
str = str.toUpperCase();
processString(str);
} // end main()
}