Download Chapter 1 Introduction to Java

Document related concepts
no text concepts found
Transcript
Advanced Programming
Language
MSc. Nguyen Cao Dat
[email protected]
Chapter I
FUNDAMENTALS OF PROGRAMMING
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
2
Content
 Introduction
 Primitive
Data Types and Operations
 Control Statements
 Loop Statements
 Methods
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
3
Introduction
Why
Java?
- Java is a general purpose programming language.
- Java is the Internet programming language.
- Java can be used to develop Web applications.
- Java can also be used to develop applications for handheld devices such as Palm and cell phone
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
4
Introduction
Examples
of Java’s Versatility
Standalone Application: TicTacToe
Applet:
TicTacToe
Servlets:
Mobile
SelfTest Web site
Computing: Cell phones
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
5
TicTacToe Standalone
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
6
TicTacToe Applet
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
7
SelfTest Website (using Java Servlets)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
8
PDA and Cell Phone
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
9
Introduction
 Java’s
History
– James Gosling and Sun Microsystems
– Oak
– Java, May 20, 1995, Sun World
– HotJava
 The
first Java-enabled Web browser
– Early History Website:
http://java.sun.com/features/1998/05/birthday.html
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
10
Introduction

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 Is Multithreaded
Java Is Dynamic
www.cs.armstrong.edu/liang/intro6e/JavaCharacteristics.pdf
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
11
Introduction

JDK(Java Development Kit) Versions
–
–
–
–
–
–
JDK 1.02 (1995)
JDK 1.1 (1996)
JDK 1.2 (1998)
JDK 1.3 (2000)
JDK 1.4 (2002)
JDK 1.5 (2004) a. k. a. JDK 5 or Java 5
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
12
Introduction

JDK Editions
– Java Standard Edition (J2SE)

J2SE can be used to develop client-side standalone applications or
applets.
– Java Enterprise Edition (J2EE)

J2EE can be used to develop server-side applications such as Java
servlets and Java ServerPages.
– Java Micro Edition (J2ME).

J2ME can be used to develop applications for mobile devices such as
cell phones.
This course uses J2SE to introduce Java programming.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
13
Introduction
A Simple Java Program
//This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
14
Creating, Compiling, and
Running Programs
Create/Modify Source Code
Source code (developed by the programmer)
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
Byte code (generated by the compiler for JVM
to read and interpret, not for you to understand)
…
Method Welcome()
0 aload_0
…
Method void main(java.lang.String[])
0 getstatic #2 …
3 ldc #3 <String "Welcome to
Java!">
5 invokevirtual #4 …
8 return
Saved on the disk
Source Code
Compile Source Code
i.e., javac Welcome.java
If compilation errors
stored on the disk
Bytecode
Run Byteode
i.e., java Welcome
Result
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 If
Pearson
Inc. All
runtime Education,
errors or incorrect
result
rights reserved. 0-13-148952-6
15
Compiling and Running Java
from the Command Window
 Set
path to JDK bin directory
– set path=c:\Program Files\java\jdk1.5.0\bin
 Set
classpath to include the current
directory
– set classpath=.
 Compile
– javac Welcome.java
 Run
– java Welcome
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
16
Introduction

