Boolean Expressions | If Statements and Control Flow | If-Else Statements | Code Example | Hacks | Quiz |
Unit 3 - Boolean Expressions and if Statements
Boolean Expressions and if Statements
- Introduction
- Boolean Expressions
- If Statements and Control Flow
- If-Else Statements
- Else If Statements
- Compound Boolean Expressions
- Equivalents Boolean Expressions
- Comparing Objects
- Hacks
Introduction
In Java, evaluating conditions and controlling the flow of your program is fundamental. This involves using boolean expressions and operators, as well as conditional statements like if, if-else, and else if. These constructs help you make decisions and execute different blocks of code based on varying conditions. Understanding how to use these effectively is crucial for writing clear and efficient code.
Boolean Expressions
Boolean expressions evaluate to either true or false and use the following operators:
==
(equals to)!=
(not equal to)<
(less than)<=
(less than or equal to)>
(greater than)>=
(greater than or equal to)
These operators compare primitive types like integers and doubles. For example:
3 < 5
returns true3 >= 5
returns false
Boolean Logic Operators include:
- ! (NOT): Negates the expression. Example:
!true
evaluates tofalse
. - && (AND): Returns true if both expressions are true. Example:
(a % 2 == 0) && (a % 3 == 0)
is true ifa
is divisible by both 2 and 3. - || (OR): Returns true if at least one expression is true. Example:
(a % 2 == 0) || (a % 3 == 0)
is true ifa
is divisible by either 2 or 3.
Order of Operations:
- NOT
- AND
- OR
Compound Boolean Statements combine multiple conditions:
if ((number % 2 == 0) && (number % 3 == 0)) {
return "Even and divisible by 3";
} else if (number % 2 == 0) {
return "Even";
}
Truth Tables help simplify boolean expressions by testing all possible inputs. For example, a || ((!b && !a) && !b)
simplifies to a || !b
.
If Statements and Control Flow
If Statements
An if statement allows you to execute a block of code only if a specified condition is true.
Example: Even Number Checker
public static int numberHalver(int number) {
if (number % 2 == 0) {
number /= 2;
}
return number;
}
In this example, the number is halved if it is even.
Return Statements
A return statement inside an if statement causes the method to terminate immediately with the return value, skipping any remaining code.
Example: Check Even Number
public static boolean isEven(int number) {
if (number % 2 == 0) {
return true;
}
return false;
}
Here, return false;
is only reached if the condition is not met.
If-Else Statements
An if-else statement executes one block of code if a condition is true, and another if the condition is false.
Example: Number Rounding
public static int round(double number) {
if (number >= 0) {
return (int) (number + 0.5);
} else {
return (int) (number - 0.5);
}
}
This method rounds a number based on its sign.
If-Else If-Else Statements
The if-else if-else structure checks multiple conditions in sequence, executing different blocks of code based on which condition is true.
Example: Divisibility Counter
public static int largestDivisorLessThanTen(int number) {
if (number % 10 == 0) { return 10; }
else if (number % 9 == 0) { return 9; }
else if (number % 8 == 0) { return 8; }
else if (number % 7 == 0) { return 7; }
else if (number % 6 == 0) { return 6; }
else if (number % 5 == 0) { return 5; }
else if (number % 4 == 0) { return 4; }
else if (number % 3 == 0) { return 3; }
else if (number % 2 == 0) { return 2; }
else { return 1; }
}
This method finds the largest divisor between 1 and 10 for a given number.
If-Else Statements
An if-else statement allows you to execute one block of code if a condition is true, and another block if the condition is false. It’s known as a two-way selection.
Anatomy of an If-Else Statement:
// Some code that runs before the conditional statement
if (condition) {
// Code that runs if the condition is true
} else {
// Code that runs if the condition is false
}
// Some code that runs after
- Condition: Enclosed in parentheses.
- If Block: Contains code that runs if the condition is true, enclosed in curly braces
{}
. - Else Block: Contains code that runs if the condition is false, also enclosed in curly braces
{}
.
Make sure to use brackets around the code in both the if
and else
blocks. This prevents confusion about which code is associated with each block and avoids unexpected behavior.
Example: Number Rounding
Here’s a method that rounds a number to the nearest integer using an if-else statement:
public static int round(double number) {
if (number >= 0) {
return (int) (number + 0.5);
} else {
return (int) (number - 0.5);
}
}
- If Block: Rounds up if the number is non-negative.
- Else Block: Rounds down if the number is negative.
Else If Statements
Else if statements are used when you need to handle multiple conditions in sequence. They allow you to test several conditions and execute different blocks of code depending on which condition is true.
Anatomy of an Else If Statement:
if (condition1) {
// Code runs if condition1 is true
} else if (condition2) {
// Code runs if condition1 is false and condition2 is true
} else if (condition3) {
// Code runs if condition1 and condition2 are false and condition3 is true
}
// Additional else if statements as needed
else {
// Code runs if none of the above conditions are true
}
- If Block: Executes if
condition1
is true. - Else If Blocks: Execute if the preceding conditions are false and the current condition is true.
- Else Block: Executes if none of the above conditions are true.
Example: Divisibility Counter
This method returns the largest divisor between 1 and 10 that a number is divisible by:
public static int largestDivisorLessThanTen(int number) {
if (number % 10 == 0) { return 10; }
else if (number % 9 == 0) { return 9; }
else if (number % 8 == 0) { return 8; }
else if (number % 7 == 0) { return 7; }
else if (number % 6 == 0) { return 6; }
else if (number % 5 == 0) { return 5; }
else if (number % 4 == 0) { return 4; }
else if (number % 3 == 0) { return 3; }
else if (number % 2 == 0) { return 2; }
else { return 1; }
}
Example: Leap Year Decider
This method determines if a year is a leap year:
public static boolean isLeap(int year) {
if (year % 400 == 0) { return true; }
else if (year % 100 == 0) { return false; }
else if (year % 4 == 0) { return true; }
return false; // This line runs if none of the above conditions are true
}
Tip: Order the conditions from most specific to least specific to ensure the correct block of code executes.
Compound Boolean Expressions
Compound boolean expressions combine multiple boolean conditions using logical operators to form more complex conditions.
Example:
if ((number % 2 == 0) && (number % 3 == 0)) {
return "Even and divisible by 3";
} else if (number % 2 == 0) {
return "Even";
}
In this example:
(number % 2 == 0) && (number % 3 == 0)
checks if a number is both even and divisible by 3.- If true, it returns “Even and divisible by 3”.
- If the first condition is false but the number is still even, it returns “Even”.
Compound boolean expressions simplify multiple condition checks into a single statement, enhancing readability and reducing nesting.
Equivalents Boolean Expressions
Boolean expressions can often be simplified or transformed into equivalent forms. For example, a boolean expression like a || ((!b && !a) && !b)
can be simplified. To simplify such expressions, you can use truth tables to test all possible input combinations.
Here’s how you can simplify expressions:
Truth Table Example for a || ((!b && !a) && !b)
:
a | b | !a | !b | !b && !a | (!b && !a) && !b | a || ((!b && !a) && !b) |
---|---|---|---|---|---|---|
False | False | True | True | True | True | True |
False | True | True | False | False | False | False |
True | False | False | True | False | False | True |
True | True | False | False | False | False | True |
From this truth table, we see that a || ((!b && !a) && !b)
simplifies to a || !b
.
Comparing Objects
In Java, to compare objects for equality, you should understand the differences between the ==
operator and the equals()
method:
Equality Operator (==
)
The ==
operator checks if two references point to the exact same object in memory. It does not compare the values or attributes of the objects.
Examples:
String a = "Hi";
String b = "Hi";
String c = a;
String d = new String("Hi");
System.out.println(a == c); // true (same reference)
System.out.println(a == b); // true (interned string literals)
System.out.println(a == d); // false (different references)
equals()
Method
The equals()
method compares the values or attributes of two objects. It is often overridden in custom classes to provide meaningful equality checks based on the class’s attributes.
Examples:
String a = "Hi";
String b = "Hi";
String d = new String("Hi");
System.out.println(a.equals(b)); // true (same content)
System.out.println(a.equals(d)); // true (same content)
Key Points:
==
Operator: Checks reference equality. Use it to see if two references point to the same object.equals()
Method: Checks value equality. Use it to compare the contents of objects.
When comparing objects, use equals()
unless you need to check if the references are the same instance. Understanding these methods helps in writing accurate and effective Java code.
Additional Resources:
Hacks
Part 1
public class Book {
String title;
String author;
int pages;
public Book(String title, String author, int pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
public boolean isLongBook() {
if (this.pages > 300) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
Book book1 = new Book("1984", "George Orwell", 328);
Book book2 = new Book("Brave New World", "Aldous Huxley", 288);
System.out.println(book1.isLongBook());
System.out.println(book2.isLongBook());
}
}
Answer the following questions based on the code above:
- a) What will be the output of the
System.out.println(book1.isLongBook());
statement? Explain the reasoning behind this output based on the code. - Answer:
- b) Modify the
isLongBook()
method to use a single return statement without using theif-else
structure. Rewrite the method and explain how your code achieves the same functionality. - Answer:
Part 2
Situation: You are developing a library management system where you need to manage book details and check certain conditions based on the book attributes. You want to write methods that utilize Boolean expressions and if statements to control the flow of your program.
(a) Explain the purpose of Boolean expressions in Java and how they are used within if statements to control the flow of a program. Provide an example using a simple comparison between two integers.
(b) Discuss the importance of order in if-else if-else statements. How does the order of conditions affect the program’s execution? Provide an example with three conditions to demonstrate your explanation.
(c) Code:
You have a method isEligibleForDiscount
that determines if a book is eligible for a discount based on its price and genre. The method should take two parameters: a double price
representing the book’s price, and a String genre
representing the book’s genre. The book is eligible for a discount if its price is above $20 and its genre is either “Fiction” or “Mystery”.
Write the method signature and the method implementation. Include comments to explain your code.