Java exercise 05: Conditional & operators

  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 control statements and operators. To answer this quiz you need to understand how conditional statements work
in combination with the following operators(&&, ||, <=, ! and <), which are used in the code.

Read More: Java Operators
Read More: Java Conditional Statements

Java exercise 05: Conditional statements & opeators

Level: Very easy

What happens if the following code is compiled and run?

class Car
  public static void main(String[] args)
    int year = 2011;
    boolean isAutomatic = true;
    double price = 2500;
    if(isAutomatic && year < 2011)
      price = 4000;
    else if(!isAutomatic || year <= 2011)
      price = 3000;
      price = 5000;

a. This program writes “3000” to the standard output.
b. This program writes “5000” to the standard output.
c. This program writes “4000” to the standard output.
d. This program writes “2500” to the standard output.

Answer explanation

  1. The first conditional statement “if(isAutomatic && year < 2011)” checks first whether it is automatic, which is true and it checks also whether it is older than 2011, which is false. Therefore, it returns false.
  2. The second conditional statement “else if(!isAutomatic || year <= 2011)” checks first whether it is automatic. That return false because using the operator ! with a boolean variable represents its reverse value, but the second operand “year <= 2011” returns true. Therefore, the conditional statement returns true. That is because the operator || is used. The block is executed and the value of 3000 is assigned to the variable price.

The correct answer is: a.

Extra exercises: Change the value of the variable year to 2015, 2010 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