Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator gives "Not a statement" error [duplicate]

Tags:

java

Hi below statement throws error . It says "Not a statement"

map.containsKey(1)? someObject.setFlag(true) : map.put(1,"hello");

Is it needed to store the returned value in some variable on the left hand side of the statement?

like image 400
tech_questions Avatar asked Jul 05 '18 17:07

tech_questions


Video Answer


2 Answers

You are using the Ternary operator as a statement, not an assignment. In your case, you should use if else

if(map.containsKey(1)) {
    someObject.setFlag(true)
}else{
    map.put(1,"hello");
}

Here is the java docs of Ternary operator.

like image 123
Amit Bera Avatar answered Sep 20 '22 15:09

Amit Bera


The ternary operator is an expression, not a statement. It is commonly used to set the value of a variable depending on some condition. In this case, you need to assign the result to a variable in order to make it into a statement:

String result = map.containsKey(1) ? someObject.setFlag(true) : map.put(1,"hello");

(Note: You should choose a better variable name.)

I think you will still have problems here because setFlag() probably doesn't return a String. Also, since you are creating side effects, you should replace this with an if statement.

like image 34
Code-Apprentice Avatar answered Sep 19 '22 15:09

Code-Apprentice