Java Quizzes Green = Easy, Blue = Normal, Red = Hard Q01 Q02 Q03 Q04 Q05 Q06 Q07 Q08 Q09 Q10 Q11 Q12 Q13 Q14 Q15 Q16 Q17 Q18 Q19 Q20 Q21 Q22 Q23 Q24 Q25 Q26 Q27 Q28 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

### 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.

If you found this difficult, you might consider reading my book Java quizmaster for beginners. It is easy to understand, organized to learn Java in 17 days and it guides you to master Java code by solving 105 quizzes and 117 assignments. This book explains each chapter properly before starting with exercises and assignments. It is available on Amazon. See inside the book here!

Please, leave your questions, feedback and suggestions in the comments below!

SarMaroof.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes.

## Suggested Articles

## Books by Sar Maroof |

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