Java Programming for Beginners: From Introduction To Your First Java Project

Concepts:

Use if, else if, and else to execute code based on conditions. Learn about the switch statement for multiple fixed outcomes.

Conditions and If Statements

Conditions and if statements let you control the flow of your program.

if statement needs a condition that results in true or false. Comparison operators:

Less than:      a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to:        a == b
Not equal to:  a != b

if the same condition is false use else to a code to be executed.

Code example

public class ConditionalExample {
 public static void main(String[] args) {
  int score = 85;
  if (score >= 90) {
   System.out.println(“Grade: A”);
   } else if (score >= 80) {
   System.out.println(“Grade: B”);
   } else {
   System.out.println(“Grade: C”);
   }
 }
}

 

Quiz: Determine the output of code blocks with if-else and switch statements.