Labs ICT
โญ Pro Login

If...Else

Life is full of decisions. Should you take the highway or the back roads? Coffee or tea? Java has the same kind of thing โ€” it is called if-else statements. And honestly, you are going to use them all the time.

An if-else statement lets your program make decisions based on conditions. If a condition is true, do one thing. Otherwise, do something else. It is that simple.

The if Statement

The simplest form is just an if. You give it a condition in parentheses, and if that condition is true, the code inside the curly braces runs.

int age = 18;

if (age >= 18) {
  System.out.println("You are an adult");
}

if-else

But what if you want to do something when the condition is false? That is where else comes in.

int age = 16;

if (age >= 18) {
  System.out.println("You can vote");
} else {
  System.out.println("Too young to vote");
}

else if

What if you have more than two possibilities? Use else if to chain multiple conditions together.

int score = 85;

if (score >= 70) {
  System.out.println("Grade A");
} else if (score >= 60) {
  System.out.println("Grade B");
} else if (score >= 50) {
  System.out.println("Grade C");
} else {
  System.out.println("Fail");
}

Java checks each condition from top to bottom. The first one that is true wins, and the rest are skipped.

Nested if

You can put an if statement inside another if statement. This is called nesting. Just be careful โ€” too much nesting and your code becomes hard to read.

int age = 20;
boolean hasID = true;

if (age >= 18) {
  if (hasID) {
    System.out.println("You can enter");
  } else {
    System.out.println("Bring your ID");
  }
}

The Ternary Operator

Java has a shorthand for simple if-else statements called the ternary operator. It uses ? and :. Think of it as a compact if-else.

int age = 20;
String result = (age >= 18) ? "Adult" : "Minor";

System.out.println(result);

The syntax is condition ? valueIfTrue : valueIfFalse. It is great for simple decisions but do not try to nest these things โ€” nobody wants to read a ? b ? c : d : e.

๐Ÿงช Quick Quiz

What does the following code print? int x = 10; if (x > 5) { System.out.println("A"); } else { System.out.println("B"); }