Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

Ternary Operator - JAVA


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, the ternary operator in Java acts like this...

return_value = (true-false condition) ? (if true expression) : (if false expression);

...Another way of looking at it...

return_value = (true-false condition) 
             ? (if true expression) 
             : (if false expression);

You question is kind of vague and we have to assume here.

  • If (and only if) callFunction(...) declares a non-void return value (Object, String, int, double, etc..) - it seems like it does not do that via your code - then you could do this...

    return_value = (string != null) 
                 ? (callFunction(...)) 
                 : (null);
    
  • If callFunction(...) does not return a value, then you cannot use the ternary operator! Simple as that. You will be using something that you don't need.

    • Please post more code to clear up any issues

Nonetheless, ternary operator should represent alternative assignments only!! Your code does not seem to do that, so you should not be doing that.

This is how they should work...

if (obj != null) {            // If-else statement

    retVal = obj.getValue();  // One alternative assignment for retVal

} else {

    retVal = "";              // Second alternative assignment for retVale

}

This can be converted to...

retVal = (obj != null)
       ? (obj.getValue())
       : ("");

Since it seems like you might be trying to just refactor this code to be a one-liner, I have added the following

Also, if your false-clause is truely empty, then you can do this...

if (string != null) {

    callFunction(...);

} // Take note that there is not false clause because it isn't needed

OR

if (string != null) callFunction(...);  // One-liner

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...