You are on page 1of 137

• If program need to compare two values.

• Use operators (also known as relational operators)

• The result of the comparison is a Boolean value: true or


false.

boolean b = (1 > 2);

92
Java Mathematics Name Example Result
Operator Symbol (radius is 5)

< < less than radius < 0 false


<= ≤ less than or equal to radius <= 0 false
> > greater than radius > 0 true
>= ≥ greater than or equal to radius >= 0 true
== = equal to radius == 0 false
!= ≠ not equal to radius != 0 true

93
Operator Name
! not
&& and
|| or
^ exclusive or

94
• Program randomly add two single-digit integers
number1 and number2.
• Prompt “What is 7 + 9?” to the student.
• After the student types the answer, the
program displays a message to indicate whether
the answer is true or false.
Output:
What is 7 + 9? 16
7 + 9 = 16 is true

95
import java.util.Scanner;
public class AdditionQuiz {
public static void main(String[] args) {
int number1 = (int)(System.currentTimeMillis() % 10); //long convert to int
int number2 = (int)(System.currentTimeMillis() / 7 % 10); //long convert to int

// Create a Scanner
Scanner input = new Scanner(System.in);
System.out.print(
"What is " + number1 + " + " + number2 + "? ");
int answer = input.nextInt();
System.out.println(
Output:
number1 + " + " + number2 + " = " + answer + " is " + What is 8 + 8? 16
(number1 + number2 == answer)); 8 + 8 = 16 is true
}
}
if i > 0 { if (i > 0) {
System.out.println("i is positive"); System.out.println("i is positive");
} }
(a) Wrong (b) Correct

if (i > 0) { if (i > 0)
System.out.println("i is positive"); Equivalent System.out.println("i is positive");
}

(a) (b)

97
Write a program that prompts the user to enter an integer. If the number is a multiple
of 5, print HiFive. If the number is divisible by 2, print HiEven.
Output
import java.util.Scanner;
Enter an integer:
public class SimpleIfDemo { 5
public static void main(String[] args) { HiFive
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer: "); Output
int number = input.nextInt(); Enter an integer:
2
if (number % 5 == 0) HiEven
System.out.println("HiFive");
Output
if (number % 2 == 0) Enter an integer:
System.out.println("HiEven"); 10
}
HiFive
}
HiEven

98
The program can guess your birth date (Day).
= 19

1 3 5 7 2 3 6 7 4 5 6 7 8 9 10 11 16 17 18 19
9 11 13 15 10 11 14 15 12 13 14 15 12 13 14 15 20 21 22 23
17 19 21 23 18 19 22 23 20 21 22 23 24 25 26 27 24 25 26 27
25 27 29 31 26 27 30 31 28 29 30 31 28 29 30 31 28 29 30 31
Set1 Set2 Set3 Set4 Set5

Programming : GuessBirthday
https://liveexample.pearsoncmg.com/html/GuessBirthday.html