Anatomy of a Java Program
–
–
–
–
–
–
–
–
–
Comments
Package
Reserved words
Modifiers
Statements
Blocks
Classes
Methods
The main method
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
17
Comments
In Java, comments are preceded by two slashes (//) in a
line, or enclosed between /* and */ in one or multiple
lines. When the compiler sees //, it ignores all text after //
in the same line. When it sees /*, it scans for the next */
and ignores any text between /* and */.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
18
Package
The second line in the program (package chapter1;)
specifies a package name, chapter1, for the class
Welcome. IDE compiles the source code in
Welcome.java, generates Welcome.class, and stores
Welcome.class in the chapter1 folder.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
19
Reserved Words
Reserved words or keywords are words that have a
specific meaning to the compiler and cannot be used for
other purposes in the program. For example, when the
compiler sees the word class, it understands that the word
after class is the name for the class. Other reserved words
in Listing 1.1 are public, static, and void. Their use will
be introduced later in the book.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
20
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. Modifiers are discussed in Chapter 6,
“Objects and Classes.”
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
21
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
22
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
23
main Method
The main method provides the control of program flow. The
Java interpreter executes the application by invoking the main
method.
The main method looks like this:
public static void main(String[] args) {
// Statements;
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
24
Displaying Text in a Message
Dialog Box
you can use the showMessageDialog method in
the JOptionPane class. JOptionPane is one of the
many predefined classes in the Java system,
which can be reused rather than “reinventing the
wheel.”
Source
Run
IMPORTANT NOTE: To run the program from the Run
button, (1) set c:\jdk1.5.0\bin for path, and (2) install
slides from the Instructor Resource Website to a
directory (e.g., c:\LiangIR) .
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
25
The showMessageDialog
Method
JOptionPane.showMessageDialog(null,
"Welcome to Java!",
“Display Message",
JOptionPane.INFORMATION_MESSAGE));
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
26
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. (See Appendix A,
“Java Keywords,” for a list of reserved words).
An identifier cannot be true, false, or
null.
 An identifier can be of any length.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
27
Variables
// Compute the first area
radius = 1.0;
area = radius * radius * 3.14159;
System.out.println("The area is “ +
area + " for radius "+radius);
// Compute the second area
radius = 2.0;
area = radius * radius * 3.14159;
System.out.println("The area is “ +
area + " for radius "+radius);
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
28
Declaring Variables
int x;
// Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a;
// Declare a to be a
// character variable;
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
29
Assignment Statements
x = 1;
// Assign 1 to x;
radius = 1.0;
// Assign 1.0 to radius;
a = 'A';
// Assign 'A' to a;
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
30
Declaring and Initializing
in One Step
 int
x = 1;
 double
d = 1.4;
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
31
Constants
final datatype CONSTANTNAME = VALUE;
final double PI = 3.14159;
final int SIZE = 3;
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
32
Numerical Data Types
Name
Range
Storage Size
byte
–27 (-128) to 27–1 (127)
8-bit signed
short
–215 (-32768) to 215–1 (32767)
16-bit signed
int
–231 (-2147483648) to 231–1 (2147483647) 32-bit signed
long
–263 to 263–1
(i.e., -9223372036854775808
to 9223372036854775807)
64-bit signed
float
Negative range:
-3.4028235E+38 to -1.4E-45
Positive range:
1.4E-45 to 3.4028235E+38
32-bit IEEE 754
double
Negative range:
-1.7976931348623157E+308 to
-4.9E-324
Positive range:
4.9E-324 to 1.7976931348623157E+308
64-bit IEEE 754
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
33
Numeric Operators
Name
Meaning
Example
Result
+
Addition
34 + 1
35
-
Subtraction
34.0 – 0.1
33.9
*
Multiplication
300 * 30
9000
/
Division
1.0 / 2.0
0.5
%
Remainder
20 % 3
33.9
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
34
Integer Division
+, -, *, /, and %
5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5
5 % 2 yields 1 (the remainder of the division)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
35
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:
Saturday is the 6th day in a week
A week has 7 days
(6 + 31) % 7 is 2
The 2nd day in a week is Tuesday
January has 31 days
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
36
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
37
Arithmetic Expressions
3  4 x 10( y  5)( a  b  c)
4 9 x

 9( 
)
5
x
x
y
is translated to
(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
38
Example: Converting Temperatures
Write a program that converts a Fahrenheit degree
to Celsius using the formula:
celsius  ( 95 )( fahrenheit  32)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
39
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
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
40
Increment and
Decrement Operators
Operator
++var
Name
preincrement
evaluates
var++
postincrement
--var
predecrement
evaluates
var--
postdecrement
Description
The expression (++var) increments var by 1 and
to the new value in var after the increment.
The expression (var++) evaluates to the original value
in var and increments var by 1.
The expression (--var) decrements var by 1 and
to the new value in var after the decrement.
The expression (var--) evaluates to the original value
in var and decrements var by 1.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
41
Increment and
Decrement Operators, cont.
int i = 10;
int newNum = 10 * i++;
Same effect as
int i = 10;
int newNum = 10 * (++i);
int newNum = 10 * i;
i = i + 1;
Same effect as
i = i + 1;
int newNum = 10 * i;
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
42
Increment and
Decrement Operators, cont.
Using increment and decrement operators makes
expressions short, but it also makes them complex and
difficult to read. Avoid using these operators in expressions
that modify multiple variables, or the same variable for
multiple times
Such as this: int k = ++i + i.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
43
Assignment Expressions and
Assignment Statements
Prior to Java 2, all the expressions can be used as
statements. Since Java 2, only the following types of
expressions can be statements:
variable op= expression; // Where op is +, -, *, /, or %
++variable;
variable++;
--variable;
variable--;
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
44
Numeric Type Conversion
Consider the following statements:
byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
45
Conversion Rules
When performing a binary operation involving two
operands of different types, Java automatically
converts the operand based on the following rules:
1. If one of the operands is double, the other is
converted into double.
2. Otherwise, if one of the operands is float, the other is
converted into float.
3. Otherwise, if one of the operands is long, the other is
converted into long.
4. Otherwise, both operands are converted into int.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
46
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
byte, short, int, long, float, double
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
47
Character Data Type
char letter = 'A'; (ASCII)
char numChar = '4'; (ASCII)
Four hexadecimal digits.
char letter = '\u0041'; (Unicode)
char numChar = '\u0034'; (Unicode)
NOTE: The increment and decrement operators can also be used
on char variables to get the next or preceding Unicode character.
For example, the following statements display character b
char ch = 'a';
System.out.println(++ch);
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
48
Unicode Format
Java characters use Unicode, a 16-bit encoding scheme
established by the Unicode Consortium to support the
interchange, processing, and display of written texts in the
world’s diverse languages. Unicode takes two bytes,
preceded by \u, expressed in four hexadecimal numbers
that run from '\u0000' to '\uFFFF'. So, Unicode can
represent 65535 + 1 characters.
Unicode \u03b1 \u03b2 \u03b3 for three Greek
letters
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
49
Example: Displaying Unicodes
Write a program that displays two Chinese
characters and three Greek letters.
DisplayUnicode
Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
50
Escape Sequences for Special
Characters
Description
Escape Sequence
Unicode
Backspace
\b
\u0008
Tab
\t
\u0009
Linefeed
\n
\u000A
Carriage return \r
\u000D
Backslash
\\
\u005C
Single Quote
\'
\u0027
Double Quote
\"
\u0022
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
51
Appendix B: ASCII Character Set
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
52
ASCII Character Set, cont.
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
53
Casting between char and
Numeric Types
int i = 'a'; // Same as int i = (int)'a';
char c = 97; // Same as char c = (char)97;
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
54
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 message = "Welcome to Java";
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. Reference data types
will be thoroughly discussed in Chapter 6, “Classes and Objects.”
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
55
String Concatenation
// Three strings are concatenated
String message = "Welcome " + "to " + "Java";
// String Chapter is concatenated with number 2
String s = "Chapter" + 2; // s becomes Chapter2
// String Supplement is concatenated with character B
String s1 = "Supplement" + 'B'; // s becomes
SupplementB
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
56
Obtaining Input
1.
2.
Using JOptionPane input dialogs
Using Scanner class
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
57
Getting Input from Input Dialog
Boxes
String string = JOptionPane.showInputDialog(
null, “Prompting Message”, “Dialog Title”,
JOptionPane.QUESTION_MESSAGE));
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
58
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
59
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:
int intValue = Integer.parseInt(intString);
where intString is a numeric string such as “123”.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
60
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:
double doubleValue =Double.parseDouble(doubleString);
where doubleString is a numeric string such as “123.45”.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
61
Example:
Computing Loan Payments
This program lets the user enter the interest
rate, number of years, and loan amount and
computes monthly payment and total
payment.
loanAmount  monthlyInterestRate
1
1
numberOfYears12
(1  monthlyInterestRate)
ComputeLoan
Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
62
Example: Monetary Units
This program lets the user enter the amount in
decimal representing dollars and cents and output
a report listing the monetary equivalent in single
dollars, quarters, dimes, nickels, and pennies.
Your program should report maximum number of
dollars, then the maximum number of quarters,
and so on, in this order.
ComputeChange
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
Run
63
Example: Displaying Current Time
Write a program that displays current time in GMT in the
format hour:minute:second such as 1:45:19.
The currentTimeMillis method in the System class returns
the current time in milliseconds since the midnight, January
1, 1970 GMT. (1970 was the year when the Unix operating
system was formally introduced.) You can use this method
to obtain the current time, and then compute the current
second, minute, and hour as follows.
ShowCurrentTime
Elapsed
time
Time
Unix Epoch
01-01-1970
00:00:00 GMT
Current Time
System.CurrentTimeMills()
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
Run
64
Getting Input Using Scanner
1. Create a Scanner object
Scanner scanner = new Scanner(System.in);
2. Use the methods next(), nextByte(), nextShort(),
nextInt(), nextLong(), nextFloat(), nextDouble(), or
nextBoolean() to obtain to a string, byte, short, int, long,
float, double, or boolean value. For example,
System.out.print("Enter a double value: ");
Scanner scanner = new Scanner(System.in);
double d = scanner.nextDouble();
TestScanner
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
Run
65
Programming Style and
Documentation
 Appropriate
Comments
 Naming Conventions
 Proper Indentation and Spacing
Lines
 Block Styles
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
66
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.
Include your name, class section, instructor, date,
and a brief description at the beginning of the
program.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
67
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
68
Naming Conventions, cont.

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
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
69
Proper Indentation and Spacing
 Indentation
– Indent two spaces.
 Spacing
– Use blank line to separate segments of the code.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
70
Block Styles
Use end-of-line style for braces.
Next-line
style
public class Test
{
public static void main(String[] args)
{
System.out.println("Block Styles");
}
}
public class Test {
public static void main(String[] args) {
System.out.println("Block Styles");
}
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
End-of-line
style
71
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. The result of the
comparison is a Boolean value: true or false.
boolean b = (1 > 2);
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
72
Comparison Operators
Operator Name
<
less than
<=
less than or equal to
>
greater than
>=
greater than or equal to
==
equal to
!=
not equal to
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
73
Boolean Operators
Operator Name
!
not
&&
and
||
or
^
exclusive or
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
74
Examples
System.out.println("Is " + num + " divisible by 2 and 3? " +
((num % 2 == 0) && (num % 3 == 0)));
System.out.println("Is " + num + " divisible by 2 or 3? " +
((num % 2 == 0) || (num % 3 == 0)));
System.out.println("Is " + num +
" divisible by 2 or 3, but not both? " +
((num % 2 == 0) ^ (num % 3 == 0)));
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
75
Example: Determining Leap
Year?
This program first prompts the user to enter a year as
an int value and checks if it is a leap year.
A year is a leap year if it is divisible by 4 but not by
100, or it is divisible by 400.
(year % 4 == 0 && year % 100 != 0) || (year % 400
== 0)
LeapYear
Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
76
Example: A Simple Math Learning
Tool
This example creates a program to let a first grader practice additions.
The program randomly generates two single-digit integers number1
and number2 and displays a question such as “What is 7 + 9?” to the
student, as shown below. After the student types the answer in the
input dialog box, the program displays a message dialog box to
indicate whether the answer is true or false.
AdditionTutor
Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
77
The & and | Operators
&&: conditional AND operator
&: unconditional AND operator
||: conditional OR operator
|: unconditional OR operator
exp1 && exp2
(1 < x) && (x < 100)
(1 < x) & (x < 100)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
78
The & and | Operators
If x is 1, what is x after this
expression?
(x > 1) & (x++ < 10)
If x is 1, what is x after this
expression?
(1 > x) && ( 1 > x++)
How about (1 == x) | (10 > x++)?
(1 == x) || (10 > x++)?
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
79
Selection Statements

if Statements

switch Statements

Conditional Operators
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
80
TIP
if (number % 2 == 0)
even = true;
else
even = false;
Equivalent
boolean even
= number % 2 == 0;
(a)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
(b)
81
CAUTION
if (even == true)
System.out.println(
"It is even.");
Equivalent
if (even)
System.out.println(
"It is even.");
(a)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
(b)
82
Example: An Improved Math Learning
Tool
This example creates a program to teach a first grade child
how to learn subtractions. The program randomly
generates two single-digit integers number1 and number2
with number1 > number2 and displays a question such as
“What is 9 – 2?” to the student, as shown in the figure.
After the student types the answer in the input dialog box,
the program displays a message dialog box to indicate
whether the answer is correct, as shown in figure.
SubtractionTutor
Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
83
Example: Guessing Birth Date
The program can guess your birth date.
Run to see how it works.
GuessBirthDate
Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
84
Conditional Operator, cont.
(booleanExp) ? exp1 : exp2
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
85
JDK 1.5
Feature
Formatting Output
Use the new JDK 1.5 printf statement.
System.out.printf(format, items);
Where format is a string that may consist of substrings and
format specifiers. A format specifier specifies how an item
should be displayed. An item may be a numeric value,
character, boolean value, or a string. Each specifier begins
with a percent sign.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
86
JDK 1.5
Feature
Frequently-Used Specifiers
Specifier Output
Example
%b
a boolean value
true or false
%c
a character
'a'
%d
a decimal integer
200
%f
a floating-point number
45.460000
%e
a number in standard scientific notation
4.556000e+01
%s
a string
"Java is cool"
int count = 5;
items
double amount = 45.56;
System.out.printf("count is %d and amount is %f", count, amount);
display
count is 5 and amount is 45.560000
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
87
Creating Formatted Strings
System.out.printf(format, item1, item2, ...,
itemk)
String.format(format, item1, item2, ..., itemk)
String s = String.format("count is %d and amount is %f", 5, 45.56));
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
88
Operator Precedence














var++, var-+, - (Unary plus and minus), ++var,--var
(type) Casting
! (Not)
*, /, % (Multiplication, division, and remainder)
+, - (Binary addition and subtraction)
<, <=, >, >= (Comparison)
==, !=; (Equality)
& (Unconditional AND)
^ (Exclusive OR)
| (Unconditional OR)
&& (Conditional AND) Short-circuit AND
|| (Conditional OR) Short-circuit OR
=, +=, -=, *=, /=, %= (Assignment operator)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
89
while Loop Flow Chart
while (loop-continuation-condition) {
// loop-body;
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java!");
Statement(s);
count++;
}
}
count = 0;
Loop
Continuation
Condition?
true
Statement(s)
(loop body)
(A)
false
(count < 100)?
false
true
System.out.println("Welcome to Java!");
count++;
(B)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
90
Example: An Advanced Math Learning Tool
The Math subtraction learning tool program
generates just one question for each run. You can
use a loop to generate questions repeatedly. This
example gives a program that generates ten
questions and reports the number of the correct
answers after a student answers all ten questions.
SubtractionTutorLoop
Run
IMPORTANT NOTE: To run the program from the Run
button, (1) set c:\jdk1.5.0\bin for path, and (2) install
slides from the Instructor Resource Website to a
directory (e.g., c:\LiangIR) .
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
91
Ending a Loop with a Sentinel
Value
Often the number of times a loop is executed is not
predetermined. You may use an input value to signify the
end of the loop. Such a value is known as a sentinel value.
Write a program that reads and calculates the sum of an
unspecified number of integers. The input 0 signifies the
end of the input.
SentinelValue
Run
IMPORTANT NOTE: To run the program from the Run
button, (1) set c:\jdk1.5.0\bin for path, and (2) install
slides from the Instructor Resource Website to a
directory (e.g., c:\LiangIR) .
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
92
Caution
Don’t use floating-point values for equality checking in
a loop control. Since floating-point values are
approximations, using them could result in imprecise
counter values and inaccurate results. This example uses
int value for data. If a floating-point type value is used
for data, (data != 0) may be true even though data is 0.
// data should be zero
double data = Math.pow(Math.sqrt(2), 2) - 2;
if (data == 0)
System.out.println("data is zero");
else
System.out.println("data is not zero");
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
93
do-while Loop
Statement(s)
(loop body)
true
do {
// Loop body;
Loop
Continuation
Condition?
false
Statement(s);
} while (loop-continuation-condition);
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
94
for Loops
for (initial-action; loopcontinuation-condition;
action-after-each-iteration) {
// loop body;
Statement(s);
}
Initial-Action
Loop
Continuation
Condition?
int i;
for (i = 0; i < 100; i++) {
System.out.println(
"Welcome to Java!");
}
i=0
false
(i < 100)?
true
Statement(s)
(loop body)
true
System.out.println(
"Welcome to Java");
Action-After-Each-Iteration
i++
(A)
(B)
false
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
95
Note
The initial-action in a for loop can be a list of zero or more
comma-separated expressions. The action-after-eachiteration in a for loop can be a list of zero or more commaseparated statements. Therefore, the following two for
loops are correct. They are rarely used in practice,
however.
for (int i = 1; i < 100; System.out.println(i++));
for (int i = 0, j = 0; (i + j < 10); i++, j++) {
// Do something
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
96
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:
for ( ; ; ) {
// Do something
}
(a)
Equivalent
while (true) {
// Do something
}
(b)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
97
Example: Using for Loops
Problem: Write a program that sums a series that starts
with 0.01 and ends with 1.0. The numbers in the series will
increment by 0.01, as follows: 0.01 + 0.02 + 0.03 and so on.
TestSum
Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
98
Nested Loops
Problem: Write a program that uses nested for loops to
print a multiplication table.
TestMultiplicationTable
Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
99
Example:
Finding the Greatest Common Divisor
Problem: Write a program that prompts the user to enter two positive
integers and finds their greatest common divisor.
Solution: Suppose you enter two integers 4 and 2, their greatest
common divisor is 2. Suppose you enter two integers 16 and 24, their
greatest common divisor is 8. So, how do you find the greatest
common divisor? Let the two input integers be n1 and n2. You know
number 1 is a common divisor, but it may not be the greatest commons
divisor. So you can check whether k (for k = 2, 3, 4, and so on) is a
common divisor for n1 and n2, until k is greater than n1 or n2.
GreatestCommonDivisor
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
Run
100
Example: Finding the Sales
Amount
Problem: You have just started a sales job in a department store. Your
pay consists of a base salary and a commission. The base salary is
$5,000. The scheme shown below is used to determine the
commission rate.
Sales Amount
Commission Rate
$0.01–$5,000
8 percent
$5,000.01–$10,000
10 percent
$10,000.01 and above
12 percent
Your goal is to earn $30,000 in a year. Write a program that will find
out the minimum amount of sales you have to generate in order to
make $30,000.
FindSalesAmount
Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
101
Example:
Displaying a Pyramid of Numbers
Problem: Write a program that prompts the user to enter an integer
from 1 to 15 and displays a pyramid. For example, if the input integer
is 12, the output is shown below.
PrintPyramid
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
Run
102
Using break and continue
Examples for using the break and continue
keywords:

TestBreak.java
TestBreak

Run
TestContinue.java
TestContinue
Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
103
Example: Displaying Prime
Numbers
Problem: Write a program that displays the first 50 prime numbers in
five lines, each of which contains 10 numbers. An integer greater than
1 is prime if its only positive divisor is 1 or itself. For example, 2, 3, 5,
and 7 are prime numbers, but 4, 6, 8, and 9 are not.
Solution: The problem can be broken into the following tasks:
•For number = 2, 3, 4, 5, 6, ..., test whether the number is prime.
•Determine whether a given number is prime.
•Count the prime numbers.
•Print each prime number, and print 10 numbers per line.
PrimeNumber
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
Run
104
Introducing Methods
A method is a collection of statements that are
grouped together to perform an operation.
Define a method
modifier
method
header
return value type
Invoke a method
method name
formal parameters
public static int max(int num1, int num2) {
int z = max(x, y);
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
parameter list
actual parameters
(arguments)
return value
return result;
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
105
Introducing Methods, cont.
• Method signature is the combination of the
method name and the parameter list.
• The variables defined in the method header are
known as formal parameters.
• When a method is invoked, you pass a value to
the parameter. This value is referred to as actual
parameter or argument.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
106
Introducing Methods, cont.
• A method may return a value. The
returnValueType is the data type of the value the
method returns. If the method does not return a
value, the returnValueType is the keyword void.
For example, the returnValueType in the main
method is void.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
107
Calling Methods
Listing 5.1 Testing the max method
This program demonstrates calling a method max
to return the largest of the int values
TestMax
Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
108
Calling Methods, cont.
pass the value of i
pass the value of j
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
return result;
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
109
Reuse Methods from Other
Classes
NOTE: One of the benefits of methods is for reuse. The
max method can be invoked from any class besides
TestMax. If you create a new class Test, you can invoke
the max method using ClassName.methodName (e.g.,
TestMax.max).
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
110
Call Stacks
Space required for the
max method
result: 5
num2: 2
num1: 5
Space required for the
main method
k:
j: 2
i: 5
The main method
is invoked.
Space required for the
main method
k:
j: 2
i: 5
Space required for the
main method
k: 5
j: 2
i: 5
The max method is
invoked.
The max method is
finished and the return
value is sent to k.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
Stack is empty
The main method
is finished.
111
Trace Call Stack
Return result and assign it to k
Space required for the
max method
result: 5
num2: 2
num1: 5
Space required for the
main method
k:5
j: 2
i: 5
The max method is
invoked.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
112
Pass by Value
Listing 5.2 Testing Pass by value
This program demonstrates passing values
to the methods.
TestPassByValue
Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
113
Pass by Value, cont.
The values of num1 and num2 are
passed to n1 and n2. Executing swap
does not affect num1 and num2.
Space required for the
swap method
temp:
n2: 2
n1: 1
Space required for the
main method
num2: 2
num1: 1
The main method
is invoked
Space required for the
main method
num2: 2
num1: 1
The swap method
is invoked
Space required for the
main method
num2: 2
num1: 1
The swap method
is finished
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
Stack is empty
The main method
is finished
114
Overloading Methods
Listing 5.3 Overloading the max Method
public static double max(double num1, double
num2) {
if (num1 > num2)
return num1;
else
return num2;
}
TestMethodOverloading
Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
115
Ambiguous Invocation
Sometimes there may be two or more
possible matches for an invocation of a
method, but the compiler cannot
determine the most specific match. This
is referred to as ambiguous invocation.
Ambiguous invocation is a compilation
error.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
116
Ambiguous Invocation
public class AmbiguousOverloading {
public static void main(String[] args) {
System.out.println(max(1, 2));
}
public static double max(int num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
117
Method Abstraction
You can think of the method body as a black
box that contains the detailed implementation
for the method.
Optional arguments
for Input
Optional return
value
Method Signature
Black Box
Method body
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
118
Benefits of Methods
• Write a method once and reuse it anywhere.
• Information hiding. Hide the implementation
from the user.
• Reduce complexity.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
119
The Math Class
 Class
constants:
– PI
–E
 Class
methods:
– Trigonometric Methods
– Exponent Methods
– Rounding Methods
– min, max, abs, and random Methods
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
120
Trigonometric Methods

sin(double a)

cos(double a)

tan(double a)

acos(double a)

asin(double a)

atan(double a)
Radians
Examples:
Math.sin(0) returns 0.0
Math.sin(Math.PI / 6)
returns 0.5
Math.sin(Math.PI / 2)
returns 1.0
Math.cos(0) returns 1.0
Math.cos(Math.PI / 6)
returns 0.866
Math.cos(Math.PI / 2)
returns 0
toRadians(90)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
121
Exponent Methods

exp(double a)
Returns e raised to the power of a.
Examples:

log(double a)
Returns the natural logarithm of a.

log10(double a)
Math.exp(1) returns 2.71
Math.log(2.71) returns 1.0
Math.pow(2, 3) returns 8.0
Math.pow(3, 2) returns 9.0
Math.pow(3.5, 2.5) returns
22.91765
Math.sqrt(4) returns 2.0
Math.sqrt(10.5) returns 3.24
Returns the 10-based logarithm of
a.

pow(double a, double b)
Returns a raised to the power of b.

sqrt(double a)
Returns the square root of a.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
122
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).
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
123
Rounding Methods Examples
Math.ceil(2.1) returns 3.0
Math.ceil(2.0) returns 2.0
Math.ceil(-2.0) returns –2.0
Math.ceil(-2.1) returns -2.0
Math.floor(2.1) returns 2.0
Math.floor(2.0) returns 2.0
Math.floor(-2.0) returns –2.0
Math.floor(-2.1) returns -3.0
Math.rint(2.1) returns 2.0
Math.rint(2.0) returns 2.0
Math.rint(-2.0) returns –2.0
Math.rint(-2.1) returns -2.0
Math.rint(2.5) returns 2.0
Math.rint(-2.5) returns -2.0
Math.round(2.6f) returns 3
Math.round(2.0) returns 2
Math.round(-2.0f) returns -2
Math.round(-2.6)
returns -3
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
124
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
Math.max(2.5, 3) returns
3.0
Math.min(2.5, 3.6)
returns 2.5
Math.abs(-2) returns 2
Math.abs(-2.1) returns
2.1
abs(a)
Returns the absolute value of the
parameter.

random()
Returns a random double value
in the range [0.0, 1.0).
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
125
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:
(int)(Math.random() * 10)
Returns a random integer
between 0 and 9.
50 + (int)(Math.random() * 50)
Returns a random integer
between 50 and 99.
In general,
a + Math.random() * b
Returns a random number between
a and a + b, excluding a + b.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
126
Stepwise Refinement (Optional)
The concept of method abstraction can be
applied to the process of developing programs.
When writing a large program, you can use the
“divide and conquer” strategy, also known as
stepwise refinement, to decompose it into
subproblems. The subproblems can be further
decomposed into smaller, more manageable
problems.
PrintCalendar
Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
127
PrintCalender Case Study
Let us use the PrintCalendar example to demonstrate
the stepwise refinement approach.
Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
128
Design Diagram
printCalendar
(main)
printMonth
readInput
printMonthTitle
getMonthName
printMonthBody
getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
129
Implementation: Top-Down
Top-down approach is to implement one method in the
structure chart at a time from the top to the bottom. Stubs
can be used for the methods waiting to be implemented. A
stub is a simple but incomplete version of a method. The
use of stubs enables you to test invoking the method from
a caller. Implement the main method first and then use a
stub for the printMonth method. For example, let
printMonth display the year and the month in the stub.
Thus, your program may begin like this:
A Skeleton for printCalendar
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
130
Implementation: Bottom-Up
Bottom-up approach is to implement one method in the
structure chart at a time from the bottom to the top. For
each method implemented, write a test program to test it.
Both top-down and bottom-up methods are fine. Both
approaches implement the methods incrementally and
help to isolate programming errors and makes debugging
easy. Sometimes, they can be used together.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
131
Optional
Package
There are three reasons for using packages:
1. To avoid naming conflicts. When you develop
reusable classes to be shared by other
programmers, naming conflicts often occur. To
prevent this, put your classes into packages so that
they can be referenced through package names.
2. To distribute software conveniently. Packages group
related classes so that they can be easily
distributed.
3. To protect classes. Packages provide protection so
that the protected members of the classes are
accessible to the classes in the same package, but
not to the external classes.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
132
Package-Naming Conventions
Packages are hierarchical, and you can have packages within
packages. For example, java.lang.Math indicates that Math is a
class in the package lang and that lang is a package in the
package java. Levels of nesting can be used to ensure the
uniqueness of package names.
Choosing a unique name is important because your package
may be used on the Internet by other programs. Java designers
recommend that you use your Internet domain name in reverse
order as a package prefix. Since Internet domain names are
unique, this prevents naming conflicts. Suppose you want to
create a package named mypackage on a host machine with the
Internet domain name prenhall.com. To follow the naming
convention, you would name the entire package
com.prenhall.mypackage. By convention, package names are all
in lowercase.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
133
Package Directories
Java expects one-to-one mapping of the package name and the
file system directory structure. For the package named
com.prenhall.mypackage, you must create a directory, as shown
in the figure. In other words, a package is actually a directory
that contains the bytecode of the classes.
com.prenhall.mypackage
The com directory does not have to be the root
directory. In order for Java to know where
your package is in the file system, you must
modify the environment variable classpath so
that it points to the directory in which your
package resides.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
134
Setting classpath Environment
The com directory does not have to be the root directory. In order for Java to know where
your package is in the file system, you must modify the environment variable classpath so
that it points to the directory in which your package resides.
Suppose the com directory is under c:\book. The following line adds c:\book into the
classpath:
classpath=.;c:\book;
The period (.) indicating the current directory is always in classpath. The directory
c:\book is in classpath so that you can use the package com.prenhall.mypackage in the
program.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
135
Putting Classes into Packages
Every class in Java belongs to a package. The class is added to the package when
it is compiled. All the classes that you have used so far in this book were placed in
the current directory (a default package) when the Java source programs were
compiled. To put a class in a specific package, you need to add the following line
as the first noncomment and nonblank statement in the program:
package packagename;
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
136
Listing 5.8 Putting Classes into Packages
Problem
This example creates a class named Format and places it in the package
com.prenhall.mypackage. The Format class contains the format(number,
numOfDecimalDigits) method that returns a new number with the specified
number of digits after the decimal point. For example, format(10.3422345, 2)
returns 10.34, and format(-0.343434, 3) returns –0.343.
Solution
1. Create Format.java as follows and save it into c:\book\com\prenhall\mypackage.
// Format.java: Format number.
package com.prenhall.mypackage;
public class Format {
public static double format(
double number, int numOfDecimalDigits) {
return Math.round(number * Math.pow(10, numOfDecimalDigits)) /
Math.pow(10, numOfDecimalDigits);
}
}
2. Compile Format.java. Make sure Format.class is in
c:\book\com\prenhall\mypackage.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
137
Using Classes from Packages
There are two ways to use classes from a package.
• One way is to use the fully qualified name of the class. For example, the fully
qualified name for JOptionPane is javax.swing.JOptionPane. For Format in the
preceding example, it is com.prenhall.mypackage.Format. This is convenient if the
class is used a few times in the program.
• The other way is to use the import statement. For example, to import all the
classes in the javax.swing package, you can use
import javax.swing.*;
An import that uses a * is called an import on demand declaration. You can also
import a specific class. For example, this statement imports
javax.swing.JOptionPane:
import javax.swing.JOptionPane;
The information for the classes in an imported package is not read in at compile time
or runtime unless the class is used in the program. The import statement simply tells
the compiler where to locate the classes.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
138
Listing 5.9 Using Packages
Problem
This example shows a program that uses the Format class in the
com.prenhall.mypackage.mypackage package.
Solution
1. Create TestFormatClass.java as follows and save it into c:\book.
The following code gives the solution to the problem.
// TestFormatClass.java: Demonstrate using the Format class
import com.prenhall.mypackage.Format;
public class TestFormatClass {
/** Main method */
public static void main(String[] args) {
System.out.println(Format.format(10.3422345, 2));
System.out.println(Format.format(-0.343434, 3));
}
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
139