if Construct QuizS2C Home « if Construct Quiz

Fundamentals Quiz 11

The quiz below tests your knowledge of the material learnt in Fundamentals - Lesson 12 - if Construct Quiz.

Question 1 : What will be output from this code snippet?

boolean a = false;
if (a = true) {System.out.println("true");}
else {System.out.println("false");}
- The snippet will output <code>true</code>. This is because <code>if ( a = true)</code> actually assigns <code>true</code> to 'a'.<br><code>if ( a == true)</code> would check <code>a</code> for equality and return <code>false</code>.
Question 2 : When would we branch to else in a simple if...else construct?
- When the <code>if</code> condition returns <code>false</code> we branch to <code>else</code>.
Question 3 : How many operands does the ? : operator take?
- The <code>? :</code> operator is known as a <code>tenary</code> operator as it takes three operands.
Question 4 : What will be be the value of maxInt after this code snippet is run?

int int1 = 1234, int2 = 180, maxInt; maxInt = (int1 > int2) ? 111 : 222;
- <code>maxInt</code> will hold the value 111 as the result of <code>(int1 > int2)</code> is <code>true</code> and therefore 111 gets assigned.
Question 5 : What will be output from this code snippet?

int a = 20, b = 20; if (a & b) {System.out.println("Result was true");}
- This will not compile as the result of an <code>if</code> conditional expression must be a <code>boolean</code> and therefore requires use of a relation operator or logical operands. <br>In this case <code>(a & b)</code> returns an <code>int</code> from a bitwise operation.
Question 6 : When would we execute conditions in an else if in a multiple if....else construct?
- We would only execute conditions in an <code>else if</code> in a multiple <code>if....else</code> construct when the <code>else if</code> condition returns <code>true</code>.
Question 7 : Can we have multiple if constructs wihout an else?
- It is fine syntactically to have multiple <code>if</code> constructs wihout an <code>else</code>.
Question 8 : What will be be the value of maxInt after this code snippet is run?

int int1 = 1234, int2 = 5678, maxInt; maxInt = (int1 & int2) ? 111 : 222;
- <code>maxInt</code> will hold the value 222 as the result of <code>(int1 > int2)</code> is <code>false</code> and therefore 222 gets assigned.
Quiz Progress Bar Please select an answer


What's Next?

The next quiz on Java is all about Loop Statements.