99
import java.util.Scanner;
public class GuessBirthday {
public static void main(String[] args) {
String set1 =
" 1 3 5 7\n" +
" 9 11 13 15\n" +
"17 19 21 23\n" +
"25 27 29 31";
String set2 =
" 2 3 6 7\n" +
"10 11 14 15\n" +
"18 19 22 23\n" +
"26 27 30 31";
String set3 =
" 4 5 6 7\n" +
"12 13 14 15\n" +
"20 21 22 23\n" +
"28 29 30 31";
String set4 =
" 8 9 10 11\n" +
"12 13 14 15\n" +
"24 25 26 27\n" +
"28 29 30 31";
String set5 =
"16 17 18 19\n" +
"20 21 22 23\n" +
"24 25 26 27\n" +
"28 29 30 31";

int day = 0;
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to answer questions
System.out.print("Is your birthday in Set1?\n");
System.out.print(set1);
System.out.print("\nEnter 0 for No and 1 for Yes: ");
int answer = input.nextInt();
if (answer == 1)
day += 1;

// Prompt the user to answer questions


System.out.print("\nIs your birthday in Set2?\n");
System.out.print(set2);
System.out.print("\nEnter 0 for No and 1 for Yes: ");
answer = input.nextInt();

if (answer == 1)
day += 2;

// Prompt the user to answer questions


System.out.print("Is your birthday in Set3?\n");
System.out.print(set3);
System.out.print("\nEnter 0 for No and 1 for Yes: ");
answer = input.nextInt();
if (answer == 1)
day += 4;
// Prompt the user to answer questions
System.out.print("\nIs your birthday in Set4?\n");
System.out.print(set4);
System.out.print("\nEnter 0 for No and 1 for Yes: ");
answer = input.nextInt();
if (answer == 1)
day += 8;
// Prompt the user to answer questions
System.out.print("\nIs your birthday in Set5?\n");
System.out.print(set5);
System.out.print("\nEnter 0 for No and 1 for Yes: ");
answer = input.nextInt();
if (answer == 1)
day += 16;
System.out.println("\nYour birthday is " + day + "!");
}
}
Is your birthday in Set1?
1 3 5 7
9 11 13 15
17 19 21 23
25 27 29 31
Enter 0 for No and 1 for Yes: 1

Is your birthday in Set2?


2 3 6 7
10 11 14 15
18 19 22 23
26 27 30 31
Enter 0 for No and 1 for Yes: 0
Is your birthday in Set3?
4 5 6 7
12 13 14 15
20 21 22 23
28 29 30 31
Enter 0 for No and 1 for Yes: 1

Is your birthday in Set4?


8 9 10 11
12 13 14 15
24 25 26 27
28 29 30 31
Enter 0 for No and 1 for Yes: 0
Is your birthday in Set5?
16 17 18 19
20 21 22 23
24 25 26 27
28 29 30 31
Enter 0 for No and 1 for Yes: 0

Your birthday is 5!
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}

true false
Boolean
Expression

Statement(s) for the true case Statement(s) for the false case

107
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");
}

108
if (score >= 90.0) if (score >= 90.0)
grade = 'A'; grade = 'A';
else else if (score >= 80.0)
if (score >= 80.0) Equivale nt grade = 'B';
grade = 'B'; else if (score >= 70.0)
else grade = 'C';
if (score >= 70.0) else if (score >= 60.0)
grade = 'C'; grade = 'D';
else else
if (score >= 60.0) grade = 'F';
grade = 'D';
else
grade = 'F';

109
false
score >= 90
false
true score >= 80
false
grade = 'A' true score >= 70
false
grade = 'B' rue score >= 60

grade = 'C' true

grade = 'D'

grade = 'F'

110
if (radius >= 0); Wrong

{
area = radius*radius*PI;
System.out.println(
"The area for the circle of radius " +
radius + " is " + area);
}

111
• The program randomly subtract two single-
digit integers number1 and number2 with
number1 >= number2
Output:
Output:
What is 7 - 2? 3
What is 6 - 1? 5
Your answer is wrong.
You are correct!
7 - 2 should be 5

Programming : SubtractionQuiz
https://liveexample.pearsoncmg.com/html/SubtractionQuiz.html

112
Show Cod

import java.util.Scanner;

public class SubtractionQuiz {


public static void main(String[] args) {
// 1. Generate two random single-digit integers
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);

// 2. If number1 < number2, swap number1 with number2


if (number1 < number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
// 3. Prompt the student to answer “what is number1 – number2?”
System.out.print
("What is " + number1 + " - " + number2 + "? ");
Scanner input = new Scanner(System.in);
int answer = input.nextInt();

// 4. Grade the answer and display the result


if (number1 - number2 == answer)
System.out.println("You are correct!");
else
System.out.println("Your answer is wrong.\n" + number1 + " - "
+ number2 + " should be " + (number1 - number2));
}
}
switch (status) {
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file jointly;
break;
case 2: compute taxes for married file separately;
break;
case 3: compute taxes for head of household;
break;
default: System.out.println("Errors: invalid status");
System.exit(1);
}
115
s tat us is 0
Compute tax for single filers break

