Enable if statement?

I'm starting a little with coding, so someone please tell me if it is possible to do something like this in Java in the void result type?

switch (if this != null {return this;} else {return that;}) { case "This": blah break; case"That": blah break; } 

Also, can someone tell me the most efficient way to make a switch statement with two variables? Thank you :)

+5
source share
3 answers

Use the ternary operator :

 switch (this != null ? this : that) { ... } 

Or Optional class:

 switch (Optional.ofNullable(this).orElse(that)) { ... } 
+8
source

The simple answer is: do not do this. Because such code is difficult to read and maintain.

If at all, do something like

 switch(computeLookupValue(whatever)) 

But your idea of ​​doing so many things in a few lines of code is bad practice.

And then also forget this part about efficiency. In Java, you write efficient code by writing simple code that can only be optimized for a time compiler. Trying to write smart Java source code can quickly result in you not letting JIT do the work!

+3
source

You cannot do it if directly using if , but with a ternary operator:

 String str = null; String st = "foo"; switch (str != null ? str : st) { case "foo": System.out.println(st); } 
+2
source

Source: https://habr.com/ru/post/1274421/


All Articles