Friday, 15 February 2013

if statement - Possibilities to short if-conditions in Java -


If I want to reduce it

  if (x) {x = false; } And {x = true; }  

I use the following code:

  x =! X;  

But what if I want to reduce this code? Is there a way to do that? if so, how?

  if (x) {method_1 (); } Other {method_2 (); }  

Can you use? : Statement

  x? Method_1 (): method_2 ()  

And sometimes, it is more readable to divide it into multiple lines:

  isSomethingTrue? Method_1 (): method_2 ()  

* Edit

To be accurate, as others have commented, you specify a return value in some variables Will happen. So the bit of code will actually look like this:

  someVar = isSomethingTrue? Method_1 (): method_2 ()  

means that you can not do it in invalid ways


No comments:

Post a Comment