status i s 1
Compute tax for married j ointly or quali fyin g wido w(er) break

status i s 2
Compute tax for married fili ng separately break

status i s 3
Compute tax for head of household break

default
Default acti ons

117
The switch-expression
must yield a value of char, switch (switch-expression) {
byte, short, or int type and case value1: statement(s)1;
must always be enclosed 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.
The resulting statements in the case valueN: statement(s)N;
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.

118
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.
119
Write a program that prompts the user to enter a year and
displays the animal for the year.
0: m onkey
pig rat
1: rooster
dog ox 2: dog
3: pi g
rooster tiger 4: rat
year % 12 = 5: ox
monkey rabbit 6: t iger
7: rabbit
sheep
8: dragon
dragon
9: s nake
horse snake 10: horse
11: sh eep
Output:
Enter a year: 11
Programing: ChineseZodiac sheep
https://liveexample.pearsoncmg.com/html/ChineseZodiac.html

120
import java.util.Scanner;
public class ChineseZodiac {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = input.nextInt();

switch (year % 12) {


case 0: System.out.println("monkey"); break;
case 1: System.out.println("rooster"); break;
case 2: System.out.println("dog"); break;
case 3: System.out.println("pig"); break;
case 4: System.out.println("rat"); break;
case 5: System.out.println("ox"); break;
case 6: System.out.println("tiger"); break;
case 7: System.out.println("rabbit"); break;
case 8: System.out.println("dragon"); break;
case 9: System.out.println("snake"); break;
case 10: System.out.println("horse"); break;
case 11: System.out.println("sheep"); break;
}
}
}
Problem:

System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
100
times



System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
124
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java");
count++;
}

125
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)

126
Initialize count
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

127
(count < 2) is true
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

128
Print Welcome to Java
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

129
Increase count by 1
int count = 0; count is 1 now
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

130
(count < 2) is still true since count
int count = 0; is 1
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

131
Print Welcome to Java
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

132
Increase count by 1
int count = 0; count is 2 now
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

133
(count < 2) is false since count is 2
int count = 0; now
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

134
The loop exits. Execute the next
int count = 0; statement after the loop.
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

135
Prompts the user to enter an answer for a question on
addition of two single digits and let the user enter a new
answer until it is correct.
Output:
What is 2 + 7? 6
Wrong answer. Try again. What is 2 + 7?

Output:
What is 2 + 7? 6
Wrong answer. Try again. What is 2 + 7? 6
Wrong answer. Try again. What is 2 + 7?

Programing: RepeatAdditionQuiz Output:


What is 2 + 7? 6
https://liveexample.pearsoncmg.
Wrong answer. Try again. What is 2 + 7? 6
com/html/RepeatAdditionQuiz. Wrong answer. Try again. What is 2 + 7? 9
html You got it!

136
Write a program that randomly generates an integer between 0 and 100.

• User need to enter a number continuously until the number matches the
randomly generated number.

• The program tells the user whether the input is too low or too high, so the
user can choose the next input intelligently.
Output:
Guess a magic number between 0 and 100

Enter your guess: 5


Your guess is too low

Enter your guess: 40


Programing: GuessNumber Your guess is too high

https://liveexample.pearsoncmg. Enter your guess: 39


com/html/GuessNumber. Yes, the number is 39

html

137
Program will generates five questions and reports the number of the correct answers
after a student answers all five questions.
Output:
What is 9 - 8? 1
You are correct!
What is 5 - 4? 1
You are correct!
What is 5 - 5? 2
Your answer is wrong.
5 - 5 should be 0
What is 6 - 1? 3
Your answer is wrong.
6 - 1 should be 5
What is 2 - 0? 5
Your answer is wrong.
2 - 0 should be 2
Correct count is 2
Test time is 19 seconds

Programing: SubtractionQuizLoop 9-8=1 correct


https://liveexample.pearsoncmg.com/html/ 5-4=1 correct
5-5=2 wrong
SubtractionQuizLoop.html 6-1=3 wrong
2-0=5 wrong

138
Statement(s)
(loop body)

