But the compiler (in WSAD 5.0.1) doesn't like this as a standalone statement.
x>y ? this.methodA():this.methodB();
It appears that some form of assignment of the result is needed yet I can't find any documentation that says this is the case! Am I missing something??
This is an expression and it can't stand alone. Try a simpler line of code like this:
and the compiler will reject it too. It doesn't really do anything (other than evaluate to some value), so it makes sense that the compiler should flag it. A command to the Java interperter (which is what a line of code is) must be a statement. Statements include things like assignments, flow control and method invocations.
Originally posted by Graham VMead: Hi Joe, Thanks for the reply,
I think I might be being pedantic and its not that important but I can see that
x+y; is obviously non-sensical
but
x>y?methodA():methodB();
is equivalent really to
if(x>y){ this.methodA(); }else{ this.methodB(); }
Which I would think is a very common logical construct and actually does achieve something sensible.
Graham
Yes, they do appear equivalent, however, the JVM treates them differently. In the case of the if statement, the JVM will execute a block of code depending on boolean condition. However, with the ternary operator ?, the JVM will assign a value to a variable, so the compiler will complain if there is no direct (or indirect via parameter-passing) assignment.
What i think it boils down to is that you can't do it because the language specification says you can't do it. If you read through the JLS (not a task i would neccesarily reccomend), it tells you exactly what can and can't be done. The trinary operator is something that can't stand alone - it must be part of something else. [ June 03, 2004: Message edited by: fred rosenberger ]
Never ascribe to malice that which can be adequately explained by stupidity.
Graham VMead
Ranch Hand
Joined: Sep 22, 2003
Posts: 154
posted
0
Thanks for the replies, its back to an if statement for me then
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.