Can the ternary operator be used instead of simple if-else statement?
The ternary operator op1 ? op2 : op3 works just like a condensed if-else statement. If op1 is true, returns op2; otherwise, returns op3. Can we use the tenery operator anywhere that applies to an if-else statement?
The answer is no. Under some circumstances, we have to use the if-else statement. The following sample code is taken from Conditional Operator.com and a compile-time error will occurs:
class Program {
static void doSomethingX() { }
static void doSomethingY() { }
pubic static void main(String[] args) {
int x;
...
//the following line causes compile-time error
System.out.println((x==5)?doSomethingX():doSomethingY());
}
}
In 15.25 Conditional Operator (? :):
Note that it is a compile-time error for either the second or the third operand expression to be an invocation of a
voidmethod. In fact, it is not permitted for a conditional expression to appear in any context where an invocation of avoidmethod could appear.
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?