true Loop
Continuation
do {
Condition?
// Loop body;
Statement(s); false
} while (loop-continuation-condition);

139
for (initial-action; loop- int i;
continuation-condition; action- for (i = 0; i < 100; i++) {
after-each-iteration) { System.out.println(
// loop body;
Statement(s);
"Welcome to Java!");
} }

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)
140
Declare i
int i;
for (i = 0; i < 2; i++) {
System.out.println(
"Welcome to Java!");
}

141
Execute initializer
int i; i is now 0
for (i = 0; i < 2; i++) {
System.out.println(
"Welcome to Java!");
}

142
(i < 2) is true
int i; since i is 0
for (i = 0; i < 2; i++) {
System.out.println( "Welcome to Java!");
}

143
Print Welcome to Java
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

144
Execute adjustment statement
int i; i now is 1
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

145
(i < 2) is still true
int i; since i is 1
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

146
Print Welcome to Java
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

147
Execute adjustment statement
int i; i now is 2
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

148
(i < 2) is false
int i; since i is 2
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

149
Exit the loop. Execute the next
int i; statement after the loop
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

150
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 ( ; ; ) { Equivalent while (true) {


// Do something // Do something
} }
(a) (b)

151
Adding a semicolon at the end of the for clause before
the loop body is a common mistake, as shown below:
Logic Error

for (int i=0; i<10; i++);


{
System.out.println("i is " + i);
}

152
Similarly, the following loop is also wrong:
int i=0; Logic Error
while (i < 10);
{
System.out.println("i is " + i);
i++;
}
In the case of the do loop, the following semicolon is needed to end
the loop.
int i=0;
do {
System.out.println("i is " + i);
i++;
} while (i<10); Correct

153
Problem: Write a program that uses nested for
loops to print a multiplication table.
Output:
Multiplication Table
1 2 3 4 5 6 7 8 9
-----------------------------------------
1| 1 2 3 4 5 6 7 8 9
2 | 2 4 6 8 10 12 14 16 18
3 | 3 6 9 12 15 18 21 24 27
4 | 4 8 12 16 20 24 28 32 36
5 | 5 10 15 20 25 30 35 40 45
6 | 6 12 18 24 30 36 42 48 54
Programing: MultiplicationTable 7 | 7 14 21 28 35 42 49 56 63
https://liveexample.pearsoncmg.com/html/ 8 | 8 16 24 32 40 48 56 64 72
MultiplicationTable.html 9 | 9 18 27 36 45 54 63 72 81

154
public class TestBreak {
public static void main(String[] args) {
int sum = 0;
int number = 0;

while (number < 20) {


number++;
sum += number;
if (sum >= 100)
break;
}

System.out.println("The number is " + number);


System.out.println("The sum is " + sum);
}
}

155
public class TestContinue {
public static void main(String[] args) {
int sum = 0;
int number = 0;

while (number < 20) {


number++;
if (number == 10 || number == 11)
continue;
sum += number;
}

System.out.println("The sum is " + sum);


}
}

156
Find the sum of integers
• From 1 to 10
• From 20 to 30
• From 35 to 45

158
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
System.out.println("Sum from 1 to 10 is " + sum);

sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
System.out.println("Sum from 20 to 30 is " + sum);

sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
System.out.println("Sum from 35 to 45 is " + sum);

159
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
System.out.println("Sum from 1 to 10 is " + sum);

sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
System.out.println("Sum from 20 to 30 is " + sum);

sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
System.out.println("Sum from 35 to 45 is " + sum);

160
public static int sum(int i1, int i2) {
int sum = 0;
for (int i = i1; i <= i2; i++)
sum += i;
return sum;
}
public static void main(String[] args) {
System.out.println("Sum from 1 to 10 is " + sum(1, 10));
System.out.println("Sum from 20 to 30 is " + sum(20, 30));
System.out.println("Sum from 35 to 45 is " + sum(35, 45));
}
161
A method is a collection of statements that are
grouped together to perform an operation.
Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

162
Program demonstrates calling a method max to
return the largest of the int values

