1 of 102

Unit-2�Selections , Mathematical functions and loops

String

1

2 of 102

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

3 of 102

Relational Operators

4 of 102

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

}

5 of 102

Note

5

6 of 102

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.

7 of 102

The Two-way if Statement

if (boolean-expression) {

statement(s)-for-the-true-case;

}

else {

statement(s)-for-the-false-case;

}

7

8 of 102

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

9 of 102

Multiple Alternative if Statements

9

10 of 102

Multi-Way if-else Statements

10

11 of 102

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

12 of 102

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

13 of 102

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

14 of 102

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

15 of 102

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

16 of 102

Note

The else clause matches the most recent if clause in the same block.

16

17 of 102

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

18 of 102

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

19 of 102

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

20 of 102

Logical Operators

20

Operator

Name

Description

!

not

logical negation

&&

and

logical conjunction

||

or

logical disjunction

^

exclusive or

logical exclusion

21 of 102

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.

22 of 102

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.

23 of 102

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

 

24 of 102

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

 

25 of 102

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:

26 of 102

27 of 102

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

28 of 102

switch Statement Flow Chart

28

29 of 102

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.

30 of 102

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.

31 of 102

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

32 of 102

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

33 of 102

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

34 of 102

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

35 of 102

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

36 of 102

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

37 of 102

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

38 of 102

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

39 of 102

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

40 of 102

Conditional Operator, cont.

boolean-expression ? exp1 : exp2

40

41 of 102

LOOPS(WHILE , FOR)

42 of 102

Problem

  • Suppose that you need to print a string (e.g., "Welcome to Java!") a hundred times.
  • It would be tedious to have to write the following statement a hundred times:

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

43 of 102

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

44 of 102

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

}

45 of 102

import java.io.*;

class GFG {

public static void main(String[] args)

{

int i = 5;

while (i < 10) {

i++;

System.out.println("GfG");

}

}

}

46 of 102

Trace while Loop

46

int count = 0;

while (count < 2) {

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

count++;

}

Initialize count

47 of 102

Trace while Loop, cont.

47

int count = 0;

while (count < 2) {

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

count++;

}

(count < 2) is true

48 of 102

Trace while Loop, cont.

48

int count = 0;

while (count < 2) {

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

count++;

}

Print Welcome to Java

49 of 102

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

50 of 102

Trace while Loop, cont.

50

int count = 0;

while (count < 2) {

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

count++;

}

Print Welcome to Java

51 of 102

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

52 of 102

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

53 of 102

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

54 of 102

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.

55 of 102

Caution

  • Don’t use floating-point values for equality checking in a loop control.
  • Since floating-point values are approximations for some values, using them could result in imprecise counter values and inaccurate results.

  • Example:: SimpleWhileDemo.java

56 of 102

do-while Loop

do {

// Loop body;

Statement(s);

} while (loop-continuation-condition);

57 of 102

import java.io.*;

class GFG {

public static void main(String[] args)

{

int i = 5;

do {

i++;

System.out.println("GfG");

} while (i < 10);

}

}

58 of 102

59 of 102

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!");

}

60 of 102

Trace for Loop

int i;

for (i = 0; i < 2; i++) {

System.out.println(

"Welcome to Java!");

}

Declare i

61 of 102

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

62 of 102

Trace for Loop, cont.

62

int i;

for (i = 0; i < 2; i++) {

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

}

Print Welcome to Java

63 of 102

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

64 of 102

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

65 of 102

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

66 of 102

Trace for Loop, cont.

66

int i;

for (i = 0; i < 2; i++) {

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

}

Print Welcome to Java

67 of 102

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

68 of 102

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

69 of 102

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

70 of 102

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:

71 of 102

Caution

  • Adding a semicolon at the end of the for clause before the loop body is a common mistake.

Logic Error

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

{

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

}

72 of 102

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

73 of 102

74 of 102

Nested Loops

Problem:

Write a program that uses nested for loops to print a multiplication table.

  • Example:: MultiplicationTable.java

75 of 102

Using break and continue

  • Example:: TestBreak.java
  • Example:: TestContinue.java

76 of 102

break

77 of 102

continue

78 of 102

Mathematical functions and String

78

79 of 102

Mathematical Functions

  • Java provides many useful methods in the Math class for performing common mathematical functions.
  • https://www.javatpoint.com/java-math

80 of 102

The Math Class

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

81 of 102

Trigonometric Methods

  • sin(double a)
  • cos(double a)
  • tan(double a)
  • acos(double a)
  • asin(double a)
  • atan(double a)

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

82 of 102

Exponent Methods

  • exp(double a)

Returns e raised to the power of a.

  • log(double a)

Returns the natural logarithm of a.

  • log10(double a)

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.

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

83 of 102

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

In general

Example:: Random1.java

84 of 102

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

85 of 102

ASCII Code for Commonly Used Characters

86 of 102

The random Class

  • Random class is used to generate pseudo-random numbers in java.
  • This class provides various method calls to generate different random data types such as float, double, int.
  • Constructors:
    • Random(): Creates a new random number generator
    • Random(long seed): Creates a new random number generator using a single long seed

87 of 102

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

88 of 102

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

89 of 102

String Class

  • The char type only represents one character. To represent a string of characters, use the data type called String.

String message = "Welcome to Java";

  • String is actually a predefined class in the Java library just like the System class and Scanner 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.

https://www.javatpoint.com/java-string.

90 of 102

Simple Methods for String Class

91 of 102

Simple Methods for String Objects

  • Strings are objects in Java.
  • The methods in the preceding table can only be invoked from a specific string instance. For this reason, these methods are called instance methods.
  • A non-instance method is called a static method. A static method can be invoked without using an object.
  • All the methods defined in the Math class are static methods. They are not tied to a specific object instance.
  • The syntax to invoke an instance method is

referenceVariable.methodName(arguments).

92 of 102

Getting String Length

String message = "Welcome to Java";

System.out.println("The length of " + message + " is "

+ message.length());

93 of 102

Getting Characters from a String

String message = "Welcome to Java";

System.out.println("The first character in message is " + message.charAt(0));

94 of 102

Converting Strings

Welcome".toLowerCase() returns a new string, welcome.

"Welcome".toUpperCase() returns a new string, WELCOME.

" Welcome ".trim() returns a new string, Welcome.

95 of 102

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

96 of 102

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

97 of 102

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

98 of 102

Comparing Strings

99 of 102

Obtaining Substrings

100 of 102

Finding a Character or a Substring in a String

101 of 102

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

102 of 102

Example

  • Demo_string.java
  • Demo_string1.java