Chapter 01
Chapter 01
Language
MSc. Nguyen Cao Dat
[email protected]
Chapter I
FUNDAMENTALS OF PROGRAMMING
1
Content
Introduction
Data Types and Operations
Control Statements
Loop Statements
Methods
Content
Introduction
Data Types and Operations
Control Statements
Loop Statements
Methods
2
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 smart
phone with Android OS.
Introduction
Examples of Java’s Versatility
Standalone Application: TicTacToe
Applet: TicTacToe
Servlets: SelfTest Web site
Mobile Computing: Cell phones
3
TicTacToe Standalone
TicTacToe Applet
4
SelfTest Website (using Java Servlets)
10
10
5
Introduction
In 1991, James Gosling of Sun
Microsystems designed what
would become the Java
programming language
– In 2010, Sun was acquired by
Oracle
Platform independent
– Can run on almost any machine
Used to create Internet
applets
11
11
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
12
12
6
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.
This course uses J2SE to introduce Java programming.
13
13
14
14
7
Java Virtual Machine (JVM)
Java code starts as
source code (human-
readable)
A compiler converts it
into machine readable
code (byte code)
Any JVM can then run
the code, which is in a
.class file
15
15
Introduction
The Java Platform consists of
two parts
– Java Virtual Machine (JVM)
– Java Application Programming
Interface (API)
A huge collection of handy software
packages that programmers can use
– Graphics, user interface, networking,
sound, database, math, etc.
Helps programmers not have to
reinvent the wheel
16
16
8
Introduction
Java Development Kit (JDK)
– To be able to create Java programs, you must
install the Java Development Kit (JDK)
– Download: http://www.oracle.com/java/
– Common location after installation will be:
C:\Program Files\Java\jdk_____ (a set of numbers)
The set of numbers will vary with the release
– The JDK includes programs such as:
javac.exe (Java compiler)
javadoc.exe (Javadoc generator)
java.exe (executes Java applications)
17
17
18
9
jGrasp: An Example IDE
Editor
Output
19
19
Compile
Output Execute
20
20
10
jGrasp: Compiling a Program
Result
21
21
Output
22
22
11
Source Code to Running Program
23
23
24
24
12
Hello World: Your First Java Program
Below is a traditional "Hello World" program in Java
– The name of the file is HelloWorld.java
Typing the program into your IDE would be good practice!
– Be careful of spelling
– JaVa iS CaSe SeNsItiVe
– Java uses special characters, such as curly braces {} and parentheses ()
– Java ignores whitespace
25
25
26
26
13
Calling Java API Methods
Note the Line:
27
28
28
14
Errors
Syntax Errors
– Examples
Misspelling, capitalization, punctuation
Ordering of statements, matching of braces/parentheses
– No .class file is generated by the compiler
– Correct the first error listed, then compile again
Logic Errors
– Program runs, but produces unintended results
– Check your algorithm for the logic you have included
Runtime Errors
– Causes the program to crash immediately, such as divide
by zero
– Check your algorithm to make sure you have handled all
cases
29
29
Syntax Errors
30
30
15
Logic Errors
31
Runtime Errors
32
32
16
Anatomy of a Java Program
Comments
Package
Reserved words
Modifiers
Statements
Blocks
Classes
Methods
The main method
33
33
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 */.
34
34
17
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.
35
35
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.
36
36
18
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.”
37
37
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.
38
38
19
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.
39
39
main Method
The main method provides the control of program flow. The
Java interpreter executes the application by invoking the main
method.
40
40
20
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.
41
41
Variables
// Compute the first area
radius = 1.0;
area = radius * radius * 3.14159;
System.out.println("The area is “ +
area + " for radius "+radius);
42
42
21
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;
43
43
Assignment Statements
x = 1; // Assign 1 to x;
44
44
22
Declaring and Initializing
in One Step
int x = 1;
double d = 1.4;
45
45
Constants
final datatype CONSTANTNAME = VALUE;
46
46
23
Programming Style and
Documentation
Appropriate Comments
Naming Conventions
Proper Indentation and Spacing Lines
Block Styles
47
47
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.
48
48
24
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.
49
49
Constants:
– Capitalize all letters in constants, and use
underscores to connect words. For
example, the constant PI and
MAX_VALUE
50
50
25
Proper Indentation and Spacing
Indentation
– Indent two spaces.
Spacing
– Use blank line to separate segments of the code.
51
51
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");
}
}
52
52
26
Content
Introduction
Data Types and Operations
Control Statements
Loop Statements
Methods
53
53
54
27
Variable Data Types (Cont'd)
Integer Types (Whole numbers, no fractions)
– byte: a very small number (-127 to +128)
– short: a small number (-32,768 to +32,767)
– int: a large number (-2,147,483,648 to +2,147,483,647)
– long: a huge number
Floating Point Types
– float: a huge number with decimal places
– double: a more precise, floating type, used for calculations
Other Types
– boolean: true or false
– char: one symbol in single quotes, such as: 'a'
55
56
28
IT 106: Introduction to IT Problem Solving Using Computer Programming
Use the
double
type for
floating-
point numbers.
57
Java Comments
There are three forms of comments
– // a single line comment (or rest of line to the right)
– /*
multi-line comment – all comments within /* */
*/
– /**
multi-line Javadoc comments – used to automatically
generate documentation
*/
The compiler ignores commented code
Use comments at the beginning of each program and
within the program to clarify details of the code
58
29
IT 106: Introduction to IT Problem Solving Using Computer Programming
Internal
Documentation
59
60
30
IT 106: Introduction to IT Problem Solving Using Computer Programming
Common Variable Errors
• Overflow
(Cont'd)
– The storage for the variable cannot correctly hold the value
– Example: Remember the int data type can store values in
the range of -2,147,483,648 to +2,147,483,647
• int oneThousand = 1000; // OK
• int oneMillion = 1000 * oneThousand; // OK
• int oneBillion = 1000 * oneMillion; // OK
• System.out.println(3 * oneBillion); // ??
– Output will print: -1294976296
– Why?
• The result (3 billion) overflowed the capacity of an int, truncated
the value, and provided something useless
– To fix this, use a long (if integer) or a double (if floating
point)
61
Variable Assignment
You can use the assignment operator (=) to
place a new value into a variable
int cansPerPack = 6; //declare and initialize
cansPerPack = 8; //assignment
Warning! The = sign is NOT used for
comparison
– It copies the value on the right side into the
variable on the left side
The variable MUST be on the left side for assignment
– Comparisons will be covered a bit later
62
31
IT 106: Introduction to IT Problem Solving Using Computer Programming
Incrementing a Variable
63
64
32
IT 106: Introduction to IT Problem Solving Using Computer Programming
Modifying a Variable
Assumes counter has already been declared using int counter;
65
Syntax: Assignment
Review of the assignment statement
– The value on the right is copied to the variable on the left
66
33
IT 106: Introduction to IT Problem Solving Using Computer Programming
Constants
It is a good practice to declare values that will
not change during program execution as
constants
Use the reserved word final before the type
in the declaration
– Example: final double BOTTLE_VOLUME = 1.75;
– They can then be used like any other variable
double volume = bottles * BOTTLE_VOLUME;
Constants are usually declared near the
beginning of the program or class
You cannot assign a new value
to a constant at run-time.
67
INPUT/OUTPUT
68
34
IT 106: Introduction to IT Problem Solving Using Computer Programming
Using a Graphical User
Interface
Previously for output, we have been using
System.out.println to print to the IDE or
a console window
Users are now used to seeing graphical
interfaces instead of just a text-based
command prompt
For now, don't worry about the details
– Pay attention to the format of the code
69
70
35
IT 106: Introduction to IT Problem Solving Using Computer Programming
New
71
Reading Input
You frequently will need to ask the user
for input (i.e. prompt them) and then
save what was entered
– We will be reading input from the keyboard
72
36
IT 106: Introduction to IT Problem Solving Using Computer Programming
73
74
37
IT 106: Introduction to IT Problem Solving Using Computer Programming
ARITHMETIC OPERATIONS
75
Arithmetic Operations
Java supports all of the same
basic calculator operations
– Addition, subtraction,
multiplication, division
However, Java expressions may No Yes
only be written on one line
Precedence is similar to
Algebra
– Remember PEMDAS
Parentheses, exponents,
multiplication/division,
addition/subtraction
76
38
IT 106: Introduction to IT Problem Solving Using Computer Programming
Integer Division and
Remainders
If both operands are integer types, you need to be
careful not to lose precision
int first = 7, second = 4, answer;
answer = first / second; // answer is 1!
– The result is an integer. The fraction was lost.
To find the fractional part, use the modulo
operator (%)
int first = 7, second = 4, answer, remainder;
answer = first / second;
remainder = first % second; // set to 3
You could also use floating-point data types,
instead
77
Java
78
39
IT 106: Introduction to IT Problem Solving Using Computer Programming
79
CONVERTING AND
FORMATTING DATA
80
40
IT 106: Introduction to IT Problem Solving Using Computer Programming
Converting Between Data
Types
It is safe to convert a value from an integer data type
to a floating point data type
– No decimal points (precision) is lost
Going the other way can be dangerous
– All fractional information is lost
– To "force" a conversion, variables can be cast from one type
to another
– Example
double balance = total + tax;
int dollars = (int) balance;
The fractional part is discarded (not rounded)
If you do not use the cast, the compiler will generate a syntax
error
81
Formatted Output
Outputting floating point values can look
strange, such as at gas stations
– Example: Price per liter = 1.21997
To control the output appearance we can create
and format a String containing a number
through a format specifier
Once the string has been formatted, we can
output it
The book covers more detailed ways you can
format your output
Note: Not all format specifiers are supported using JOptionPane
82
41
IT 106: Introduction to IT Problem Solving Using Computer Programming
83
Common Errors
Unintended Integer Division
Why an error?
– Since all of the data types are integers, the compiler performs
integer division
– Then the resulting integer is assigned to a double
– When decimal points are important, use a floating-point type
84
42
IT 106: Introduction to IT Problem Solving Using Computer Programming
85
STRINGS
86
43
IT 106: Introduction to IT Problem Solving Using Computer Programming
Strings
The String data type stores a set of characters
Once you have a string variable you can use methods
on it, such as finding the length
87
88
44
IT 106: Introduction to IT Problem Solving Using Computer Programming
89
90
90
45
Numeric Operators
+ Addition 34 + 1 35
% Remainder 20 % 3 2
91
91
Integer Division
+, -, *, /, and %
5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5
92
92
46
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:
93
93
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.
94
94
47
Arithmetic Expressions
3 + 4 x 10( y − 5)(a + b + c) 4 9+ x
− + 9( + )
5 x x y
is translated to
95
95
96
96
48
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
97
97
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.
98
98
49
Increment and
Decrement Operators, cont.
99
99
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
100
100
50
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--;
101
101
byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;
102
102
51
Conversion Rules
When performing a binary operation involving two
operands of different types, Java automatically
converts the operand based on the following rules:
103
103
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
104
104
52
Character Data Type
Four hexadecimal digits.
char letter = 'A'; (ASCII)
char numChar = '4'; (ASCII)
char letter = '\u0041'; (Unicode)
char numChar = '\u0034'; (Unicode)
105
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
106
106
53
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
107
107
108
108
54
ASCII Character Set, cont.
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
109
109
110
110
55
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. 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.
111
111
String Concatenation
// Three strings are concatenated
String message = "Welcome " + "to " + "Java";
112
112
56
Obtaining Input
1. Using JOptionPane input dialogs
2. Using Scanner class
113
113
114
114
57
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:
115
115
116
58
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:
117
117
118
118
59
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.
119
119
Comparison Operators
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
120
120
60
Boolean Operators
Operator Name
! not
&& and
|| or
^ exclusive or
121
121
Examples
System.out.println("Is " + num + " divisible by 2 and 3? " +
((num % 2 == 0) && (num % 3 == 0)));
122
122
61
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)
123
123
124
62
The & and | Operators
If x is 1, what is x after this
expression?
(x > 1) & (x++ < 10)
125
125
Content
Introduction
Data Types and Operations
Control Statements
Loop Statements
Methods
126
126
63
Control Statements
if Statements
switch Statements
Conditional Operators
127
127
TIP
if (number % 2 == 0) Equivalent
even = true; boolean even
else = number % 2 == 0;
even = false;
(a) (b)
128
128
64
CAUTION
if (even == true) Equivalent if (even)
System.out.println( System.out.println(
"It is even."); "It is even.");
(a) (b)
129
129
130
130
65
Conditional Operator, cont.
I = (booleanExp) ? exp1 :
exp2
131
131
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)
132
132
66
Content
Introduction
Data Types and Operations
Control Statements
Loop Statements
Methods
133
133
Loop
false false
Continuation (count < 100)?
Condition?
true true
Statement(s) System.out.println("Welcome to Java!");
(loop body) count++;
(A) (B)
134
134
67
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.
135
135
136
136
68
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.
if (data == 0)
System.out.println("data is zero");
else
System.out.println("data is not zero");
137
137
do-while Loop
Statement(s)
(loop body)
true Loop
Continuation
do { Condition?
// Loop body; false
Statement(s);
} while (loop-continuation-condition);
138
138
69
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)
139
139
Note
The initial-action in a for loop can be a list of zero or more
comma-separated expressions. The action-after-each-
iteration in a for loop can be a list of zero or more comma-
separated 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++));
140
70
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:
141
141
142
142
71
Nested Loops
Problem: Write a program that uses nested for loops to
print a multiplication table.
143
143
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.
144
144
72
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.
145
145
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.
146
146
73
Content
Introduction
Data Types and Operations
Control Statements
Loop Statements
Methods
147
147
148
148
74
Introducing Methods
A method is a collection of statements that are
grouped together to perform an operation.
method
public static int max(int num1, int num2) { int z = max(x, y);
header
int result;
method actual parameters
body parameter list (arguments)
if (num1 > num2)
result = num1;
else
result = num2;
return value
return result;
}
149
149
150
150
75
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.
151
151
Calling Methods
Testing the max method
This program demonstrates calling a method max
to return the largest of the int values
152
152
76
Calling Methods, cont.
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
153
153
154
154
77
Call Stacks
The main method The max method is The max method is The main method
is invoked. invoked. finished and the return is finished.
value is sent to k.
155
155
156
156
78
Overloading Methods
Listing 5.3 Overloading the max Method
157
157
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.
158
158
79
Ambiguous Invocation
public class AmbiguousOverloading {
public static void main(String[] args) {
System.out.println(max(1, 2));
}
159
Method Abstraction
You can think of the method body as a black
box that contains the detailed implementation
for the method.
Optional arguments Optional return
for Input value
Method Signature
Black Box
Method body
160
160
80
Benefits of Methods
• Write a method once and reuse it anywhere.
• Information hiding. Hide the implementation
from the user.
• Reduce complexity.
161
161
162
162
81
Trigonometric Methods
sin(double a) Examples:
cos(double a)
Math.sin(0) returns 0.0
tan(double a) Math.sin(Math.PI / 6)
returns 0.5
acos(double a) Math.sin(Math.PI / 2)
returns 1.0
asin(double a)
Math.cos(0) returns 1.0
atan(double a) Math.cos(Math.PI / 6)
returns 0.866
Math.cos(Math.PI / 2)
Radians returns 0
toRadians(90)
163
163
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.
164
164
82
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).
165
165
166
83
min, max, and abs
max(a, b)and min(a, Examples:
b)
Returns the maximum or Math.max(2, 3) returns 3
minimum of two parameters.
Math.max(2.5, 3) returns
abs(a) 3.0
Returns the absolute value of the Math.min(2.5, 3.6)
parameter. returns 2.5
random() Math.abs(-2) returns 2
Returns a random double value Math.abs(-2.1) returns
in the range [0.0, 1.0). 2.1
167
167
Examples:
In general,
168
168
84