Output:

The maximum between 5 and 2 is 5

163
pass the value of i
pass the value of j

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;
}

164
i is now 5

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;
}

165
j is now 2

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;
}

166
invoke max(i, j)

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;
}

167
invoke max(i, j)
Pass the value of i to num1
Pass the value of j to num2

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;
}

168
declare variable result

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;
}

169
(num1 > num2) is true since num1
is 5 and num2 is 2

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;
}

170
result is now 5

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;
}

171
return result, which is 5

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;
}

172
return max(i, j) and assign the
return value to k

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;
}

173
Execute the print statement

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;
}

174
This type of method does not return a value. The method
performs some actions.

Output:
The grade is C
The grade is F

175
• Write a method once and reuse it anywhere.
• Information hiding. Hide the implementation
from the user.
• Reduce complexity.

176
• Class constants:
• PI
• E
• Class methods:
• Trigonometric Methods
• Exponent Methods
• Rounding Methods
• min, max, abs, and random Methods

177
• 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)
178
• exp(double a) Examples:
Returns e raised to the power of a.
• log(double a) Math.exp(1) returns 2.71
Returns the natural logarithm of a. Math.log(2.71) returns 1.0
Math.pow(2, 3) returns 8.0
• log10(double a)
Math.pow(3, 2) returns 9.0
Returns the 10-based logarithm of
a. Math.pow(3.5, 2.5) returns
22.91765
• pow(double a, double b) Math.sqrt(4) returns 2.0
Returns a raised to the power of b. Math.sqrt(10.5) returns 3.24
• sqrt(double a)
Returns the square root of a.

179
• 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).

180
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

181
• 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
Returns the absolute value of the
parameter.
3.0
Math.min(2.5, 3.6)
• random() returns 2.5
Returns a random double value
in the range [0.0, 1.0). Math.abs(-2) returns 2
Math.abs(-2.1) returns
2.1

182
Generates a random double value greater than or equal to 0.0 and
less than 1.0 (0 <= Math.random() < 1.0).

Examples:

Returns a random integer


(int)(Math.random() * 10)
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.

183
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

185
• datatype[] arrayRefVar;
Example:
double[] myList;

• datatype arrayRefVar[];
Example:
double myList[];

186
arrayRefVar = new datatype[arraySize];

Example:
myList = new double[10];

myList[0] references the first element in the array.


myList[9] references the last element in the array.

187
• datatype[] arrayRefVar = new
datatype[arraySize];
double[] myList = new double[10];

• datatype arrayRefVar[] = new


datatype[arraySize];
double myList[] = new double[10];

188
• After an array is created, an indexed variable
can be used in the same way as a regular
variable.
• For example, the following code adds the value
in myList[0] and myList[1] to myList[2].

myList[2] = myList[0] + myList[1];

189
• Declaring, creating, initializing in one step:
double[] myList = {1.9, 2.9, 3.4, 3.5};

This shorthand syntax must be in one


statement.

190
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;

191
Declare array variable values, create an
array, and assign its reference to values

public class Test {


public static void main(String[] args) { After the array is created

int[] values = new int[5];


for (int i = 1; i < 5; i++) { 0 0

1 0
values[i] = i + values[i-1]; 2 0
} 3 0
values[0] = values[1] + values[4]; 4 0

}
}

192
i becomes 1

public class Test {


public static void main(String[] args) {
After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0
values[i] = i + values[i-1]; 1 0

} 2 0

values[0] = values[1] + values[4]; 3 0

} 4 0

193
i (=1) is less than 5

