Thursday, July 4, 2013

[android help] logical operation in java


logical operation in java


android - logical operation in java - Stack Overflow







Tell me more ×

Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

















I have been trying to implement the following condition in a more sofisticated manner:



if (x > 1)
doSomething();
else {
doSomething();
}


want to code it like:



(x > 1) ? doSomething() : doSomething();


Is this not possible at all?


























Not possible if doSomething() returns void. Refer the JLS 15.25



The first expression must be of type boolean or Boolean, or a compile-time error occurs.


It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.


In fact, by the grammar of expression statements (§14.8), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.



P.S: Why you want to doSomething() for both true or false?























Not in full generality; the arguments in the ternary (formally the ternary requires expressions) have to evaluate to the same type.


If doSomething() is a void type then certainly not.






















It is dependent on return type.If you define like this void doSomething() then its not possible.






















No you can't. In JLS §14.8



ExpressionStatement:
StatementExpression ;

StatementExpression:
Assignment
PreIncrementExpression
PreDecrementExpression
PostIncrementExpression
PostDecrementExpression
MethodInvocation
ClassInstanceCreationExpression

Oops, no ConditionalExpression at all.






















The ternary is used for inline if conditions. They need a return value, because u could write something like that:



System.out.println((x > 1) ? "True" : "False");


with void this would not be possible




















lang-java






.

stackoverflow.comm



No comments:

Post a Comment

Google Voice on T-Mobile? [General]

Google Voice on T-Mobile? So I recently switched from a GNex on Verizon to a Moto X DE on T-Mobile. I had always used Google Voice for my v...