Java Reference
In-Depth Information
Conditional Expressions
if/else
if is similar to if as defined in other languages. First, a condition is evaluated
and if true, the expression block is evaluated. Otherwise, if an else expression
block is provided, that expression block is evaluated.
if (date == today) {
println("Date is today");
}else {
println("Out of date!!!");
}
One important feature of if / else is that each expression block may evaluate to
an expression that may be assigned to a variable:
var outOfDateMessage = if(date==today) "Date is today"
else "Out of Date";
Also the expression blocks can be more complex than simple expressions. List-
ing 3.7 shows a complex assignment using an if / else statement to assign the
value to outOfDateMessage .
Listing 3.7
Complex Assignment Using if/else Expression
var outOfDateMessage = if(date==today) {
var total = 0;
for(item in items) {
total += items.price;
}
totalPrice += total;
"Date is today";
} else {
errorFlag = true;
"Out of Date";
};
In the previous example, the last expression in the block, the error message string
literal, is the object that is assigned to the variable. This can be any JavaFX
Object, including numbers.
Because the if / else is an expression block, it can be used with another if / else
statement. For example:
 
 
Search WWH ::




Custom Search