public class Test {


public static void main(String[] args) {
int[] values = new int[5]; After the array is created

for (int i = 1; i < 5; i++) {


0 0
values[i] = i + values[i-1]; 1 0
} 2 0

values[0] = values[1] + values[4]; 3 0

} 4 0

194
After this line is executed, value[1] is 1

public class Test {


public static void main(String[] args) { After the first iteration

int[] values = new int[5];


0
for (int i = 1; i < 5; i++) { 0

1 1
values[i] = i + values[i-1]; 2 0
} 3 0

values[0] = values[1] + values[4]; 4 0

}
}

195
Trace Program with Arrays

After i++, i becomes 2

public class Test {


public static void main(String[] args) {
int[] values = new int[5]; After the first iteration

for (int i = 1; i < 5; i++) { 0 0

values[i] = i + values[i-1]; 1 1

2 0
} 3 0

values[0] = values[1] + values[4]; 4 0

}
}

196
Trace Program with
Arrays
i (= 2) is less than 5
public class Test {
public static void main(String[]
args) {
int[] values = new int[5]; After the first iteration

for (int i = 1; i < 5; i++) { 0 0


values[i] = i + values[i-1]; 1 1

} 2 0

0
values[0] = values[1] +
3

values[4]; 4 0

}
}

197
After this line is executed,
values[2] is 3 (2 + 1)

public class Test {


public static void main(String[] args) { After the second iteration

int[] values = new int[5];


0
for (int i = 1; i < 5; i++) { 0

1 1
values[i] = i + values[i-1]; 2 3
} 3 0

values[0] = values[1] + values[4]; 4 0

}
}

198
After this, i becomes 3.

public class Test {


public static void main(String[] args) { After the second iteration

int[] values = new int[5];


0
for (int i = 1; i < 5; i++) { 0

1 1
values[i] = i + values[i-1]; 2 3
} 3 0

values[0] = values[1] + values[4]; 4 0

}
}

199
i (=3) is still less than 5.

public class Test {


public static void main(String[] args) { After the second iteration

int[] values = new int[5];


0
for (int i = 1; i < 5; i++) { 0

1 1
values[i] = i + values[i-1]; 2 3
} 3 0

values[0] = values[1] + values[4]; 4 0

}
}

200
After this line, values[3] becomes 6 (3 + 3)

public class Test {


public static void main(String[] args) { After the third iteration

int[] values = new int[5];


0
for (int i = 1; i < 5; i++) { 0

1 1
values[i] = i + values[i-1]; 2 3
} 3 6

values[0] = values[1] + values[4]; 4 0

}
}

201
After this, i becomes 4

public class Test {


public static void main(String[] args) { After the third iteration

int[] values = new int[5];


0
for (int i = 1; i < 5; i++) { 0

1 1
values[i] = i + values[i-1]; 2 3
} 3 6

values[0] = values[1] + values[4]; 4 0

}
}

202
i (=4) is still less than 5

public class Test {


public static void main(String[] args) { After the third iteration
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0

1 1
values[i] = i + values[i-1];
2 3
} 3 6
values[0] = values[1] + values[4]; 4 0
}
}

203
After this, values[4] becomes 10 (4 + 6)

public class Test {


public static void main(String[] args) { After the fourth iteration

int[] values = new int[5];


0
for (int i = 1; i < 5; i++) { 0

1 1
values[i] = i + values[i-1]; 2 3
} 3 6

values[0] = values[1] + values[4]; 4 10

}
}

204
Trace Program with
Arrays
After i++, i becomes 5

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
After the fourth iteration
values[i] = i + values[i-1];
} 0 0
1
values[0] = values[1] + values[4]; 1

2 3
}
3 6
} 4 10

205
Trace Program with
Arrays
i ( =5) < 5 is false. Exit the loop

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) { After the fourth iteration
values[i] = i + values[i-1];
} 0 0

1 1
values[0] = values[1] + values[4]; 2 3

} 3 6

} 4 10

206
After this line, values[0] is 11 (1 + 10)

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 11
values[i] = i + values[i-1]; 1 1
} 2 3
values[0] = values[1] + values[4]; 3 6
} 4 10
}

207
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();

208
for (int i = 0; i < myList.length; i++) {
myList[i] = Math.random() * 100;
}

209
for (int i = 0; i < myList.length; i++) {
System.out.print(myList[i] + " ");
}

210
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}

211
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max)
max = myList[i];
}

