5

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
  • 4,956
  • 1
  • 21
  • 53
tech_questions
  • 243
  • 5
  • 13

2 Answers2

6

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.

YCF_L
  • 51,266
  • 13
  • 85
  • 129
Amit Bera
  • 6,855
  • 1
  • 16
  • 38
6

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
  • 76,639
  • 19
  • 130
  • 241