Unit-2�Selections , Mathematical functions and loops
String
1
The boolean Type and Operators
boolean b = (1 > 2);
Relational Operators
One-way if Statements
if (boolean-expression) {
statement(s);
}
4
if (radius >= 0) {
area = radius * radius * PI;
System.out.println("The area"
+ " for the circle of radius "
+ radius + " is " + area);
}
Note
5
Simple if Demo
6
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.
The Two-way if Statement
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
7
if-else Example
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");
}
8
Multiple Alternative if Statements
9
Multi-Way if-else Statements
10
Trace if-else statement
11
if (score >= 90.0)
System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");
Suppose score is 70.0
The condition is false
animation
Trace if-else statement
12
if (score >= 90.0)
System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");
Suppose score is 70.0
The condition is false
animation
Trace if-else statement
13
if (score >= 90.0)
System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");
Suppose score is 70.0
The condition is true
animation
Trace if-else statement
14
if (score >= 90.0)
System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");
Suppose score is 70.0
grade is C
animation
Trace if-else statement
15
if (score >= 90.0)
System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");
Suppose score is 70.0
Exit the if statement
animation
Note
The else clause matches the most recent if clause in the same block.
16
Note, cont.
Nothing is printed from the preceding statement. To force the else clause to match the first if clause, you must add a pair of braces:
int i = 1;
int j = 2;
int k = 3;
if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");
This statement prints B.
17
Common Errors
Adding a semicolon at the end of an if clause is a common mistake.
if (radius >= 0);
{
area = radius*radius*PI;
System.out.println(
"The area for the circle of radius " +
radius + " is " + area);
}
This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error.
This error often occurs when you use the next-line block style.
18
Wrong
Problem: Body Mass Index
Body Mass Index (BMI) is a measure of health on weight. It can be calculated by taking your weight in kilograms and dividing by the square of your height in meters. The interpretation of BMI for people 16 years or older is as follows:
19
Logical Operators
20
Operator | Name | Description |
! | not | logical negation |
&& | and | logical conjunction |
|| | or | logical disjunction |
^ | exclusive or | logical exclusion |
Truth Table for Operator !
21
p | !p | Example (assume age = 24, weight = 140) |
true | false | !(age > 18) is false, because (age > 18) is true. |
false | true | !(weight == 150) is true, because (weight == 150) is false. |
Truth Table for Operator &&
22
p1 | p2 | p1 && p2 | Example (assume age = 24, weight = 140) |
false | false | false | (age <= 18) && (weight < 140) is false, because both conditions are both false. |
false | true | false |
|
true | false | false | (age > 18) && (weight > 140) is false, because (weight > 140) is false. |
true | true | true | (age > 18) && (weight >= 140) is true, because both (age > 18) and (weight >= 140) are true. |
Truth Table for Operator ||
23
p1 | p2 | p1 || p2 | Example (assume age = 24, weihgt = 140) |
false | false | false | |
false | true | true | (age > 34) || (weight <= 140) is true, because (age > 34) is false, but (weight <= 140) is true. |
true | false | true | (age > 14) || (weight >= 150) is false, because (age > 14) is true. |
true | true | true |
|
Truth Table for Operator ^
24
p1 | p2 | p1 ^ p2 | Example (assume age = 24, weight = 140) |
false | false | false | (age > 34) ^ (weight > 140) is true, because (age > 34) is false and (weight > 140) is false. |
false | true | true | (age > 34) ^ (weight >= 140) is true, because (age > 34) is false but (weight >= 140) is true. |
true | false | true | (age > 14) ^ (weight > 140) is true, because (age > 14) is true and (weight > 140) is false. |
true | true | false |
|
Examples(TestBooleanOperators.java)�
25
Here is a program that checks whether a number is divisible by 2 and 3, whether a number is divisible by 2 or 3, and whether a number is divisible by 2 or 3 but not both:
switch Statements
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);
}
27
switch Statement Flow Chart
28
switch Statement Rules
29
switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
…
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}
The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses.
The value1, ..., and valueN must have the same data type as the value of the switch-expression. The resulting statements in the case statement are executed when the value in the case statement 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.
switch Statement Rules
The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed.
30
switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
…
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}
The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression.
When the value in a case statement matches the value of the switch-expression, the statements starting from this case are executed until either a break statement or the end of the switch statement is reached.
Trace switch statement
31
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
Suppose day is 2:
animation
Trace switch statement
32
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
Match case 2
animation
Trace switch statement
33
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
Fall through case 3
animation
Trace switch statement
34
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
Fall through case 4
animation
Trace switch statement
35
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
Fall through case 5
animation
Trace switch statement
36
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
Encounter break
animation
Trace switch statement
37
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
Exit the statement
animation
Conditional Expressions
if (x > 0)
y = 1
else
y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;
(boolean-expression) ? expression1 : expression2
Ternary operator
Binary operator
Unary operator
38
Conditional Operator
if (num % 2 == 0)
System.out.println(num + “is even”);
else
System.out.println(num + “is odd”);
System.out.println(
(num % 2 == 0)? num + “is even” :
num + “is odd”);
39
Conditional Operator, cont.
boolean-expression ? exp1 : exp2
40
LOOPS(WHILE , FOR)
Problem
System.out.println("Welcome to Java!");
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!");
…
…
…
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
100 times
while Loop Flow Chart
while (loop-continuation-condition) {
// loop-body;
Statement(s);
}
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java!");
count++;
}
import java.io.*;
class GFG {
public static void main(String[] args)
{
int i = 5;
while (i < 10) {
i++;
System.out.println("GfG");
}
}
}
Trace while Loop
46
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Initialize count
Trace while Loop, cont.
47
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
(count < 2) is true
Trace while Loop, cont.
48
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Print Welcome to Java
Trace while Loop, cont.
49
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Increase count by 1
count is 1 now
Trace while Loop, cont.
50
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Print Welcome to Java
Trace while Loop, cont.
51
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
(count < 2) is still true since count is 1
Trace while Loop, cont.
52
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Increase count by 1
count is 2 now
Trace while Loop, cont.
53
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
(count < 2) is false since count is 2 now
Trace while Loop
54
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
The loop exits. Execute the next statement after the loop.
Caution
do-while Loop
do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
import java.io.*;
class GFG {
public static void main(String[] args)
{
int i = 5;
do {
i++;
System.out.println("GfG");
} while (i < 10);
}
}
for Loops
for (initial-action; loop-continuation-condition; action-after-each-iteration)
{
// loop body;
Statement(s);
}
Example:
int i;
for (i = 0; i < 100; i++)
{
System.out.println(
"Welcome to Java!");
}
Trace for Loop
int i;
for (i = 0; i < 2; i++) {
System.out.println(
"Welcome to Java!");
}
Declare i
Trace for Loop, cont.
61
int i;
for (i = 0; i < 2; i++) {
System.out.println(
"Welcome to Java!");
}
Execute initializer
i is now 0
Trace for Loop, cont.
62
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
Print Welcome to Java
Trace for Loop, cont.
63
int i;
for (i = 0; i < 2; i++) {
System.out.println( "Welcome to Java!");
}
(i < 2) is true
since i is 0
Trace for Loop, cont.
64
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
Execute adjustment statement
i now is 1
Trace for Loop, cont.
65
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
(i < 2) is still true
since i is 1
Trace for Loop, cont.
66
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
Print Welcome to Java
Trace for Loop, cont.
67
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
Execute adjustment statement
i now is 2
Trace for Loop, cont.
68
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
(i < 2) is false
since i is 2
Trace for Loop, cont.
69
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
Exit the loop. Execute the next statement after the loop
Note
Caution
Logic Error
for (int i=0; i<10; i++);
{
System.out.println("i is " + i);
}
Caution, cont.
Similarly, the following loop is also wrong:
int i=0;
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);
Example:SimpleForDemo.java
Nested Loops
Problem:
Write a program that uses nested for loops to print a multiplication table.
Using break and continue
break
continue
Mathematical functions and String
78
Mathematical Functions
The Math Class
Trigonometric Methods
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
Example:: Math_fun.java
Exponent Methods
Returns e raised to the power of a.
Returns the natural logarithm of a.
Returns the 10-based logarithm of a.
Returns a raised to the power of b.
Returns the square root of a.
Examples:
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
Example:: Math_fun1.java
The random Method
In general
Example:: Random1.java
public class Random {
public static void main(String args[]) {
// Generating random doubles
System.out.println("Random doubles: " +(int)(Math.random()*10));
System.out.println("Random doubles: " + Math.random());
}
Random doubles: 5
Random doubles: 0.9665636788509409
ASCII Code for Commonly Used Characters
The random Class
The random Class Methods
Methods | Description |
Generates the next pseudorandom number. | |
Returns the next uniformly distributed pseudorandom boolean value from the random number generator's sequence | |
Generates random bytes and puts them into a specified byte array. | |
Returns the next pseudorandom Double value between 0.0 and 1.0 from the random number generator's sequence | |
Returns the next uniformly distributed pseudorandom Float value between 0.0 and 1.0 from this random number generator's sequence | |
Returns a uniformly distributed pseudorandom int value generated from this random number generator's sequence | |
Returns the next uniformly distributed pseudorandom long value from the random number generator's sequence. | |
Sets the seed of this random number generator using a single long seed. |
Example:: Random2.java
Example:: Random3.java
import java.util.Random;
public class Randomclass {
public static void main(String args[])
{
// create instance of Random class
Random rand = new Random();
// Generate random integers in range 0 to 999
int rand_int1 = rand.nextInt(1000);
// Print random integers
System.out.println("Random Integers: "+rand_int1);
// Generate Random doubles
double rand_dub1 = rand.nextDouble();
// Print random doubles
System.out.println("Random Doubles: "+rand_dub1);
}
}
Random Integers: 854
Random Doubles: 0.9329324962596014
String Class
String message = "Welcome to Java";
Simple Methods for String Class
Simple Methods for String Objects
referenceVariable.methodName(arguments).
Getting String Length
String message = "Welcome to Java";
System.out.println("The length of " + message + " is "
+ message.length());
Getting Characters from a String
String message = "Welcome to Java";
System.out.println("The first character in message is " + message.charAt(0));
Converting Strings
Welcome".toLowerCase() returns a new string, welcome.
"Welcome".toUpperCase() returns a new string, WELCOME.
" Welcome ".trim() returns a new string, Welcome.
String Concatenation
String s3 = s1.concat(s2);
Or
String s3 = s1 + s2;
// 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'; // s1 becomes SupplementB
Reading a String from the Console
Scanner input = new Scanner(System.in);
System.out.print("Enter three words separated by spaces: ");
String s1 = input.next();
String s2 = input.next();
String s3 = input.next();
System.out.println("s1 is " + s1);
System.out.println("s2 is " + s2);
System.out.println("s3 is " + s3);
Reading a Character from the Console
Scanner input = new Scanner(System.in);
System.out.print("Enter a character: ");
String s = input.nextLine();
char ch = s.charAt(0);
System.out.println("The character entered is " + ch);
Comparing Strings
Obtaining Substrings
Finding a Character or a Substring in a String
Finding a Character or a Substring in a String
int k = s.indexOf(' ');
String firstName = s.substring(0, k);
String lastName = s.substring(k + 1);
Example