Java Ternary Without Assignment

Java Ternary without Assignment

Nope you cannot do that. The spec says so.

The conditional operator has three operand expressions. ? appears
between the first and second expressions, and : appears between the
second and third expressions.

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.

[EDIT]

Since you asked about reflection, here's a solution. I'm not recommending this. I'm posting it only because you asked.

public class MyCall
{

public void a(){System.out.println("a");}
public void b(){System.out.println("b");}

public static void main(String... args)
{
new MyCall().go();
}

public void go()
{
Class<? extends MyCall> class1 = this.getClass();
Method aMethod = class1.getMethod("b", null);
Method bMethod = class1.getMethod("a", null);
Object fake = false ? aMethod.invoke(this, null) : bMethod.invoke(this, null);
Object fake2 = true ? aMethod.invoke(this, null) : bMethod.invoke(this, null);
}
}

At the end of the day you've got to ask yourself if being succint improves your code's readability (think for-each loop). None of these solutions improve the code's readability IMHO. If I were you I'd rather go with this.

if(condition)
a();
else
b();

I'm actually for including braces even when loops only contain a single line, but since you're going after crisp code, the snippet above should do.

Why can't Ternary operator be used without assignment (variable on the left)?

The conditional operator is an expression: it has a result:

int a = cond ? 1 : 2;

but you can't use it like this:

cond ? 1 : 2;

because it's not a StatementExpression; this is much the same as the fact you can't write any of:

1;
2 * 3;
array[1];

because they just don't serve any purpose.

A StatementExpression is an expression that you can pop a ; after, for example:

int i = 0;        // (Not actually a StatementExpression - it's a LocalVariableDeclaration - just showing what i is)

someMethod(i++); // Use of i++ as an expression.
i++; // Use of i++ as a StatementExpression.

The full list of StatementExpressions can be found in the language spec:

StatementExpression:
Assignment
PreIncrementExpression
PreDecrementExpression
PostIncrementExpression
PostDecrementExpression
MethodInvocation
ClassInstanceCreationExpression

As such, you don't have to have an assignment: you can use the conditional operator in a contrived way such as this:

(true ? new int[1] : null)[0]++;

(Not that I am in any way advocating this as good code, or in any way useful; merely pointing out that it is legal)


As for the rest of your issues: these are just compiler-implementation-specific messages. Your compiler is tripping over the invalid syntax, and doing its best to help you, but it is not doing an especially good job.

Note that other compilers (e.g. the one used by Ideone) give totally different messages.

The first form should be written using an if/else:

if (stuff.equals ("TV")) res= "Walter" else res = "White" ;

(if is a statement, incidentally)

The second one is just missing some parentheses:

res = stuff.equals("TV")?(res="WALTER"):(res="WHITE");

Although the assignments in the second and third operands are redundant anyway:

res = stuff.equals("TV")?"WALTER":"WHITE";    

Can we write an ternary operator without a return value

Can i write a Ternary operator with return value as void

No, you can't.

The thing you can do is:

a = a<b ? a+b : a-b;

Or even:

a += a<b ? b : -b;

If without else ternary operator

No, you cannot do that.
Instead try this:

if(bool1 && bool2) voidFunc1();

Is there a ternary assignment operator in Java?

I disagree with all other answers. They require special functionality from specific versions by importing structures from the standard library, or obscure calls that works in this specific case, and all in all just hides the simplicity of what you're trying to do.

Keep it simple (KISS). Don't introduce more complexity and concepts when you don't need them. You're refactoring another developers code, which means this is a project where someone else will probably be reading your code later on. So keep it dead simple.

String name = xService.getName(xID);
xModel.setName(name != null ? name : "");

This is more readable than all other examples and doesn't require intimate knowledge of the standard library and its API.

Ternary operator is not a statement

this is not valid, you need to return a value

printFile() : throw new Exception("Error in creating file")

try this one

if(f.exists() || f.createNewFile()) {
printFile();
}else{
throw new Exception("Error in creating file");
}

Conditional ternary without else

You could create a class (or classes) that would create a nice fluent API. Such that your line would be:

calculationTo = replace(calculationTo).with(0).when(calculationTo < 1)

In my opinion it doesn't read much better than a standard if statement, but it also depends on the conditions that you have.

Example implementation:

public class Replacer<T> {

private final T value;
private T replacementValue;

private Replacer(T value) {
this.value = value;
}

public static <V> Replacer<V> replace(V value) {
return new Replacer<V>(value);
}

public Replacer<T> with (T replacementValue) {
this.replacementValue = replacementValue;
return this;
}

public T when(boolean condition) {
if (condition) {
return replacementValue;
} else {
return value;
}
}

}

import static somepackage.Replacer.replace;

public class Main {

public static void main(String[] args) {
int calculationTo = 3;

calculationTo = replace(calculationTo).with(0).when(calculationTo < 1);
}

}

You might expand it or make condition a function so it can be used with lambda, etc. I would also make method with return object of different class (e.g. ReplacerWithValue) so that calling with twice in one chain would result in compilation error.



Related Topics



Leave a reply



Submit