Java Programming Tutorial
Java Programming Tutorial
Java Programming Tutorial
Java Basics
This chapter explains the basic syntaxes of the Java programming language. I shall
assume that you could write some simple Java programs. (Otherwise, read "Introduction
To Java Programming for First-time Programmers".)
To be a proficient programmer, you need to master two things: (1) the syntax of the
programming language, and (2) the API libraries associated with the language.
1. Basic Syntaxes
1.1 Revision
Step 1: Write the source codes (.java) using a programming text editor (such as
Notepad++, Textpad, gEdit) or an IDE (such as Eclipse or NetBeans).
Step 2: Compile the source codes (.java) into Java portable bytecode (.class) using
the JDK compiler ("javac").
Step 3: Run the compiled bytecode (.class) with the input to produce the desired output,
using the Java Runtime ("java").
Below is a simple Java program that demonstrates the three basic programming
constructs: sequential, loop, and conditional. Read "Introduction To Java Programming
for First-time Programmers" if you need help in understanding this program.
1 /*
2 * Sum the odd numbers and the even numbers from a lowerbound to an
upperbound
3
*/
4
public class OddEvenSum { // Save as "OddEvenSum.java"
5
public static void main(String[] args) {
6
int lowerbound = 1, upperbound = 1000;
7
int sumOdd = 0; // For accumulating odd numbers, init to 0
8
int sumEven = 0; // For accumulating even numbers, init to 0
9
int number = lowerbound;
10
while (number <= upperbound) {
11
if (number % 2 == 0) { // Even
12
sumEven += number; // Same as sumEven = sumEven + number
13
} else { // Odd
14
sumOdd += number; // Same as sumOdd = sumOdd + number
15
}
16
++number; // Next number
17
}
18
// Print the result
19
System.out.println("The sum of odd numbers from " + lowerbound
20 + " to " + upperbound + " is " + sumOdd);
1.2 Comments
Comments are used to document and explain your codes and your program logic.
Comments are not programming statements. They are ignored by the compiler and have
no consequences to the program execution. Nevertheless, comments are VERY
IMPORTANT for providing documentation and explanation for others to understand
your programs (and also for yourself three days later).
1. Multi-Line Comment: begins with a /* and ends with a */, and can span multiple lines.
2. End-of-Line (Single-Line) Comment: begins with // and lasts till the end of the current line.
I recommend that you use comments liberally to explain and document your codes.
During program development, instead of deleting a chunk of statements irrevocably, you
could comment-out these statements so that you could get them back later, if needed.
For examples,
int product;
System.out.println("Hello");
Block: A block is a group of statements surrounded by a pair of curly braces { }. All the
statements inside the block is treated as one single unit. Blocks are used as the body in
constructs like class, method, if-else and for-loop, which may contain multiple
statements but are treated as one unit (one body). There is no need to put a semi-colon
after the closing brace to end a compound statement. Empty block (i.e., no statement
inside the braces) is permitted. For examples,
// Take note that a "complex" statement is usually written over a few lines
for readability.
System.out.println("PASS");
System.out.println("Well Done!");
System.out.println("Keep it Up!");
if (number == 88) {
System.out.println("Got it!");
} else {
System.out.println("Try Again!");
i = 1;
while (i < 8) {
++i;
...statements...
White Spaces: Blank, tab and newline are collectively called white spaces. Java, like
most of the computing languages, ignores extra white spaces. That is, multiple
contiguous white spaces are treated as a single white space.
You need to use a white space to separate two keywords or tokens to avoid ambiguity,
e.g.,
int sum=0; // Cannot write intsum=0. Need at least one white space
between "int" and "sum"
double average; // Again, need at least a white space between "double" and
"average"
Additional white spaces and extra lines are, however, ignored, e.g.,
// same as above
int sum
= 0 ;
double average ;
Formatting Source Codes: As mentioned, extra white spaces are ignored and have no
computational significance. However, proper indentation (with tabs and blanks) and
extra empty lines greatly improves the readability of the program. This is extremely
important for others (and yourself three days later) to understand your programs.
For example, the following one-line hello-world program works. But can you read and
understand the program?
Braces: Java's convention is to place the beginning brace at the end of the line, and align
the ending brace with the start of the statement.
Indentation: Indent each level of the body of a block by an extra 3 (or 4) spaces.
/*
*/
// Sequential statements
statement;
statement;
// Conditional statement
if (test) {
statements;
} else {
statements;
}
// loop
init;
while (test) {
statements;
update;
}
2.1 Variables
Computer programs manipulate (or process) data. A variable is used to store a piece of
data for processing. It is called variable because you can change the value stored.
More precisely, a variable is a named storage location, that stores a value of a particular
data type. In other words, a variable has a name, a type and stores a value.
A variable has a name (aka identifier), e.g., radius, area, age, and height. The name is
needed to uniquely identify each variable, so as to assign a value to the variable (e.g.,
radius=1.2), as well as to retrieve the value stored (e.g., radius*radius*3.1419265).
A variable has a type. Examples of Java type are:
o int: meant for integers (whole numbers) such as 123 and -456.
o double: meant for floating-point (real numbers), such as 3.1416, -55.66, 1.2e3,
-4.5E-6, having a optional decimal point and fractional part.
o String: meant for texts such as "Hello", "Good Morning!". Strings are enclosed
within a pair of double quotes.
o char: meant for a single character, such as 'a', '8'. A char is enclosed by a pair of
single quotes.
A variable can store a value of that particular data type. It is important to take note that a
variable in most programming languages is associated with a type, and can only store value of
the particular type. For example, a int variable can store an integer value such as 123, but NOT
real number such as 12.34, nor string such as "Hello".
The concept of type was introduced in the early programming languages to simplify
interpretation of data made up of binary numbers (0's and 1's). The type determines the size
and layout of the data, the range of its values, and the set of operations that can be applied.
The following diagram illustrates three types of variables: int, double and String. An
int variable stores an integer (or whole number or fixed-point number); a double
variable stores a floating-point number or real number; a String variable stores texts.
An identifier is needed to name a variable (or any other entity such as a method or a
class). Java imposes the following rules on identifiers:
Caution: Programmers don't use blank character in names. It is either not supported (e.g.,
in Java and C/C++), or will pose you many more challenges.
A variable name is a noun, or a noun phrase made up of several words with no spaces
between words. The first word is in lowercase, while the remaining words are
initial-capitalized. For example, thefontSize, roomNumber, xMax, yMin, xTopLeft and
thisIsAVeryLongVariableName. This convention is also known as camel-case.
Recommendations
1. It is important to choose a name that is self-descriptive and closely reflects the meaning of the
variable, e.g., numberOfStudents or numStudents, but not n or x, to store the number of
students. It is okay to use long names!
2. Do not use meaningless names like a, b, c, d, i, j, k, i1, j99.
3. Avoid single-letter names like i, j, k, a, b, c, which is easier to type but often meaningless.
Exception are common names like x, y, z for coordinates, i for index. Long names are harder to
type, but self-document your program. (I suggest you spend sometimes practicing your typing.)
4. Use singular and plural nouns prudently to differentiate between singular and plural
variables. For example, you may use the variable row to refer to a single row number and the
variable rows to refer to many rows (such as an array of rows - to be discussed later).
To use a variable in your program, you need to first "introduce" it by declaring its name
and type, in one of the following syntaxes. The act of declaring a variable allocates a
storage (of size capable of holding a value of the type).
Syntax Example
int magicNumber =
88;
String greetingMsg
= "Hi!", quitMsg =
"Bye!";
Java is a "strongly type" language. A variable is declared with a type. Once the type of a variable
is declared, it can only store a value belonging to this particular type. For example, an int
variable can hold only integer such as 123, and NOT floating-point number such as -2.17 or
text string such as "Hello".
Each variable can only be declared once.
You can declare a variable anywhere inside the program, as long as it is declared before used.
The type of a variable cannot be changed inside the program, after it is declared.
A variable declaration statement begins with a type, and works for only that type. In other words,
you cannot declare variables of two different type in a single declaration statement.
Constants are non-modifiable variables, declared with keyword final. Their values
cannot be changed during program execution. Also, constants must be initialized during
declaration. For examples:
Constant Naming Convention: Use uppercase words, joined with underscore. For
example, MIN_VALUE, MAX_SIZE.
2.5 Expressions
1 + 2 * 3 // evaluated to int 7
int sum, number;
2.6 Assignment
An assignment statement:
1. assigns a literal value (of the RHS) to a variable (of the LHS), e.g.,
x = 1; or
2. evaluates an expression (of the RHS) and assign the resultant value
to a variable (of the LHS), e.g., x = (y + z) / 2.
Syntax Example
// Assign the literal value (of the RHS) to the variable (of number = 88;
the LHS)variable = literalValue;// Evaluate the expression
(RHS) and assign the result to the variable (LHS)variable =
expression; sum = sum +
number;
8 = number; // INVALID
In Java, the equal symbol '=' is known as the assignment operator. The meaning
of '=' in programming is different from Mathematics. It denotes assignment
of the LHS value to the RHS variable, instead of equality of the RHS and
LHS. The RHS shall be a literal value or an expression that evaluates to
a value; while the LHS must be a variable.
Some programming languages use symbol ":=", "->" or "<-" as the assignment
operator to avoid confusion with equality.
In Java, there are two broad categories of types: primitive types (e.g.,
int, double) and reference types (e.g., objects and arrays). We shall
describe the primitive types here and the reference types (classes and
objects) in the later chapters on "Object-Oriented Programming".
TYPE DESCRIPTION
Character
Represented in 16-bit Unicode '\u0000' to '\uFFFF'.
char
Can be treated as 16-bit unsigned integers in the range of [0,
65535] in arithmetic operations.
Binary
Takes a value of either true or false.
boolean
The size of boolean is not defined in the Java specification, but
requires at least one bit.
Primitive type are built-in to the languages. Java has eight primitive types,
as listed in the above table:
There are four integer types: 8-bit byte, 16-bit short, 32-bit int
and 64-bit long. They are signed integers in 2's complement
representation, and can hold an integer value of the various ranges
as shown in the table.
There are two floating-point types: 32-bit single-precision float and
64-bit double-precision double, represented as specified by IEEE 754
standard. A float can represent a number between ±1.40239846×10^-45
and ±3.40282347×10^38, approximated. A double can represented a
number between ±4.94065645841246544×10^-324 and ±
1.79769313486231570×10^308, approximated. Take note that not all
real numbers can be represented by float and double. This is because
there are infinite real numbers even in a small range of say [1.1,
2.2], but there is a finite number of patterns in a n-bit
representation. Most of the floating-point values are approximated
to their nearest representation.
The type char represents a single character, such as '0', 'A', 'a'.
In Java, char is represented using 16-bit Unicode (in UCS-2 format)
to support internationalization (i18n). A char can be treated as a
16-bit unsigned integer (in the range of [0, 65535]) in arithmetic
operations. For example, character '0' is 48 (decimal) or 30H
(hexadecimal); character 'A' is 65 (decimal) or 41H (hexadecimal);
character 'a' is 97 (decimal) or 61H (hexadecimal).
Java introduces a new binary type called "boolean", which takes a value
of either true or false.
Example: The following program can be used to print the maximum, minimum
and bit-length of the primitive types. The maximum, minimum and bit-size
of int are kept in constants INTERER.MIN_VALUE, INTEGER.MAX_VALUE,
INTEGER.SIZE.
/*
*/
System.out.println("byte(bit-length)=" + Byte.SIZE);
int(min) = -2147483648
int(max) = 2147483647
int(bit-length) = 32
byte(min) = -128
byte(max) = 127
byte(bit-length)=8
short(min) = -32768
short(max) = 32767
short(bit-length) = 16
long(min) = -9223372036854775808
long(max) = 9223372036854775807
long(bit-length) = 64
char(min) = 0
char(max) = 65535
char(bit-length) = 16
float(min) = 1.4E-45
float(max) = 3.4028235E38
float(bit-length) = 32
double(min) = 4.9E-324
double(max) = 1.7976931348623157E308
double(bit-length) = 64
String
Another commonly-used type is String, which represents texts (a sequence
of characters) such as "Hello, world". String is not a primitive type, and
will be further elaborated later. In Java, a char is enclosed by single quotes
(e.g., 'A', '0'), while a String is enclosed by double quotes (e.g., "Hello").
For example,
As a programmer, you need to choose variables and decide on the type of the
variables to be used in your programs. Most of the times, the decision is
intuitive. For example, use an integer type for counting and whole number;
a floating-point type for number with fractional part, String for text
message, char for a single character, and boolean for binary outcomes.
Rules of Thumb
Use int for integer and double for floating point numbers. Use byte,
short, long and float only if you have a good reason to choose that
specific precision.
Use int for counting and indexing, NOT floating-point type (float or
double). This is because integer type are precise and more efficient
in operations.
Use an integer type if possible. Use a floating-point type only if
the number contains a fractional part.
Data Representation
Read "Data Representation" if you wish to understand how the numbers and
characters are represented inside the computer memory. In brief, It is
important to take note that char '1' is different from int 1, byte 1, short
1, float 1.0, double 1.0, and String "1". They are represented differently
in the computer memory, with different precision and interpretation. For
example, byte 1 is "00000001", short 1 is "00000000 00000001", int 1 is
"00000000 00000000 00000000 00000001", long 1 is "00000000 00000000 00000000
00000000 00000000 00000000 00000000 00000001", float 1.0 is "0 01111111
0000000 00000000 00000000", double 1.0 is "0 01111111111 0000 00000000
00000000 00000000 00000000 00000000 00000000", char '1' is "00000000
00110001", and String "1" is a complex object.
Furthermore, you MUST know the type of a value before you can interpret a
value. For example, this value "00000000 00000000 00000000 00000001" cannot
be interpreted unless you know its type (or its representation).
Example (Variable Names and Types): Paul has bought a new notebook of "abc"
brand, with a processor speed of 3.2GHz, 4 GB of RAM, 500GB hard disk, with
a 15-inch monitor, for $1650.45. He has chosen service plan 'B' among plans
'A', 'B' and 'C', plus on-site servicing. Identify the data types and name
the variables.
Exercise (Variable Names and Types): You are asked to develop a software
for a college. The system shall maintain information about students. This
includes name, address, phone number, gender, date of birth, height, weight,
degree pursued (e.g., B.Sc., B.A.), year of study, average GPA, with/without
tuition grant, is/is not a scholar. Each student is assigned a unique 8-digit
number as id. Identify the variables. Assign a suitable name to each variable
and choose an appropriate type. Write the variable declaration statements.
2.8 Literals for Primitive Types and String
int sum = 1234567890; // This value is within the range of intint bigSum
= 8234567890; // ERROR: this value is outside the range of int
An int literal may precede with a plus (+) or minus (-) sign, followed by
digits. No commas or special symbols (e.g., $ or space) is allowed (e.g.,
1,234 and $123 are invalid). No preceding 0 is allowed too (e.g., 007 is
invalid).
You can use a prefix '0' (zero) to denote a value in octal, and prefix '0x'
(or '0X') for a value in hexadecimal, e.g.,
(JDK 1.7) From JDK 7, you can use prefix '0b' or '0B' to specify a value
in binary. You are also permitted to use underscore (_) to break the digits
into groups to improve the readability. But you must start and end the literal
with a digit. For example,
A long literal above the int range requires a suffix 'L' or 'l' (avoid
lowercase, which confuses with the number one), e.g., 123456789012L,
-9876543210l. In Java, the range of 64-bit long literals is
-9,223,372,036,854,775,808L (-2^63) to 9,223,372,036,854,775,807L
(2^63-1). For example,
No suffix is needed for byte and short literals. But you can only use integer
values in the permitted range. For example,
You can optionally use suffix 'd' or 'D' to denote double literals.
You MUST use a suffix of 'f' or 'F' for float literals, e.g., -1.2345F. For
example,
float average = 55.66; // Error! RHS is a double. Need suffix 'f' for
float.
For example,
Notes:
String Literals
'__'
(oo)
+========\/
/ || %%% ||
* ||-----||
"" ""
boolean Literals
There are only two boolean literals, i.e., true and false. For example,
Example on Literals
/*
*/
long netAsset = 8234567890L; // Need suffix 'L' for long. Beyond int
3. Operations
expr1 * 2 * 3 → 6
* Multiplication
expr2 3.3 * 1.0 → 3.3
expr1 / 1 / 2 → 0
/ Division
expr2 1.0 / 2.0 → 0.5
5 % 2 → 1
Remainder expr1 %
% -5 % 2 → -1
(Modulus) expr2
5.5 % 2.2 → 1.1
Addition expr1 +
1 + 2 → 3
+ (or unary expr2
1.1 + 2.2 → 3.3
positive) +expr
expr1 -
Subtraction 1 - 2 → -1
- expr2
(or unary negate) 1.1 - 2.2 → -1.1
-expr
All these operators are binary operators, i.e., they take two operands.
However, '+' and '-' can also be interpreted as unary "positive" and
"negative" operators. For example,
Rules on Precedence
Like Mathematics:
1. The multiplication (*), division (/) and remainder (%) take precedence
over addition (+) and subtraction (-). For example, 1+2*3-4/2 is
interpreted as 1+(2*3)-(4/2).
2. Unary '+' (positive) and '-' (negate) have higher precedence.
3. Parentheses () have the highest precedence and can be used to change
the order of evaluation.
4. Within the same precedence level (e.g., addition and subtraction),
the expression is evaluated from left to right (called
left-associative). For example, 1+2-3+4 is evaluated as ((1+2)-3)+4
and 1*2%3/4 is ((1*2)%3)/4.
If both operands are int, long, float or double, the arithmetic operations
are carried in that type, and evaluated to a value of that type, i.e., int
5 + int 6 → int 11; double 2.1 + double 1.2 → double 3.3.
If the two operands belong to different types, the value of the smaller type
is promoted automatically to the larger type (known as implicit
type-casting). The operation is then carried out in the larger type, and
evaluated to a value in the larger type.
For examples,
byte b1 = 1, b2 = 2;
5.
The type-promotion rules for unary operations (e.g., negate '-') can be
summarized as follows:
For example,
byte b1 = 1;
For example,
-5 % 2 ⇒ -3 % 2 ⇒ -1
5.5 % 2.2 ⇒ 3.3 % 2.2 ⇒ 1.1
Exponent?
Java does not have an exponent operator. (The '^' operator is for
exclusive-or, NOT exponent). You need to use method Math.exp(x, y) to
evaluate x raises to power y.
3.4 Overflow/Underflow
/*
* Illustrate "int" overflow
*/
System.out.println(i1 * i1); // 1
System.out.println(i2 * i2); // 0
On the other hand, integer division produces an truncated integer and results
in so-called underflow. For example, 1/2 gives 0, instead of 0.5. Again,
Java runtime does NOT issue an error/warning message, but produces an
imprecise result.
3.5 Type-Casting
In Java, you will get a compilation error if you try to assign a double or
float value of to an int variable. This is because the fractional part would
be lost. The compiler issues an error "possible loss in precision". For
example,
double d = 3.5;
To assign the a double value to an int variable, you need to invoke the
so-called type-casting operator - in the form of (int)value - to operate
on the double operand and return a truncated value in int. In other words,
you tell the compiler you concisely perform the truncation and you are aware
of the possible loss of precision. You can then assign the truncated int
value to the int variable. For example,
double d = 3.5;
int i;
int i = 3;
double d;
// d = 3.0
This is because both the sum and 100 are int. The result of division is an
int, which is then implicitly casted to double and assign to the double
variable average. To get the correct answer, you can do either:
average = (double)sum / 100; // Cast sum from int to double before
division
Besides the usual simple assignment operator (=) described earlier, Java
also provides the so-called compound assignment operators as listed:
Assignment
Assign the value of the
= var = expr x = 5;
LHS to the variable at the
RHS
var +=
expr x += 5;
Compound addition and
+= same as same as x = x
assignment
var = var + + 5
expr
var -=
expr x -= 5;
Compound subtraction and
-= same as same as x = x
assignment
var = var - - 5
expr
var *=
expr x *= 5;
Compound multiplication
*= same as same as x = x
and assignment
var = var * * 5
expr
/= var /= x /= 5;
Compound division and
expr same as x = x
assignment same as / 5
var = var /
expr
var %=
expr x %= 5;
Compound remainder
%= same as same as x = x %
(modulus) and assignment
var = var % 5
expr
3.7 Increment/Decrement
Java supports these unary arithmetic operators: increment (++) and decrement
(--) for all numeric primitive types (byte, short, char, int, long, float
and double, except boolean).
The increment (++) and decrement (--) operate on its operand and store the
result back to its operand. For example, x++ retrieves x, increment and
stores the result back to x. Writing x = x++ is a logical error!!!
Unlike other unary operator (such as negate (-)) which promotes byte, short
and char to int, the increment and decrement do not promote its operand
(because there is no such need).
Pre-Increment
y = ++x;
++var Increment var, then use the
same as x=x+1; y=x;
new value of var
Post-Increment y = x++;
var++ Use the old value of var, then same as oldX=x; x=x+1;
increment var y=oldX;
y = --x;
--var Pre-Decrement
same as x=x-1; y=x;
y = x--;
var-- Post-Decrement same as oldX=x; x=x-1;
y=oldX;
For examples,
x = 5;
x = 5;
Prefix operator (e.g, ++i) could be more efficient than postfix operator
(e.g., i++)?!
expr1 ==
== Equal to (x == y) → false
expr2
expr1 !=
!= Not Equal to (x != y) → true
expr2
expr1 >
> Greater than (x > y) → false
expr2
expr1 <
< Less than (y < 8) → false
expr2
Java provides four logical operators, which operate on boolean operands only,
in descending order of precedences, as follows:
booleanExpr1 &&
&& Logical AND
booleanExpr2
booleanExpr1 ||
|| Logical OR
booleanExpr2
AND
true false
(&&)
NOT
true false
(!)
XOR
true false
(^)
Example:
// Return true if x is between 0 and 100 (inclusive)
/*
*/
System.out.println((height >= 180) && (weight >= 65) && (weight <=
80));
Write an expression for all unmarried male, age between 21 and 35, with height
above 180, and weight between 70 and 80.
Exercise: Given the year, month (1-12), and day (1-31), write a boolean
expression which returns true for dates before October 15, 1582 (Gregorian
calendar cut over date).
Ans: (year < 1582) || (year == 1582 && month < 10) || (year == 1582 && month
== 10 && day < 15)
Operator Precedence
The precedence from highest to lowest is: '!' (unary), '^', '&&', '||'. But
when in doubt, use parentheses!
Short-Circuit Operation
The logical AND (&&) and OR (||) operators are known as short-circuit
operators, meaning that the right operand will not be evaluated if the result
can be determined by the left operand. For example, false && ... gives false;
true || ... give true without evaluating the right operand. This may have
adverse consequences if you rely on the right operand to perform certain
operations, e.g. false && (++i < 5) but ++i will not be evaluated.
4. Strings
A String is a sequence of characters. A string literal is surrounded by a
pair of double quotes, e.g.,
You need to use an escape sequence for special control characters (such as
newline \n and tab \t), double-quote \" and backslash \\ (due to conflict)
and Unicode character \uhhhh (if your editor does not support Unicode input),
e.g.,
1 + 2 → 3
If both operands are Strings, '+' concatenates the two Strings
and returns the concatenated String. E.g.,
"The number is " + 5 → "The number is " + "5" → "The number is 5"
For examples,
To check all the available methods for String, open JDK API documentation
⇒ select package "java.lang" ⇒ select class "String" ⇒ choose method. For
examples,
int pos = 0;
.......
++pos;
double d = 55.66;
// char to String
char c = 'a';
// boolean to String
String s9 = String.valueOf(done);
"char" to "int": You can convert char '0' to '9' to int 0 to 9 by subtracting
the char with '0' (e.g., '8'-'0' → 8).
5. Flow Control
There are three basic flow control constructs - sequential, conditional (or
decision), and loop (or iteration), as illustrated below.
// if-thenif System.out.println("Congr
( booleanExpress atulation!");
ion ) {
true-block ;} System.out.println("Keep
it up!");
System.out.println("Congr
// if-then-elseif atulation!");
( booleanExpress
ion ) { System.out.println("Keep
true-block ;} it up!");
else { } else {
false-block ;}
System.out.println("Try
Harder!");
block-3 ;
System.out.println("D");
} else if
( booleanExpr-4 ) } else {
{
...... System.out.println("F");
} else { }
elseBlock ;
}
default-block;
System.err.println("Unkno
} wn operator);
Braces: You could omit the braces { }, if there is only one statement inside
the block. However, I recommend that you keep the braces to improve the
readability of your program. For example,
System.out.println("FAIL");
System.out.println("Try Harder!");
"switch-case-default"
Syntax Example
Again, there are a few types of loops: for, while-do, and do-while.
// Sum
from 1 to
1000
int sum =
// for-loopfor
0;
(initialization;
test; for (int
post-processing) number =
{ 1; number
<= 1000;
body;}
++number)
{
sum +=
number;
int sum =
// while-do 0, number
loopwhile ( test ) = 1;
{
while
body; (number <=
} 1000) {
sum +=
number;
++number;
int sum =
0, number
= 1;
// do-while do {
loopdo {
sum +=
body; number;
}
The difference between while-do and do-while lies in the order of the body
and condition. In while-do, the condition is tested first. The body will
be executed if the condition is true and the process repeats. In do-while,
the body is executed and then the condition is tested. Take note that the
body of do-while will be executed at least once vs. possibly zero for while-do.
Similarly, the for-loop's body could possibly not executed.
Example: Suppose that your program prompts user for a number between 1 to
10, and checks for valid input. A do-while loop with a boolean flag could
be more appropriate as it prompts for input at least once, and repeat again
and again if the input is invalid.
int number;
do {
valid = true;
// Game loop
while (!gameOver) {
......
......
Empty for-loop
You could place more than one statement in the initialization and
post-processing, separated with commas (instead of the usual semi-colon).
For example,
for (int row = 0, col = 0; row < SIZE; ++row, ++col) {
......
The break statement breaks out and exits the current (innermost) loop.
The continue statement aborts the current iteration and continue to the next
iteration of the current (innermost) loop.
break and continue are poor structures as they are hard to read and hard
to follow. Use them only if absolutely necessary.
Example (break): The following program lists the non-prime numbers between
2 and an upperbound.
/*
*/
Let's rewrite the above program to list all the primes instead. A boolean
flag called isPrime is used to indicate whether the current number is a prime.
It is then used to control the printing.
/*
*/
Let's rewrite the above program without using break statement. A while loop
is used (which is controlled by the boolean flag) instead of for loop with
break.
/*
*/
int factor = 2;
isPrime = false;
++factor;
}
if (isPrime) System.out.println(number + " is a prime");
Example (continue):
/*
*/
int sum = 0;
/*
*/
int number = 1;
while(true) {
++number;
if ((number % 3) == 0) continue;
if ((number % 2) == 0) {
number += 3;
} else {
number -= 3;
Labeled break
In a nested loop, the break statement breaks out the innermost loop and
continue into the outer loop. At times, there is a need to break out all
the loops (or multiple loops). This is clumsy to achieve with boolean flag,
but can be done easily via the so-called labeled break. You can add a label
to a loop in the form of labelName: loop. For example,
for (.....) {
for (.....) {
if (...) break level1; // break all loops, continue after the loop
......
}
Labeled continue
In a nested loop, similar to labeled break, you can use labeled continue
to continue into a specified loop. For example,
for (.....) {
for (.....) {
......
Again, labeled break and continue are not structured and hard to read. Use
them only if absolutely necessary.
Example (Labeled break): Suppose that you are searching for a particular
number in a 2D array.
3 int[][] testArray = {
4 {1, 2, 3, 4},
5 {4, 3, 1, 4},
6 {9, 2, 3, 4}
7 };
9 int magicNumber = 8;
11 mainLoop:
14 if (testArray[i][j] == magicNumber) {
15 found = true;
16 break mainLoop;
17 }
18 }
19 }
The return statement: You could also use a "return returnValue" statement
in the main() method to terminate the program and return control back to
the Java Runtime. For example,
...
...
Try out the following program, which prints a 8-by-8 checker box pattern
using nested loops, as follows:
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
/*
8 for (int col = 1; col <= size; ++col) { // Inner loop to print
all the columns of each row
9
System.out.print("# ");
10
}
11
System.out.println(); // A row ended, bring the cursor to
12
the next line
13
}
14
}
This program contains two nested for-loops. The inner loop is used to print
a row of eight "# ", which is followed by printing a newline. The outer loop
repeats the inner loop to print all the rows.
Suppose that you want to print this pattern instead (in program called
PrintCheckerPattern):
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
You need to print an additional space for even-number rows. You could do
so by adding the following statement before Line 8.
System.out.print(" ");
TRY:
# * # * # * # * # # # # # # # # # # # # # # # # 1
1
# * # * # * # * # # # # # # # # # # # # # # 2 1
1 2
# * # * # * # * # # # # # # # # # # # # 3 2 1
1 2 3
# * # * # * # * # # # # # # # # # # 4 3 2 1
1 2 3 4
# * # * # * # * # # # # # # # # 5 4 3 2 1
1 2 3 4 5
# * # * # * # * # # # # # # 6 5 4 3 2
1 1 2 3 4 5 6
# * # * # * # * # # # # 7 6 5 4 3
2 1 1 2 3 4 5 6 7
# * # * # * # * # # 8 7 6 5 4
3 2 1 1 2 3 4 5 6 7 8
2. Hints:
The equations for major and opposite diagonals are row = col
and row + col = size + 1. Decide on what to print above and below
the diagonal.
3. Print the timetable of 1 to 9, as follows, using nested loop.
(Hints: you need to use an if-else statement to check whether
the product is single-digit or double-digit, and print an
additional space if needed.)
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
......
4.
5. Print these patterns using nested loop.
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # #
6.
if (i == 0)
if (j == 0)
The else clause in the above codes is syntactically applicable to both the
outer-if and the inner-if. Java compiler always associate the else clause
with the innermost if (i.e., the nearest if). Dangling else can be resolved
by applying explicit parentheses. The above codes are logically incorrect
and require explicit parentheses as shown below.
if ( i == 0) {
} else {
System.out.println("PASS");
} else {
System.out.println("FAIL");
How to ensure that your program always produces correct result, 100% of the
times? It is impossible to try out all the possible outcomes, even for a
simple program. Program testing usually involves a set of representative
test cases, which are designed to catch the major classes of errors. Program
testing is beyond the scope of this writing.
7. Input/Output
Java SE 5 introduced a new method called printf() for formatted output (which
is modeled after C Language's printf()). printf() takes the following form:
Examples:
Hi,Hello**88
Hi, 8 5.56
Hi,Hi**&**5.50
Take note that printf() does not advance the cursor to the next line after
printing. You need to explicitly print a newline character at the end of
the formatting-string to advance the cursor to the next line, if desires.
[In C program, we often use '\n' to print a newline, which results in
non-portable program. You should use format specifier "%n" instead.]
There are many more format specifiers in Java. Refer to JDK Documentation
for the detailed descriptions.
(Also take note that printf() take a variable number of arguments (or
varargs), which is a new feature introduced in JDK 1.5 in order to support
printf())
7.2 Input From Keyboard via "Scanner" (JDK 1.5)
Java, like all other languages, supports three standard input/output streams:
System.in (standard input device), System.out (standard output device), and
System.err (standard error device). The System.in is defaulted to be the
keyboard; while System.out and System.err are defaulted to the console. They
can be re-directed to other devices, e.g., it is quite common to redirect
System.err to a disk file to save these error message.
You can read input from keyboard via System.in (standard input device).
/*
// Declare variables
int num1;
double num2;
String str;
in.close();
You can also use method nextLine() to read in the entire line, including
white spaces, but excluding the terminating newline.
/*
*/
System.out.printf("%s%n", str);
in.close();
The Scanner supports many other input formats. Check the JDK documentation
page, under package java.util ⇒ class Scanner ⇒ Method.
Other than scanning System.in (keyboard), you can connect your Scanner to
scan any input source, such as a disk file or a network socket, and use the
same set of methods nextInt(), nextDouble(), next(), nextLine() to parse
the next int, double, String and line. For example,
To open a file via new File(filename), you need to handle the so-called
FileNotFoundException, i.e., the file that you are trying to open cannot
be found. Otherwise, you cannot compile your program. There are two ways
to handle this exception: throws or try-catch.
/*
*/
int num1;
double num2;
String name;
in.close();
To run the above program, create a text file called in.txt containing:
1234
55.66
Paul
/*
* Input from File.
*/
int num1;
double num2;
String name;
in.close();
/*
* Output to File.
*/
import java.io.File;
}
Run the above program, and check the outputs in text file "out.txt".
/*
* Output to File.
*/
import java.io.File;
}
}
You can also get inputs from users via a graphical dialog box, using the
JOptionPane class. For example, the following program prompts the user to
enter the radius of a circle, and computes the area.
1 /*
3 */
7 String radiusStr;
13 area = radius*radius*Math.PI;
14 System.out.println("The area is " + area);
15 }
To use the new Console class, you first use System.console() to retrieve
the Console object corresponding to the current system console.
You can then use methods such as readLine() to read a line. You can optionally
include a prompting message with format specifiers (e.g., %d, %s) in the
prompting message.
You can use con.printf() for formatted output with format specifiers such
as %d, %s. You can also connect the Console to a Scanner for formatted input,
i.e., parsing primitives such as int, double, for example,
Scanner in = new Scanner(con.reader()); // Use Scanner to scan the
Console// Use the Scanner's methods such as nextInt(), nextDouble() to parse
primitives
Example:
/*
*/import java.io.Console;
import java.util.Scanner;
if (con == null) {
System.exit(1);
in.close();
The Console class also provides a secure mean for password entry via method
readPassword(). This method disables input echoing and keep the password
in a char[] instead of a String. The char[] containing the password can be
and should be overwritten, removing it from memory as soon as it is no longer
needed. (Recall that Strings are immutable and cannot be overwritten. When
they are longer needed, they will be garbage-collected at an unknown
instance.)
/*
*/
import java.io.Console;
import java.util.Arrays;
System.exit(1);
if (checkPassword(login, password)) {
// Continue ...
return true;
8. Arrays
Suppose that you want to find the average of the marks for a class of 30
students, you certainly do not want to create 30 variables: mark1, mark2, ...,
mark30. Instead, You could use a single variable, called an array, with 30
elements.
An array is an ordered collection of elements of the same type, identified
by a pair of square brackets [ ]. To use an array, you need to:
1. Declare the array with a name and a type. Use a plural name for array,
e.g., marks, rows, numbers. All elements of the array belong to the
same type.
2. Allocate the array using new operator, or through
initialization, e.g.,
int[] numbers = {11, 22, 33, 44, 55, 66}; // size of array deduced
from the number of items
3.
When an array is constructed via the new operator, all the elements are
initialized to their default value, e.g., 0 for int, 0.0 for double, false
for boolean, and null for objects. [Unlike C/C++, which does NOT initialize
the array contents.]
You can refer to an element of an array via an index (or subscript) enclosed
within the square bracket [ ]. Java's array index begins with zero (0). For
example, suppose that marks is an int array of 5 elements, then the 5 elements
are: marks[0], marks[1], marks[2], marks[3], and marks[4].
int[] marks = new int[5]; // Declare & allocate a 5-element int array//
Assign values to the elements
marks[0] = 95;
marks[1] = 85;
marks[2] = 77;
marks[3] = 69;
marks[4] = 66;
System.out.println(marks[0]);
System.out.println(marks[3] + marks[4]);
To create an array, you need to known the length (or size) of the array in
advance, and allocate accordingly. Once an array is created, its length is
fixed and cannot be changed. At times, it is hard to ascertain the length
of an array (e.g., how many students?). Nonetheless, you need to estimate
the length and allocate an upper bound. This is probably the major drawback
of using an array.
Unlike languages like C/C++, Java performs array index-bound check at the
runtime. In other words, for each reference to an array element, the index
is checked against the array's length. If the index is outside the range
of [0, arrayName.legnth-1], the Java Runtime will signal an exception called
ArrayIndexOutOfBoundException. It is important to note that checking array
index-bound consumes computation power, which inevitably slows down the
processing. However, the benefits gained in terms of good software
engineering out-weight the slow down in speed.
Arrays works hand-in-hand with loops. You can process all the elements of
an array via a loop, for example,
1 /*
3 */
7 int sum = 0;
8 int sumSq = 0;
12 sum += marks[i];
13 sumSq += marks[i]*marks[i];
14 }
15 mean = (double)sum/count;
20 }
JDK 1,5 introduces a new loop syntax known as enhanced for-loop (or for-each
loop) to facilitate processing of arrays and collections. It takes the
following syntax:
Syntax Example
It shall be read as "for each element in the array...". The loop executes
once for each element in the array, with the element's value copied into
the declared variable. The for-each loop is handy to transverse all the
elements of an array or a collection. It requires fewer lines of codes,
eliminates the loop counter and the array index, and is easier to read.
However, for array of primitive types (e.g., array of ints), it can read
the elements only, and cannot modify the array's contents. This is because
each element's value is copied into the loop's variable (pass-by-value),
instead of working on its original copy.
In many situations, you merely want to transverse thru the array and read
each of the elements. For these cases, enhanced for-loop is preferred and
recommended over other loop constructs.
grid[0][0] = 8;
grid[1][1] = 5;
System.out.println(grid.length); // 12
System.out.println(grid[0].length); // 8
System.out.println(grid[11].length); // 8
// Fill in grid
}
// Print grid
System.out.printf("%3d", grid[row][col]);
System.out.println();
Take note that the right way to view the "array of arrays" is as shown, instead
of treating it as a 2D table, even if all the arrays have the same length.
For example,
1 public class Array2DWithDifferentLength {
3 int[][] grid = {
4 {1, 2},
5 {3, 4, 5},
6 {6, 7, 8, 9}
7 };
9 // Print grid
12 System.out.printf("%2d", grid[y][x]);
13 }
14 System.out.println();
15 }
16
21
25 System.out.printf("%2d", grid1[y][x]);
26 }
27 System.out.println();
28 }
29 }
30 }
9. Methods (Functions)
1. Divide and conquer: construct the program from simple, small pieces
or components. Modularize the program into self-contained tasks.
2. Avoid repeating codes: It is easy to copy and paste, but hard to
maintain and synchronize all the copies.
3. Software Reuse: you can reuse the methods in other programs, by
packaging them into library codes.
Two parties are involved in using a method: a caller, who calls or invokes
the method, and the method called.
Example: Suppose that we need to evaluate the area of a circle many times,
it is better to write a method called getArea(), and re-use it when needed.
6 area = getArea(r);
9 area2 = getArea(2.2);
13 }
14
15 // Method getArea() Eefinition.
16 // Compute and return the area (in double) of circle given its radius
(in double).
17
public static double getArea(double radius) {
18
return radius * radius * Math.PI;
19
}
20
}
area is 3.8013271108436504
area 2 is 15.205308443374602
area 3 is 34.21194399759284
Take note that there is a transfer of control from the caller to the method
called, and from the method back to the caller, as illustrated.
Another Example:
Inside the method body, you could use a return statement to return a value
(of the returnValueType declared in the method's signature) to return a value
back to the caller. The syntax is:
Suppose that you need a method to perform certain actions (e.g., printing)
without a need to return a value to the caller, you can declare its
return-value type as void. In the method's body, you could use a "return;"
statement without a return value to return control to the caller. In this
case, the return statement is optional. If there is no return statement,
the entire body will be executed, and control returns to the caller at the
end of the body.
Recall that a method receives arguments from its caller, performs the actions
defined in the method's body, and return a value (or nothing) to the caller.
In the above example, the variable (double radius) declared in the signature
of getArea(double radius) is known as formal parameter. Its scope is within
the method's body. When the method is invoked by a caller, the caller must
supply so-called actual parameters or arguments, whose value is then used
for the actual computation. For example, when the method is invoked via
"area1=getArea(radius1)", radius1 is the actual parameter, with a value of
1.1.
For example,
9 }
10
9.7 Varargs - Method with Variable Number of Formal Arguments (JDK 1.5)
Before JDK 1.5, a method has to be declared with a fixed number of formal
arguments. C-like printf(), which take a variable number of argument, cannot
not be implemented. Although you can use an array for passing a variable
number of arguments, it is not neat and requires some programming efforts.
JDK 1.5 introduces variable arguments (or varargs) and a new syntax "Type...".
For example,
Varargs can be used only for the last argument. The three dots (...) indicate
that the last argument may be passed as an array or as a sequence of
comma-separated arguments. The compiler automatically packs the varargs
into an array. You could then retrieve and process each of these arguments
inside the method's body as an array. It is possible to pass varargs as an
array, because Java maintains the length of the array in an associated
variable length.
public class VarargsTest {
1
// A method which takes a variable number of arguments (varargs)
2
public static void doSomething(String... strs) {
3
System.out.print("Arguments are: ");
4
for (String str : strs) {
5
System.out.print(str + ", ");
6
}
7
System.out.println();
8
}
9
10
// A method which takes exactly two arguments
11
public static void doSomething(String s1, String s2) {
12
System.out.println("Overloaded version with 2 args: " + s1 + ",
13
" + s2);
14
}
15
16
// Cannot overload with this method - crash with varargs version
17
// public static void doSomething(String[] strs)
18
19
// Test main() method
20
// Can also use String... instead of String[]
21
public static void main(String... args) {
22
doSomething("Hello", "world", "again", "and", "again");
23
doSomething("Hello", "world");
24
25
String[] strs = {"apple", "orange"};
26 doSomething(strs); // invoke varargs version
27 }
28 }
Notes:
In Java, a method (of a particular method name) can have more than one
versions, each version operates on different set of parameters - known as
method overloading. The versions shall be differentiated by the numbers,
types, or orders of the parameters.
For example,
System.out.println(average(8, 6.1));
System.out.println("version 1");
System.out.println("version 2");
System.out.println("version 3");
version 1
version 2
version 3
7.1
version 3
7.05
1 /**
3 */
7 if (number % 2 == 1) {
8 return true;
9 } else {
10 return false;
11 }
12 }
13
15 System.out.println(isOdd(5)); // true
16 System.out.println(isOdd(6)); // false
17 System.out.println(isOdd(-5)); // false
18 }
19 }
This seemingly correct codes produces false for -5, because -5%2 is -1
instead of 1. You may rewrite the condition:
if (number % 2 == 0) {
return false;
} else {
return true;
The above produces the correct answer, but is poor. For boolean method, you
can simply return the resultant boolean value of the comparison, instead
of using a conditional statement, as follow:
double Math.sin()
double Math.cos()
Math.PI // 3.141592653589793
Math.E // 2.718281828459045
To check all the available methods, open JDK API documentation ⇒ select
package "java.lang" ⇒ select class "Math" ⇒ choose method.
For examples,
int x1 = 1, y1 = 1, x2 = 2, y2 = 2;
int dx = x2 - x1;
int dy = y2 - y1;
A method that takes a double parameter can accept any numeric primitive type,
such as int or float. This is because implicit type-casting is carried out.
However, a method that take a int parameter cannot accept a double value.
This is because the implicit type-casting is always a widening conversion
which prevents loss of precision. An explicit type-cast is required for
narrowing conversion. Read "Type-Casting" on the conversion rules.
9.12 Exercises on Methods
Each argument, i.e., "12", "3456" and "+", is a String. Java runtime packs
all the arguments into a String array and passes into the main() method as
args. For this example, args has the following properties:
args[1] = "3456"
args[2] = "+"
args[1].length() = 4
args[2].length() = 1
Example: The program Arithmetic reads three parameters form the command-line,
two integers and an arithmetic operator ('+', '-', '*', or '/'), and performs
the arithmetic operation accordingly. For example,
java Arithmetic 3 2 +
3+2=5java Arithmetic 3 2 -
3-2=1java Arithmetic 3 2 /
3/2=1
public class Arithmetic {
1
public static void main (String[] args) {
2
int operand1, operand2;
3
char theOperator;
4
operand1 = Integer.parseInt(args[0]); // Convert String to int
5
operand2 = Integer.parseInt(args[1]);
6
theOperator = args[2].charAt(0); // Consider only 1st
7
character
8
System.out.print(args[0] + args[2] + args[1] + "=");
9
switch(theOperator) {
10
case ('+'):
11
System.out.println(operand1 + operand2); break;
12
case ('-'):
13
System.out.println(operand1 - operand2); break;
14
case ('*'):
15
System.out.println(operand1 * operand2); break;
16
case ('/'):
17
System.out.println(operand1 / operand2); break;
18
default:
19
System.out.printf("%nError: Invalid operator!");
20
}
21
}
22
}
11.1 EG 1: Bin2Dec
Version 1:
/*
* Prompt user for a binary string, and convert into its equivalent decimal
number.
*/
import java.util.Scanner;
// Read input
binStr = in.next();
binStrLen = binStr.length();
if (binChar == '1') {
System.exit(1); // quit
// Print result
in.close();
binStr : 1 0 1 1 1 0 0 1
binStr.length() = 8
Version 2:
/*
* Prompt user for a binary string, and convert into its equivalent decimal
number.
* Validate the input string.
*/
import java.util.Scanner;
while (!done) {
if (inStr.equals("q")) {
System.out.println("Bye!");
done = true;
} else if (!isValidBinStr(inStr)) {
} else {
in.close();
}
// Return true if the given string contains only binary numbers and
blanks.
return true;
// 3 cases: '1' (add to dec, ++exp), '0' (++exp), ' ' (do nothing)
if (binChar == '1') {
dec += (int)Math.pow(2, exp);
++exp;
++exp;
return dec;
11.2 EG 2: Hex2Dec
/*
* Prompt user for the hexadecimal string, and convert to its equivalent
decimal number
*/
import java.util.Scanner;
// Read input
hexStr = in.next();
hexStrLen = hexStr.length();
} else {
System.exit(1);
in.close();
You may use in.next().toLowercase() to reduce the number of cases. But that
modifies the input string.
11.3 EG 3: Dec2Hex
/*
* Prompt user for an int, and convert to its equivalent hexadecimal number.
*/
import java.util.Scanner;
// Read input
dec = in.nextInt();
in.close();
11.4 EG 4: Hex2Bin
/*
*/
import java.util.Scanner;
// Lookup table for the binary string corresponding to Hex digit '0'
(index 0) to 'F' (index 15)
String[] binStrs
= {"0000","0001","0010","0011","0100","0101","0110","0111",
"1000","1001","1010","1011","1100","1101","1110","1111"};
// Read input
Scanner in = new Scanner(System.in);
hexStr = in.next();
hexStrLen = hexStr.length();
binStr += binStrs[hexChar-'a'+10];
binStr += binStrs[hexChar-'A'+10];
} else {
System.exit(1); // quit
in.close();
import java.util.Scanner;
secretNumber = (int)(Math.random()*100);
while (!done) {
++trialNumber;
numberIn = in.nextInt();
if (numberIn == secretNumber) {
System.out.println("Congratulation");
done = true;
System.out.println("Try higher");
} else {
System.out.println("Try lower");
}
in.close();
Example
1
public class TestBitwiseOp {
2
public static void main(String[] args) {
3
int x = 0xAAAA_5555; // a negative number (sign
4 bit (msb) = 1)
Compound operator &=, |= and ^= are also available, e.g., x &= y is the same
as x = x & y.
1. '&', '|' and '^' are applicable when both operands are integers
(int, byte, short, long and char) or booleans. When both
operands are integers, they perform bitwise operations. When
both operands are booleans, they perform logical AND, OR, XOR
operations (i.e., same as logical &&, || and ^). They are not
applicable to float and double. On the other hand, logical AND
(&&) and OR (||) are applicable to booleans only.
2.
3. The bitwise NOT (or bit inversion) operator is represented as '~',
which is different from logical NOT (!).
4. The bitwise XOR is represented as '^', which is the same as logical
XOR (^).
5. The operators' precedence is in this order: '~', '&', '^', '|',
'&&', '||'. For example,
6.
operand <<
<< Left-shift and padded with zeros
number
Since all the Java's integers (byte, short, int and long) are signed integers,
left-shift << and right-shift >> operators perform signed-extended bit shift.
Signed-extended right shift >> pads the most significant bits with the sign
bit to maintain its sign (i.e., padded with zeros for positive numbers and
ones for negative numbers). Operator >>> (introduced in Java, not in C/C++)
is needed to perform unsigned-extended right shift, which always pads the
most significant bits with zeros. There is no difference between the
signed-extended and unsigned-extended left shift, as both operations pad
the least significant bits with zeros.
Example
18
// More efficient to use signed-right-right to perform division
19 by 2, 4, 8,...
20 int i1 = 12345;
24 int i2 = -12345;
13. Algorithms
Before writing a program to solve a problem, you have to first develop the
steps involved, called algorithm, and then translate the algorithm into
programming statements. This is the hardest part in programming, which is
also hard to teach because the it involves intuition, knowledge and
experience.
assume x is a prime;
if (x is divisible by factor) {
x is not a prime;
TRY: translate the above pseudocode into a Java program called PrimeTest.
13.2 Algorithm for Perfect Numbers
A positive integer is called a perfect number if the sum of all its proper
divisor is equal to its value. For example, the number 6 is perfect because
its proper divisors are 1, 2, and 3, and 6=1+2+3; but the number 10 is not
perfect because its proper divisors are 1, 2, and 5, and 10≠1+2+5. Other
perfect numbers are 28, 496, ...
int sum = 0;
if (x is divisible by i) {
i is a proper divisor;
if (sum == x)
x is a perfect number
else
1. GCD(a, 0) = a
2. GCD(a, b) = GCD(b, a mod b), where "a mod b" denotes the remainder of
a divides by b.
For example,
GCD(15, 5) = GCD(5, 0) = 5
temp ← b
b ← a mod b
a ← temp
GCD is a
Before explaining the algorithm, suppose we want to exchange (or swap) the
values of two variables x and y. Explain why the following code does not
work.
x = y;
y = x;
To swap the values of two variables, we need to define a temporary variable
as follows:
temp = y;
y = x;
x = temp;
14. Summary