212
When you develop programs to create graphical user
interfaces, you will use Java classes such as JFrame, JButton,
JRadioButton, JComboBox, and JList to create frames,
buttons, radio buttons, combo boxes, lists, and so on. Here
is an example that creates two windows using the JFrame
class.

214
Declare, create,
and assign in one
statement
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150); : JFrame
frame1.setVisible(true); JFrame frame2 = title:
new JFrame(); frame2.setTitle("Window 2"); width:
frame2.setSize(200, 150); height:
frame2.setVisible(true); visible:

215
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1"); Set title property
frame1.setSize(200, 150); : JFrame
frame1.setVisible(true); JFrame frame2 = title: "Window 1"
new JFrame(); frame2.setTitle("Window 2"); width:
frame2.setSize(200, 150); height:
frame2.setVisible(true); visible:

216
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150); : JFrame Set size property
frame1.setVisible(true); title: "Window 1"
JFrame frame2 = new JFrame(); width: 200
frame2.setTitle("Window 2"); height: 150
frame2.setSize(200, 150); visible:
frame2.setVisible(true);

217
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150); : JFrame
frame1.setVisible(true); title: "Window 1"
JFrame frame2 = new JFrame(); width: 200 Set visible
frame2.setTitle("Window 2"); height: 150 property
frame2.setSize(200, 150); visible: true
frame2.setVisible(true);

218
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150); : JFrame
frame1.setVisible(true); title: "Window 1"
JFrame frame2 = new JFrame(); width: 200
frame2.setTitle("Window 2"); height: 150
frame2.setSize(200, 150); visible: true
frame2.setVisible(true);
Declare, create,
frame2 reference and assign in one
statement
: JFrame
title:
width:
height:
visible:

219
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150); : JFrame
frame1.setVisible(true); title: "Window 1"
JFrame frame2 = new JFrame(); width: 200
frame2.setTitle("Window 2"); height: 150
frame2.setSize(200, 150); visible: true
frame2.setVisible(true);

frame2 reference
Set title property
: JFrame
title: "Window 2"
width:
height:
visible:

220
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150); : JFrame
frame1.setVisible(true); title: "Window 1"
JFrame frame2 = new JFrame(); width: 200
frame2.setTitle("Window 2"); height: 150
frame2.setSize(200, 150); visible: true
frame2.setVisible(true);

frame2 reference

: JFrame
title: "Window 2" Set size property
width: 200
height: 150
visible:

221
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150); : JFrame
frame1.setVisible(true); title: "Window 1"
JFrame frame2 = new JFrame(); width: 200
frame2.setTitle("Window 2"); height: 150
frame2.setSize(200, 150); visible: true
frame2.setVisible(true);

frame2 reference

: JFrame
title: "Window 2"
Set visible
width: 200
property
height: 150
visible: true

222
You can add graphical user interface components, such as
buttons, labels, text fields, combo boxes, lists, and menus,
to the window. The components are defined using classes.
Here is an example to create buttons, labels, text fields,
check boxes, radio buttons, and combo boxes.

223
By default, the class, variable, or method can be
accessed by any class in the same package.
 public
The class, data, or method is visible to any class in any
package.

 private
The data or methods can be accessed only by the declaring
class.
The get and set methods are used to read and modify private
properties.
224
package p1; package p2;
public class C1 { public class C2 { public class C3 {
public int x; void aMethod() { void aMethod() {
int y; C1 o = new C1(); C1 o = new C1();
private int z; can access o.x; can access o.x;
can access o.y; cannot access o.y;
public void m1() { cannot access o.z; cannot access o.z;
}
void m2() { can invoke o.m1(); can invoke o.m1();
} can invoke o.m2(); cannot invoke o.m2();
private void m3() { cannot invoke o.m3(); cannot invoke o.m3();
} } }
} } }

package p1; package p2;


class C1 { public class C2 { public class C3 {
... can access C1 cannot access C1;
} } can access C2;
}

The private modifier restricts access to within a class, the default modifier restricts
access to within a package, and the public modifier enables unrestricted access.

225
To protect data.

To make class easy to maintain.

226
END

You might also like