Lecture-04 Selection: by Dr. Bharati Mishra
Lecture-04 Selection: by Dr. Bharati Mishra
Selection
By
Dr. Bharati Mishra
Agenda
• boolean Data Type
• if Statements
• Two-Way if-else Statements
• Nested if
• Multi-Way if-else Statements
• Common Errors and Pitfalls
• Generating Random Numbers
• Case Study:
• Computing Body Mass Index,
• Computing Taxes
• Logical Operators
• Case Study:
• Determining Leap Year, Lottery
boolean Data Type
Operator Name
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
!= Not equal to
Class vs. Primitive Type
10 Integer
….
y ….
x
Comparison Operators
• Be careful about ==
• Primitive data type:
• Compares the value
• Reference data type:
• Compares the references (memory address)!
• So only use with primitive data types
• E.g. if x and y are String
• x==y will not always return the correct result!
• Instead use String.compare(x,y)
• In general, use equals() to compare two objects
• E.g. a.equals(b)
Comparison Operators
“What is 7 + 9?”
• E.g.
if (radius >= 0) {
area = radius * radius * PI;
}
One way if
• Be careful!
If Program
• 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.
Two-way if
• If you get here by 10:00 am, then we can have
brunch, else we can go for lunch.
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
Two-way if
• Example
if (radius >= 0) {
area = radius * radius * 3.14159;
System.out.println("The area is: “ + area);
}
else {
System.out.println("Negative input");
}
Multiple if-else
• else if is used for checking multiple conditions
• This prints B.
Tips
• Some tips
Program
Operator Name
! not
&& and
|| OR
^ Exclusive OR
Logical Operators
• Or (||) operator
Logical Operators
• Equivalent to
if (radius >= 0) { };
other statements
• What is the output?
• Always prints the area, even for negative numbers
Case Study-01