News Ticker

if-then-else statements

The if condition must evaluate to a boolean. If it evaluates to a primitive type or String it will error.

Unusual loop/conditional constructions that ARE valid.

[sourcecode language=”java” toolbar=”false”]
for (int x = 0; x<5; x++)
if (true )
System. out .println(x);
[/sourcecode]

Exercise: What is the output of these code snippets:

[sourcecode language=”java” toolbar=”false”]
if (8 == 81) {}
if (true) {}
if (bool = false) {} //assume that bool is declared as a boolean
if (x == 10 ? true:false) { } // assume that x is an int
[/sourcecode]

Unusual loop/conditional constructions that ARE NOT valid.

[sourcecode language=”java” toolbar=”false”]
if (true) { break; }
[/sourcecode]

Cannot have break or continue in an ‘if‘ or ‘else‘ block.

[sourcecode language=”java” toolbar=”false”]
if (x = 3) {} // assume that x is an int
[/sourcecode]

Because the expression x = 3 does not return a boolean.

The ternary statement

[sourcecode language=”java” toolbar=”false”]
result = testCondition ? value1 : value2
^ ^
true false
[/sourcecode]

The ternary statement cannot have a void operator as the second and third:

[sourcecode language=”java” toolbar=”false”]
System.out.println( i<20 ? out1() : out2() );
[/sourcecode]

Assume that out1 and out2 have method signature:

  • public void out1(); and
  • public void out2();

This code snippet will not compile.

Type of the operation is ‘highest’ type of the second and third operands.

Leave a Reply