CHAPTER 1 Java Review
CHAPTER 1 Java Review
1
Java, Web, and Beyond
• Java can be used to develop Web applications.
• Java Applets
• Java Web Applications
• Java can also be used to develop applications for
hand-held devices such as Palm and cell phones
2
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
3
JDK Editions
• Java Standard Edition (JSE)
• JSE can be used to develop client-side standalone applications
or applets.
• Java Enterprise Edition (JEE)
• JEE can be used to develop server-side applications such as
Java servlets and Java ServerPages.
• Java Micro Edition (JME).
• JME can be used to develop applications for mobile devices
such as cell phones.
• Popular Java IDE:
NetBeans Open Source by Sun
Eclipse Open Source by IBM
4
A Simple Java Program
5
Compiling Java Source Code
Java was designed to run object programs on any platform. With Java, you
write the program once, and compile the source program into a special type of
object code, known as bytecode.
The source program must be recompiled, however, because the object
program can only run on a specific machine. Nowadays computers are
networked to work together.
The bytecode can then run on any computer with a Java Virtual Machine, as
shown below. Java Virtual Machine is a software that interprets Java bytecode.
Java Bytecode
Java Virtual
Machine
Any
Computer
6
Comments
Three types of comments in Java.
8
Modifiers
Java uses certain reserved words called modifiers
that specify the properties of the data, methods, and
classes and how they can be used.
Examples of modifiers are public and static. Other
modifiers are private, final, abstract, and protected.
A public datum, method, or class can be accessed by
other programs.
A private datum or method cannot be accessed by
other programs.
9
Statements
A statement represents an action or a sequence of actions.
The statement System.out.println("Welcome to Java!") is a
statement to display the greeting "Welcome to Java!" Every
statement in Java ends with a semicolon (;).
Block: A pair of braces in a program forms a block that groups
components of a program.
10
Classes
The class is the essential Java construct.
A class is a template or blueprint for objects. To
program in Java, you must understand classes and be
able to write and use them.
The mystery of the class will continue to be unveiled
throughout this course.
For now, though, understand that a program is defined
by using one or more classes.
11
Methods
What is System.out.println?
It is a method: a collection of statements that performs
a sequence of operations to display a message on the
console.
It can be used even without fully understanding the
details of how it works.
It is used by invoking a statement with a string
argument. The string argument is enclosed within
parentheses.
In this case, the argument is "Welcome to Java!" You can
call the same println method with a different argument to
print a different message.
12
Trace a Program Execution
public class ComputeArea { allocate memory
for radius
/** Main method */
public static void main(String[] args) {
radius no value
double radius;
double area;
// Assign a radius
radius = 20;
// Compute area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
13
Trace a Program Execution
public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
radius no value
double radius;
area no value
double area;
// Assign a radius
radius = 20; allocate memory
for area
// Compute area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
14
Trace a Program Execution
public class ComputeArea { assign 20 to radius
/** Main method */
public static void main(String[] args) {
radius 20
double radius;
double area; area no value
// Assign a radius
radius = 20;
// Compute area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
15
Trace a Program Execution
public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
radius 20
double radius;
double area; area 1256.636
// Assign a radius
radius = 20;
compute area and assign
it to variable area
// Compute area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
16
Trace a Program Execution
public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
radius 20
double radius;
double area; area 1256.636
// Assign a radius
radius = 20;
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
17
Reading Input from the Console
18
Identifiers
• An identifier is a sequence of characters that consist of letters,
digits, underscores (_), and dollar signs ($).
• An identifier must start with a letter, an underscore (_), or a
dollar sign ($). It cannot start with a digit.
• An identifier cannot be a reserved word.
• An identifier cannot be true, false, or null.
• An identifier can be of any length.
19
Variables
// Compute the first area
radius = 1.0;
area = radius * radius * 3.14159;
System.out.println("The area is “ + area + " for
radius "+radius);
22
Numerical Data Types
23
Numeric Operators
Name Meaning Example Result
+ Addition 34 + 1 35
% Remainder 20 % 3 2
Numeric Operators:
5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5
5 % 2 yields 1 (the remainder of the division)
24
Remainder Operator
Remainder is very useful in programming. For example, an even
number % 2 is always 0 and an odd number % 2 is always 1.
So you can use this property to determine whether a number is
even or odd.
Suppose today is Saturday and you and your friends are
going to meet in 10 days. What day is in 10 days? You can
find that day is Tuesday using the following expression:
25
NOTE
Calculations involving floating-point numbers are
approximated because these numbers are not stored with
complete accuracy.
For example,
System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);
displays 0.5000000000000001, not 0.5, and
System.out.println(1.0 - 0.9);
displays 0.09999999999999998, not 0.1. Integers are stored
precisely.
Therefore, calculations with integers yield a precise integer
result. 26
Number Literals
A literal is a constant value that appears directly
in the program. For example, 34, 1,000,000, and
5.0 are literals in the following statements:
int i = 34;
long x = 1000000;
double d = 5.0;
27
Integer Literals
An integer literal can be assigned to an integer variable as
long as it can fit into the variable. A compilation error
would occur if the literal were too large for the variable to
hold. For example, the statement byte b = 1000 would
cause a compilation error, because 1000 cannot be stored
in a variable of the byte type.
An integer literal is assumed to be of the int type, whose
value is between -231 (-2147483648) to 231–1
(2147483647). To denote an integer literal of the long
type, append it with the letter L or l. L is preferred
because l (lowercase L) can easily be confused with 1 (the
digit one).
28
Floating-Point Literals
Floating-point literals are written with a decimal point. By
default, a floating-point literal is treated as a double type
value. For example, 5.0 is considered a double value, not a
float value. You can make a number a float by appending
the letter f or F, and make a number a double by
appending the letter d or D. For example, you can use
100.2f or 100.2F for a float number, and 100.2d or 100.2D
for a double number.
29
Scientific Notation
Floating-point literals can also be specified in
scientific notation, for example, 1.23456e+2,
same as 1.23456e2, is equivalent to 123.456,
and 1.23456e-2 is equivalent to 0.0123456. E (or
e) represents an exponent and it can be either in
lowercase or uppercase.
30
How to Evaluate an Expression
Though Java has its own way to evaluate an
expression behind the scene, the result of a Java
expression and its corresponding arithmetic
expression are the same. Therefore, you can safely
apply the arithmetic rule for evaluating a Java
expression. 3 + 4 * 4 + 5 * (4 + 3) - 1
(1) inside parentheses first
3 + 4 * 4 + 5 * 7 – 1
(2) multiplication
3 + 16 + 5 * 7 – 1
(3) multiplication
3 + 16 + 35 – 1
(4) addition
19 + 35 – 1
(5) addition
54 - 1
(6) subtraction
53
31
Shortcut Assignment Operators
Operator Example Equivalent
+= i += 8 i = i + 8
-= f -= 8.0 f = f - 8.0
*= i *= 8 i = i * 8
/= i /= 8 i = i / 8
%= i %= 8 i = i % 8
32
Increment and Decrement Operators
Operator Name Description
++var preincrement The expression (++var) increments var by 1 and evaluates
to the new value in var after the increment.
var++ postincrement The expression (var++) evaluates to the original value
in var and increments var by 1.
--var predecrement The expression (--var) decrements var by 1 and evaluates
to the new value in var after the decrement.
var-- postdecrement The expression (var--) evaluates to the original value
in var and decrements var by 1.
33
Numeric Type Conversion
Consider the following statements:
byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;
34
Conversion Rules
When performing a binary operation involving two
operands of different types, Java automatically
converts the operand based on the following rules:
35
Type Casting
Implicit casting
double d = 3; (type widening)
Explicit casting
int i = (int)3.0; (type narrowing)
int i = (int)3.9; (Fraction part is
truncated)
What is wrong? int x = 5 / 2.0;
range increases
36
Casting between char and
Numeric Types
int i = 'a'; // Same as int i = (int)'a';
37
Escape Sequences for Special Characters
Description Escape Sequence Unicode
Backspace \b \u0008
Tab \t \u0009
Line feed \n \u000A
Carriage return \r \u000D
Backslash \\ \u005C
Single Quote \' \u0027
Double Quote \" \u0022
38
The String Type
The char type only represents one character. To represent a string of
characters, use the data type called String. For example,
String is actually a predefined class in the Java library just like the
System class and JOptionPane class.
The String type is not a primitive type. It is known as a reference type.
Any Java class can be used as a reference type for a variable.
For the time being, you just need to know how to declare a String
variable, how to assign a string to the variable, and how to concatenate
strings.
39
String Concatenation
// Three strings are concatenated
String message = "Welcome " + "to " + "Java";
40
Programming Style and
Documentation
• Appropriate Comments
• Naming Conventions
• Proper Indentation and Spacing
Lines
• Block Styles
41
Appropriate Comments
Include a summary at the beginning of the program to
explain what the program does, its key features, its
supporting data structures, and any unique techniques it
uses.
42
Naming Conventions
• Choose meaningful and descriptive names.
• Variables and method names:
• Use lowercase. If the name consists of several words, concatenate
all in one, use lowercase for the first word, and capitalize the first
letter of each subsequent word in the name. For example, the
variables radius and area, and the method computeArea.
• Class names:
• Capitalize the first letter of each word in the name. For example,
the class name ComputeArea.
• Constants:
• Capitalize all letters in constants, and use underscores to connect
words. For example, the constant PI and MAX_VALUE
43
Proper Indentation and Spacing
• Indentation
• Indent two spaces.
• Spacing
• Use blank line to separate segments of the code.
44
Block Styles
Use end-of-line style for braces.
End-of-line
style
public class Test {
public static void main(String[] args) {
System.out.println("Block Styles");
}
}
45
JOptionPane Input
This book provides two ways of obtaining input.
46
Getting Input from Input Dialog Boxes
String string = JOptionPane.showInputDialog(
null, “Prompting Message”, “Dialog Title”,
JOptionPane.QUESTION_MESSAGE);
47
Two Ways to Invoke the Method
There are several ways to use the showInputDialog method.
For the time being, you only need to know two ways to invoke
it.
One is to use a statement as shown in the example:
String string = JOptionPane.showInputDialog(null, x, y,
JOptionPane.QUESTION_MESSAGE); where x is a string for the
prompting message, and y is a string for the title of the
input dialog box.
The other is to use a statement like this:
JOptionPane.showInputDialog(x); where x is a string for the
prompting message.
48
Converting Strings to Integers
The input returned from the input dialog box is a string. If you
enter a numeric value such as 123, it returns “123”.
To obtain the input as a number, you have to convert a string
into a number.
To convert a string into an int value, you can use the static
parseInt method in the Integer class as follows:
49
Converting Strings to Doubles
To convert a string into a double value, you can use the
static parseDouble method in the Double class as
follows:
50
The boolean Type and Operators
Often in a program you need to compare two values,
such as whether i is greater than j. Java provides six
comparison operators (also known as relational
operators) that can be used to compare two values.
51
Comparison Operators
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
52
One-way if Statements
if (radius >= 0) {
area = radius * radius * PI;
if (boolean-expression) { System.out.println("The area"
statement(s);
}
+ " for the circle of radius "
+ radius + " is " + area);
}
false false
Boolean (radius >= 0)
Expression
true true
(A) (B)
53
The Two-way if Statement
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
if (radius >= 0) {
area = radius * radius * 3.14159;
System.out.println("The area for the” +
“circle of radius " + radius + " is " + area);
}
else {
System.out.println("Negative input");
}
54
Multiple Alternative if Statements
55
Logical Operators
Operator Name
! not
&& and
|| or
^ exclusive or
56
switch Statement Rules
The switch-expression
must yield a value of char, switch (switch-expression) {
byte, short, or int type and
must always be enclosed case value1: statement(s)1;
in parentheses. break;
case value2: statement(s)2;
The value1, ..., and valueN must break;
have the same data type as the …
value of the switch-expression.
case valueN: statement(s)N;
The resulting statements in the
case statement are executed when break;
the value in the case statement default: statement(s)-for-default;
matches the value of the switch- }
expression. Note that value1, ...,
and valueN are constant
expressions, meaning that they
cannot contain variables in the
expression, such as 1 + x.
57
switch Statement Rules
The keyword break is optional, switch (switch-expression) {
but it should be used at the end
of each case in order to terminate case value1: statement(s)1;
the remainder of the switch break;
statement. If the break statement
is not present, the next case case value2: statement(s)2;
statement will be executed. break;
…
case valueN: statement(s)N;
The default case, which is
break;
optional, can be used to perform default: statement(s)-for-default;
actions when none of the }
specified cases matches the
switch-expression. The case statements are executed in sequential
order, but the order of the cases (including the
default case) does not matter. However, it is good
programming style to follow the logical sequence of
the cases and place the default case at the end.
58
Conditional Operator
if (x > 0)
y=1
else
y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;
(boolean-expression) ? expression1 : expression2
Ternary operator
Binary operator
Unary operator
59
Conditional Operator
if (num % 2 == 0)
System.out.println(num + “is even”);
else
System.out.println(num + “is odd”);
System.out.println(
(num % 2 == 0)? num + “is even” :
num + “is odd”);
60
Frequently-Used Specifiers
int count = 5;
items
double amount = 45.56;
System.out.printf("count is %d and amount is %f", count, amount);
61
Operator Precedence
1) var++, var--
2) +, - (Unary plus and minus), ++var,--var
3) (type) Casting
4) ! (Not)
5) *, /, % (Multiplication, division, and remainder)
6) +, - (Binary addition and subtraction)
7) <, <=, >, >= (Comparison)
8) ==, !=; (Equality)
9) ^ (Exclusive OR)
10) && (Conditional AND) Short-circuit AND
11) || (Conditional OR) Short-circuit OR
12) =, +=, -=, *=, /=, %= (Assignment operator)
62
(GUI) Confirmation Dialogs
int option = JOptionPane.showConfirmDialog
(null, "Continue");
63
while Loop Flow Chart
int count = 0;
while (loop-continuation-condition) {
while (count < 100) {
// loop-body;
System.out.println("Welcome to Java!");
Statement(s); count++;
} }
count = 0;
Loop
false false
Continuation (count < 100)?
Condition?
true true
Statement(s) System.out.println("Welcome to Java!");
(loop body) count++;
(A) (B)
64
do-while Loop
Statement(s)
(loop body)
true Loop
Continuation
do { Condition?
// Loop body;
false
Statement(s);
} while (loop-continuation-condition);
65
for Loops
for (initial-action; loop- int i;
continuation-condition; for (i = 0; i < 100; i++) {
action-after-each-iteration) { System.out.println(
// loop body; "Welcome to Java!");
Statement(s);
} }
Initial-Action i = 0
Loop
false false
Continuation (i < 100)?
Condition?
true true
Statement(s) System.out.println(
(loop body) "Welcome to Java");
Action-After-Each-Iteration i++
(A) (B)
66
Note
If the loop-continuation-condition in a for loop is omitted,
it is implicitly true. Thus the statement given below in (a),
which is an infinite loop, is correct. Nevertheless, it is
better to use the equivalent loop in (b) to avoid confusion:
Remember: Nested loops, break and continue statements.
67
(GUI) Controlling a Loop with a
Confirmation Dialog
A sentinel-controlled loop can be implemented using a confirmation
dialog. The answers Yes or No to continue or terminate the loop. The
template of the loop may look as follows:
int option = 0;
while (option == JOptionPane.YES_OPTION) {
System.out.println("continue loop");
option = JOptionPane.showConfirmDialog(null, "Continue?");
}
68
Introducing Arrays
Array is a data structure that represents a collection of the
same types of data.
double[] myList = new double[10];
myList reference
myList[0] 5.6
myList[1] 4.5
Array reference myList[2] 3.3
variable
myList[3] 13.2
myList[4] 4
Array element at
myList[5] 34.33 Element value
index 5
myList[6] 34
myList[7] 45.45
myList[8] 99.993
myList[9] 11123
69
Declaring Array Variables
• datatype[] arrayRefVar;
Example:
double[] myList;
70
Creating Arrays
arrayRefVar = new datatype[arraySize];
Example:
myList = new double[10];
71
Declaring and Creating
in One Step
• datatype[] arrayRefVar = new
datatype[arraySize];
double[] myList = new double[10];
72
Declaring, creating, initializing Using the
Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the following
statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
73
Trace Program with Arrays
1 0
}
2 0
values[0] = values[1] + values[4]; 3 0
} 4 0
74
Initializing arrays with input values
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter " + myList.length + " values: ");
for (int i = 0; i < myList.length; i++)
myList[i] = input.nextDouble();
75
Printing arrays
for (int i = 0; i < myList.length; i++) {
System.out.print(myList[i] + " ");
}
//determines largest value;
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
76
Copying Arrays
Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new int[sourceArray.length];
77
The Arrays.sort Method
Since sorting is frequently used in programming, Java provides several
overloaded sort methods for sorting an array of int, double, char, short,
long, and float in the java.util.Arrays class. For example, the following
code sorts an array of numbers and an array of characters.
78
Declaring Variables of Two-dimensional
Arrays and Creating Two-dimensional
Arrays
79
Method
80
Example
public static int sum(int i1, int i2) {
int sum = 0;
for (int i = i1; i <= i2; i++)
sum += i;
return sum;
}
83
Trigonometric Methods
• sin(double a) Examples:
• cos(double a)
Math.sin(0) returns 0.0
• tan(double a) Math.sin(Math.PI / 6)
• acos(double a) returns 0.5
Math.sin(Math.PI / 2)
• asin(double a) returns 1.0
• atan(double a) Math.cos(0) returns 1.0
Math.cos(Math.PI / 6)
returns 0.866
Math.cos(Math.PI / 2)
Radians returns 0
toRadians(90)
84
Exponent Methods
• exp(double a) Examples:
Returns e raised to the power of
a. Math.exp(1) returns 2.71
• log(double a) Math.log(2.71) returns 1.0
Returns the natural logarithm of a. Math.pow(2, 3) returns 8.0
• log10(double a) Math.pow(3, 2) returns 9.0
Returns the 10-based logarithm of Math.pow(3.5, 2.5) returns
a. 22.91765
Math.sqrt(4) returns 2.0
• pow(double a, double b)
Math.sqrt(10.5) returns 3.24
Returns a raised to the power of
b.
• sqrt(double a)
Returns the square root of a.
85
Rounding Methods
• double ceil(double x)
x rounded up to its nearest integer. This integer is returned as a
double value.
• double floor(double x)
x is rounded down to its nearest integer. This integer is returned as a
double value.
• double rint(double x)
x is rounded to its nearest integer. If x is equally close to two integers,
the even one is returned as a double.
• int round(float x)
Return (int)Math.floor(x+0.5).
• long round(double x)
Return (long)Math.floor(x+0.5).
86
min, max, and abs
• max(a, b)and min(a, b) Examples:
Returns the maximum or
minimum of two parameters.
Math.max(2, 3) returns 3
• abs(a)
Math.max(2.5, 3) returns 3.0
Returns the absolute value of the
parameter. Math.min(2.5, 3.6) returns 2.5
• random() Math.abs(-2) returns 2
Returns a random double value Math.abs(-2.1) returns 2.1
in the range [0.0, 1.0).
87
The random Method
Generates a random double value greater than or equal to 0.0 and
less than 1.0 (0 <= Math.random() < 1.0).
Examples:
In general,
88