7

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?

Gonen I
  • 5,576
  • 1
  • 29
  • 60
tech_questions
  • 263
  • 5
  • 14

2 Answers2

8

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.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Amit Bera
  • 7,075
  • 1
  • 19
  • 42
7

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.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268