0

Java "Conditional Assignment"

Posted by Guillermo GarcĂ­a on 9:22 PM in , ,
We all know that an "assignment" is an expression that sets the value of a variable. But usually, the assignment expression may change, depending on a condition (boolean expression). For example:

String action, message;

action = "login";

if("login".equals(action)){
message = "login";
} else {
message = "Good bye!";
}

System.out.println(message);

In the code above, you can see the condition affecting the assignment expression of the variable "message" (the "action" changes the "message"). This is very usual in algorithms. So Java has a special operator that allows the simplification of this kind of "contitional assignment".

The operator is the "?" character, and you must see it as a short if, with the same behavior and features (if-else block, nested if, etc). So if you want to simplify the previous code, you can do this:

String action, message;

action = "login";

message = ("login".equals(action)) ? "Welcome" : "Good bye!";

System.out.println(message);

Using this, you will get the same behavior and a simplier code. Let's see a little explanation of this operator (a.k.a "Ternary operator"):

boolean expression ? returned value if "true" : returned value if "false";

NOTE: you can nest this operator (like the if), but your code may result very confusing.

0 Comments

Copyright © 2009 ggarciao.com
- Cup of Java -
All rights reserved.