Chapter 3 Flashcards
What does an if statement do?
It decides whether a section of code executes based on a condition.
What is the syntax for an if statement?
if (boolean expression)
statement;
What happens if an if statement doesn’t use curly braces?
Only the first statement after the if condition is executed conditionally.
How do you group multiple statements in an if block?
Use curly braces {} to enclose the statements.
Example:
if (x > 0) {
System.out.println(“Positive”);
System.out.println(“Greater than zero”);
}
What is a flag?
A boolean variable that monitors a condition in a program.
How can characters be compared in Java?
Characters can be compared using relational operators because they are stored as Unicode values.
Example:
if (‘A’ < ‘Z’)
System.out.println(“A comes before Z”);
What does an if-else statement do?
Executes one block of code if the condition is true and another block if the condition is false.
Syntax:
if (condition)
statement1;
else
statement2;
What is a nested if statement?
An if statement inside another if statement.
How does an if-else-if statement work?
It simplifies multiple decision branches.
Syntax:
if (condition1)
statement1;
else if (condition2)
statement2;
else
statement3;
What are the three logical operators in Java?
Logical AND (&&)
Logical OR (||)
Logical NOT (!)
When does && evaluate to true?
When both operands are true.
When does || evaluate to true?
When at least one operand is true.
What does the ! operator do?
It negates the truth value of a boolean expression.
Example:
if (!(temperature > 100))
System.out.println(“Below max temperature”);
What is short-circuit evaluation?
&& stops evaluating as soon as one operand is false.
|| stops evaluating as soon as one operand is true.
Can relational operators compare two String objects?
No, use methods like equals or compareTo.