Java exercise 04: How operators work?

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
Easy Exercises   For Beginners
Select    01   02   03   04   05   By title 

Here is a simple code using operators. To answer this quiz you need to understand the following operators(<=, > and &&), which are used in the code.

Read More: Java Operators

Java exercise 04: How operators work?

Level: Very easy

public class Discount
{
  public static void main(String[] args)
  {
    int age = 39;
    double discount = 5;
    if(age <= 20)
    {
      discount = 10;
    }
    else if(age > 20 && age <= 50)
    {
      discount = 15;
    }
    else
    {
      discount = 20;
    }
    System.out.print(discount);
  }
}
Author: Sar Maroof

What happens if the following code is compiled and run?

a. This program writes “5” to the standard output.
b. This program writes “10” to the standard output.
c. This program writes “15” to the standard output.
d. This program writes “20” to the standard output.

Answer explanation

  1. The first conditional statement “if(age <= 20)” checks whether the age is smaller or equal to 20. The age is 39 therefore this will return false and this block will not be executed.
  2. The second conditional statement is “if(age > 20 && age <= 50)” checks whether the age is greater than 20 and smaller or equal to 50. This one will be excuted, because the age is 39.
  3. The third else block will be ignored, because by else if statements, the program
    ignores the rest of the conditions as soon the first true statement is found.

The correct answer is: c.

Extra exercises: Change the value of the variable age to 12, 23, 44, 55 and run the program to test the results.

 





Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

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