🖇️Conditionals

💡 Conditionals in Java 👨‍💻

Conditionals allow executing different code blocks based on conditions. Here are the main conditionals in Java:

  • 👉 if: Executes code if condition is true

if (condition) {
  // code to execute if condition is true
}

The condition is written within the parentheses after the if keyword. It will be evaluated and must resolve to a Boolean true or false.

If true, the block of code following the opening curly brace will execute. If false, the code block is skipped over.

  • 👉 if-else: Executes one block if condition true, another if false

if (condition) {
  // code to run if condition is true
} else { 
  // code to run if condition is false
}

Within the parentheses after if, we specify the condition we want to check. This will evaluate to true or false. If true, the code block after if will run. If false, else code block runs.

  • 👉 else-if: Checks multiple conditions and executes corresponding blocks

if (condition1) {
  // code to execute if condition1 is true
} else if (condition2) {
  // code to execute if condition2 is true 
} else {
  // default code
}
  • 👉 switch: Selects one of many code blocks to execute based on a value

switch(expression) {
  case value1: 
    // code block 1
    break;
    
  case value2:
    // code block 2
    break;
    
  default: 
    // default code block
}

The expression is evaluated once and compared to the values provided in each case. If a match is found, the code block for that case is executed.

The key thing to note is the break keyword at the end of each case block. This prevents code from executing for subsequent cases if a match is found.

A default case can be added as a fallback if no other matches. Without break, it would fall through to other cases below.

  • 👉 Ternary: Shorthand for if-else statement

condition ? expression1 : expression2;

Rules

  • Condition must evaluate to a boolean value

  • Code blocks must be enclosed in {} braces

  • Break is needed in switch to exit the block

  • Default case is optional in switch

Java uses boolean variables to evaluate conditions. The boolean values true and false are returned when an expression is compared or evaluated. For example:

int a = 4;
boolean b = a == 4;

if (b) {
    System.out.println("It's true!");
}

Of course, we don't normally assign a conditional expression to a boolean. Normally, we just use the short version:

int a = 4;

if (a == 4) {
    System.out.println("Ohhh! So a is 4!");
}

Boolean operators

There aren't that many operators to use in conditional statements and most of them are pretty straightforward:

int a = 4;
int b = 5;
boolean result;
result = a < b; // true
result = a > b; // false
result = a <= 4; // a smaller or equal to 4 - true
result = b >= 6; // b bigger or equal to 6 - false
result = a == b; // a equal to b - false
result = a != b; // a is not equal to b - true
result = a > b || a < b; // Logical or - true
result = 3 < a && a < 6; // Logical and - true
result = !result; // Logical not - false

if - else and between

The if, else statement in Java is pretty simple.

if (a == b) {
    // a and b are equal, let's do something cool
}

And we can also add an else statement after an if, to do something if the condition is not true

if (a == b) {
    // We already know this part
} else {
    // a and b are not equal... :/
}

The if-else statements don't have to be in several lines with {}, if can be used in one line, or without the {}, for a single line statement.

if (a == b)
    System.out.println("Another line Wow!");
else
    System.out.println("Double rainbow!");

Although this method might be useful for making your code shorter by using fewer lines, we strongly recommend for beginners not use this short version of statements and always use the full version with {}. This goes for every statement that can be shortened to a single line (for, while, etc).

The ugly side of if

There is another way to write a one-line if - else statement by using the operator ? :

int a = 4;
int result = a == 4 ? 1 : 8;

// result will be 1
// This is equivalent to
int result;

if (a == 4) {
    result = 1;
} else {
    result = 8;
}

Again, we strongly recommend for beginners not to use this version of if.

== and equals

The operator == works a bit differently on objects than on primitives. When we are using objects and want to check if they are equal, the operator == will say if they are the same, if you want to check if they are logically equal, you should use the equals method on the object. For example:

String a = new String("Wow");
String b = new String("Wow");
String sameA = a;

boolean r1 = a == b;      // This is false, since a and b are not the same object
boolean r2 = a.equals(b); // This is true, since a and b are logically equals
boolean r3 = a == sameA;  // This is true, since a and sameA are really the same object

Last updated