CodeGym /Courses /Java Syntax Zero /Nuances of working with a conditional statement

Nuances of working with a conditional statement

Java Syntax Zero
Level 3 , Lesson 4
Available

1. Sequence of if statements

Sometimes a program needs to perform many different actions depending on the value of a variable or the value of an expression.

Let's say our task is something like this:

  • If the temperature is greater than 20 degrees, then put on a shirt
  • If the temperature is greater than 10 degrees and less than (or equal to) 20, then put on a sweater
  • If the temperature is greater than 0 degrees and less than (or equal to) 10, then put on a raincoat
  • If the temperature is less than 0 degrees, then put on a coat.

Here's how this can be represented in code:

int temperature = 9;

if (temperature > 20)
   System.out.println("put on a shirt");
else // Here the temperature is less than (or equal to) 20
{
   if (temperature > 10)
      System.out.println("put on a sweater");
   else // Here the temperature is less than (or equal to) 10
   {
      if (temperature > 0)
         System.out.println("put on a raincoat");
      else // Here the temperature is less than 0
         System.out.println("put on a coat");
   }
}

If-else statements can be nested within one another. This makes it possible to implement rather complex logic in a program.

But the above example is also interesting in that we can make the code a little simpler by omitting the curly braces:

int temperature = 9;

if (temperature > 20)
   System.out.println("put on a shirt");
else // Here the temperature is less than (or equal to) 20
   if (temperature > 10)
      System.out.println("put on a sweater");
   else // Here the temperature is less than (or equal to) 10
      if (temperature > 0)
         System.out.println("put on a raincoat");
      else // Here the temperature is less than 0
         System.out.println("put on a coat");

However, programmers usually write this construct a little differently:

int temperature = 9;

if (temperature > 20)
   System.out.println("put on a shirt");
else if (temperature > 10) // Here the temperature is less than (or equal to) 20
   System.out.println("put on a sweater");
else if (temperature > 0) // Here the temperature is less than (or equal to) 10
   System.out.println("put on a raincoat");
else // Here the temperature is less than 0
   System.out.println("put on a coat");

All three of these examples are equivalent.


2. Nuances of the else block

An important point:

If don't use curly braces in an if-else construct, then the else refers to the closest previous if.

Example:

Our code How will it work
int age = 65;

if (age < 60)
   if (age > 20)
      System.out.println("You must work");
else
   System.out.println("You don't have to work");
int age = 65;

if (age < 60)
{
   if (age > 20)
     System.out.println("You must work");
   else
     System.out.println("You don't have to work");
}

If you look at the code on the left, it seems that the screen output will be "You don't have to work". But that isn't the case. In reality, the else block and the "You don't have to work" statement are associated with the second (the closer) if statement.

In the code on the right, the associated if and else are highlighted in red. Additionally, the curly braces are placed unambiguously, clearly showing what actions will be performed. Is the string You don't have to work never displayed when age is greater than 60?


3
Task
New Java Syntax, level 3, lesson 4
Locked
This age doesn't work for me…
Think about what the program is doing. Fix the programming error so that person.age changes value. Hint: carefully review the adjustAge method

3. Example of using an if-else statement

Since we explored the if-else statement so well, let's give an example:

import java.util.Scanner;
public class Solution {
   public static void main(String[] args)
   {
     Scanner console = new Scanner(System.in); // Create a Scanner object
     int a = console.nextInt(); // Read the first number from the keyboard
     int b = console.nextInt(); // Read the second number from the keyboard
     if (a < b)                   // If a is less than b
       System.out.println(a);     // we display a
     else                         // otherwise
       System.out.println(b);     // we display b
   }
}
Displaying the minimum of two numbers

3
Task
New Java Syntax, level 3, lesson 4
Locked
Price of apples
Calculate the total cost of apples. The total cost of apples corresponds to public static int applePrice.
Comments (7)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Timurlan Level 3, Russian Federation
2 August 2023
That's cool
Abe Level 13, los angeles, United States
15 January 2023
The example and the explanation under section 2 "Nuances of the else block" make no sense at all? I tried running both codes and got no output so what gives? what was supposed to be the output and why??
Rene Level 28, Netherlands
23 October 2023
The block on the left sets the age on 65. The next statement (if age < 60) will do nothing as the age is currently 65. So it wont proceed to the next if-statement (if age > 20). And the else below that belongs to the closest if (if age > 20) because there is no curly braces. So any age from 60 and above will completely skip the if with all that follows. The block on the right shows the same code as on the left, but more readable with curly braces (and better indention). Same thing happens as above on execution.
Gummy C Level 11, United States of America, United States
12 December 2022
if (age < 18){ if (age >= 6) System.out.println("Off to school with you, my child"); }else System.out.println("Your college class starts soon"); } So, just want to make sure I am understanding this bit of code. Because age =5, it will run the second if statement, and check to see if age is greater than 5. Since it is not, it doesn't return anything. The else is only associated with the first "if" statement. The else will only run, if the first "if" statement is false. Am I right about that? Thank you so much for answering
Anonymous #11225109 Level 5, United States of America, United States
30 December 2022
Hi Gummy....all values are less than 18...the key , i think, is how to cancel all statements and not print out anything. So to do that is to get else statement closer to if statement...so the college thing is not anymore related to 18, but to >=6...so 5 is less than >=6, and there's not else statement for <6.
Hiyo Level 24
12 January 2023
Yes you are right. Since "age = 5", "if (age < 18) block executes and we go into that "if" scope. Since "age >= 6" is false, it ends there with no print. In other words, "Your college class starts soon" only prints if age is below 18. "Off to school with you, my child" only prints if age is within the range 6 ( inclusive ) to 17 ( inclusive )
Anonymous#222 Level 3, Canada
23 November 2022
HI