Java quiz 16: Ternary operator

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
< Java Quizzes    Green = Easy,  Blue = Normal,  Red = Hard
Select    01   02   03   04   05   06   07   08   09   10   11   12   13   14   15 
 16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   By title 
>

Here is an example that shows how the ternary operator works in Java.

Java quiz 16: Ternary operator

Level: easy

What is the output of this code?

public class MyClass
{
  public static void main(String[] args)
  {
    int x = 3;
    int y = (x < 3) ? 4 : 8;
    System.out.print(y);
  }
}
Author: Sar Maroof

Select the correct answer.


Answer explanation

  • The statement int y = (x < 3) ? 4 : 8; means
if(x < 3)
{
  y = 4;
}
else
{
  y = 8;
}
  • The statement if(x < 3) returns false, because x is equal to 3. Therefore, y = 8.

The correct answer is: b.





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 *