Java Conditional Statements

 

Just like the decisions we make in life such as for example buying a car. If the car we are looking for is higher than our searching price then that car is too expensive and we won’t buy it. Else if the car is at our searching price or less we will buy it. In Java and programming in general, we use conditional statements to evaluate our decision.

We use the comparison operators to evaluate our condition.
1. Less than (x < y)
2. Less than or equal to (x <= y)
3. Greater than (x > y)
4. Greater than or equal to (x >= y)
5. Equal (x == y)
6. Not equal (x != y)

If - one if

if (condition) statement;

if (condition) {
  statement;
  statement;
}

 


It is recommended to use {} to specify where the block code ends. It is for readability.

if(10 > 5){
  System.out.println("10 is greater than 5");
}

(10 > 5) – condition
System.out.println(“10 is greater than 5”); – statement

If Else – one if else
if(condition){
        statement;
}else{
        statement;
}

if(5 < 10){
  System.out.println("5 is less than 10");
}else{
  System.out.println("10 is greater than 5");
}
If ElseIf ElseIf Else - multiple if else

if (condition1) {
     //block of code to execute if condition1 is true ;
}else if(condition2){
     //block of code to execute if condition2 is true ;
}else if(condition3){
     //block of code to execute if condition3 is true ;;
}else{
     //block of code to execute if none of the above conditions are true;
}

 

int age 30;
if(age < 19){
  System.out.println("You are a baby.");
} else if (age < 30){
  System.out.println("You are an adult.");
} else {
  System.out.println("You are old.");
}

Switch Statement
Switch statement provides better readability when they are too many if else statements.

String gender = "MALE";
switch(gender){
   case:"MALE";
   System.out.println("You are a man");
   break;
   case:"FEMALE";
   System.out.println("You are a woman");
   break;
   default:
   System.out.println("You are bisexual");
   break;
}

Notice a few key differences:

Arrow (->) vs. Colon (:): The new syntax uses -> for cases instead of :

Multiple Labels: Multiple case labels can be grouped together, separated by commas, as shown with MONDAY, FRIDAY, SUNDAY. No fallthrough: The new switch expression eliminates the notorious “fallthrough” behavior of the traditional switch statement, thus reducing errors.

Returning values: The switch expression returns a value, allowing it to be used in more expressive ways, like assigning a value to a variable. Yield for returning values in a block: If a case needs to execute a block of code, you can use yield to return a value from that block:

Benefits:

Readability: The code becomes concise and easier to understand.

 Safety: Avoids accidental fallthrough.

Expressiveness: Switch can now be used in more contexts due to its ability to return values.

 Considerations:

Always have a default case or cover all possible cases to ensure exhaustive handling.

When using the new switch expressions, always ensure that each case is exhaustive and handles all scenarios. The compiler will help in this by throwing an error if you’ve missed a case for a known set of inputs.

Remember that switch expressions were introduced in Java 12 as a preview feature. If you’re using a version prior to Java 14, you’ll need to enable preview features to use switch expressions. Starting from Java 14, they are a standard feature.

DayOfWeek dayOfWeek = DayOfWeek.WEDNESDAY;

        // you can return a value from the switch
        String dayType = switch (dayOfWeek) {
            case FRIDAY, SATURDAY, SUNDAY -> "End of week";
            case MONDAY, TUESDAY -> "Start of week";
            case WEDNESDAY, THURSDAY -> "Midweek";
            default -> throw new IllegalArgumentException("Invalid day");
        };

        System.out.println("dayType: " + dayType);

        Random random = new Random();
        int number = random.nextInt(1, 11);

        String message = switch (number) {
            case 1, 2, 3 -> "End of week";
            case 4, 5, 6 -> "Start of week";
            case 7, 8, 9 -> {
                /**
                 * if you want to execute lines of code, this is how to do it.
                 * 
                 * Yield for returning values in a block: If a case needs to execute a block of code, you can use yield
                 * to return a value from that block:
                 */
                String result = "Midweek";
                yield result; // 'yield' returns the value for this case
            }
            default -> "no idea";
        };

        System.out.println("number: " + number + ", message: " + message);

 

 

IF, IF ELSE, and ELSE

double amount = 0;

if(amount>0) {
    System.out.println("amount>0");
}else if(amount<0) {
    System.out.println("amount<0");
}else {
    System.out.println("amount=0");
}

// output
amount=0
double amount = -0.60;

if(amount < -0.50) {
    System.out.println("amount < -0.50");
}else {
    System.out.println("amount > -0.50");
}

//output
amount < -0.50

 

 




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *