If statements
COP 3330 – Object Oriented Programming in Java
Boolean Expressions and the If Statement
Boolean Expressions
Definition: In Java,
boolean(in lowercase) is a type that can hold one of two values:Literals:
truefalse
Example:
boolean ok = true;This statement initializes a variable named
oktotrue.
Relational Operators
Definition: Boolean expressions can be constructed using relational operators that compare primitive quantitative types.
List of Operators:
Greater Than:
>Greater Than or Equal To:
>=Less Than:
<Less Than or Equal To:
<=Equal To:
==Not Equal To:
!=
Comparison with C and Python:
In both C and Java, the operators behave similarly.
In C, the result is an integer (0 or 1) rather than a boolean.
For example, if
ageis set to 40:age >= 21evaluates totrue.age < 40evaluates tofalse.
Boolean Operators
Use: To create complex boolean expressions, multiple simple boolean expressions can be combined using boolean operators.
List of Operators:
Logical AND:
&&Logical OR:
||Logical NOT:
!
Comparison with Other Languages:
The operators in Java correspond with C.
Python uses keywords (e.g.
and,or,not) instead of symbols.
Example:
If
ageis set to 17, the expressionage >= 16 && age <= 18evaluates totrue.Note:
16 <= age <= 18does not compile in Java, but works in C because it evaluates16 <= agefirst, yielding 1 (true), which is then compared to whether it's<= 18. In Python, it gets interpreted implicitly withand.
Advantages of Java:
The strict rules in Java catch more errors at compile time, reducing debugging time for the programmer.
If Statement
General Description:
The
ifstatement functions similarly across C, Python, and Java, with minor syntax differences.
Block of Statements:
Python: Indentation signifies a block.
C and Java: Curly braces
{}are used to denote a block of statements inside a control structure.Styles:
Placing the opening brace on the same line as the control structure.
Placing the opening brace on the next line left-justified.
Closing braces should be left-justified to match the start of the control structure.
Single Statement Rule:
All three languages allow only one statement officially within an
ifstatement, but a block of statements is treated as a single statement.In Java and C, failing to use braces means only the next statement is executed within the
if.In Python, indentation clarifies what belongs to the control structure.
If Statement Versions
Version 1: Basic If Statement
Syntax:
```java
if (boolean_expression) stmt;
- For multiple statements inside, use:
java
if (boolean_expression) {
stmt1;
…
stmtk;
}
- **Behavior**: If the boolean expression evaluates to `true`, execute statements inside; otherwise, skip them.
- **Version 2**: If-Else Statement
- **Syntax**:
java
if (boolean_expression) stmt; else stmt;
- Using blocks:
java
if (boolean_expression) {
stmta1;
…
stmtak;
} else {
stmtb1;
…
stmtbk;
}
- **Behavior**: Executes statements based on the evaluation of the boolean expression; one block runs, the other is skipped.
- **Version 3**: Else-If Ladder
- **Syntax**:
java
if (booleanexpression1) stmt1;
else if (booleanexpression2) stmt2;
else if (booleanexpression3) stmt3;
…
else if (booleanexpressionk) stmtk;
- **Behavior**: Evaluates expressions in order; executes the block of the first `true` expression; if no expressions are true, none are executed.
- **Note**: In Python, the keyword `elif` is used instead of `else if`.
- **Version 4**: Else-If with Default Case
- **Syntax**:
java
if (booleanexpression1) stmt1;
else if (booleanexpression2) stmt2;
else if (booleanexpression3) stmt3;
…
else if (booleanexpressionk) stmtk;
else stmtn;
- **Behavior**: A default action `stmtn` is executed if all previous boolean expressions evaluate to `false`.
### If Statement Design/Caveats
- **Flexibility**: With four constructs, a programmer can create a vast variety of programs.
- **Logical Nuances**: The structure and placement of statements can significantly impact execution and meaning.
- **Common Error**: Beginners often feel compelled to use `else` with every `if`; however, not every logical task requires an `else`.
### Example Using Framework #1
- **Context**: Determine item cost with or without tax.
- **Program**:
java
import java.util.*;
public class SalesTax {
final public static double SALESTAXRATE = 0.065;
public static void main(String[] args) {
// Get cost.
Scanner stdin = new Scanner(System.in);
System.out.println("How much did your item cost?");
double cost = stdin.nextDouble();
// Get if it's taxed or not.
System.out.println("Is it taxed?(0=no,1=yes)");
int tax = stdin.nextInt();
// Add tax only if necessary.
if (tax == 1) cost += (cost * SALESTAXRATE);
// Print final cost.
System.out.printf("Your final cost is $%.2f.\n", cost);
}
}
- **Notes**:
- One statement inside the `if` does not require a block of statements.
- Indentation is essential for readability, even if Java allows flexibility in indents.
- Experimentation: Change `==` to `=` to observe outcomes and learn about common programming errors.
### Example Using Framework #2
- **Context**: Temperature conversion between Celsius and Fahrenheit.
- **Program**:
java
import java.util.*;
public class Temp {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
// Get the desired conversion.
System.out.println("Would you like to…");
System.out.println("1. Convert from Celsius to Fahrenheit.");
System.out.println("2. Convert from Fahrenheit to Celsius.");
int ans = stdin.nextInt();
double fahr, cel;
// cel -> fahr.
if (ans == 1) {
// Read in the input temperature.
System.out.println("What is the temperature in Celsius?");
cel = stdin.nextDouble();
// Calculate and output temperature in Fahrenheit.
fahr = 1.8 * cel + 32;
System.out.print("The converted temperature is " + fahr);
System.out.println(" degrees Fahrenheit.");
}
// fahr -> cel
else {
// Read in the input temperature.
System.out.println("What is the temperature in Fahrenheit?");
fahr = stdin.nextDouble();
// Calculate and output temperature in Celsius.
cel = 5 * (fahr - 32) / 9;
System.out.print("The converted temperature is " + cel);
System.out.println(" degrees Celsius.");
}
}
}
- **Notes**:
- Menu presents two choices.
- Each choice has its own block for the corresponding task.
- Calculations and print statements change based on selected task.
### Example Using Framework #3
- **Context**: Calculate user's age based on birth date.
- **Concept**: Subtract birth year from the current year and adjust based on birthday.
- **Program**:
java
import java.util.*;
public class Age {
final public static int CURYEAR = 2026;
public static void main(String[] argv) {
Scanner stdin = new Scanner(System.in);
System.out.println("Enter the month of your birthday:");
int month = stdin.nextInt();
System.out.println("Enter the day of your birthday:");
int day = stdin.nextInt();
System.out.println("Enter the year of your birthday:");
int year = stdin.nextInt();
System.out.println("Enter today's month:");
int curmonth = stdin.nextInt();
System.out.println("Enter today's day:");
int curday = stdin.nextInt();
int age = CURYEAR - year;
if (curmonth < month) age--;
else if (curmonth == month && curday < day) age--;
System.out.println("You are " + age + " years old.");
}
}
- **Notes**:
- The program calculates age correctly by adjusting for the actual birthday.
- Logic is handled with clear `if` and `else if` structures.
### Example Using Framework #4
- **Context**: Convert numeric grades to letter grades (A, B, C, D, F).
- **Program**:
java
import java.util.*;
public class ClassGrade {
public static void main(String[] args) {
// Get input.
Scanner stdin = new Scanner(System.in);
System.out.println("What percent(integer) did you get?");
int grade = stdin.nextInt();
char letter;
// Criterion for an A.
if (grade >= 90) letter = 'A';
else if (grade >= 80) letter = 'B';
else if (grade >= 70) letter = 'C';
else if (grade >= 60) letter = 'D';
else letter = 'F';
// Show letter grade.
System.out.println("Your letter grade is " + letter + ".");
}
}
```
Notes:
The program contains logical branches to evaluate and assign letter grades based on numeric input.
The order of these conditions is crucial to ensure proper grading.
If conditions are not mutually exclusive, errors may result (e.g., if checking for D were done before C).