Skip to content

Instantly share code, notes, and snippets.

@almibe
Created October 6, 2021 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save almibe/5c69270ee5ac932c7fc4b530467c4fe8 to your computer and use it in GitHub Desktop.
Save almibe/5c69270ee5ac932c7fc4b530467c4fe8 to your computer and use it in GitHub Desktop.
Java if statements vs if expressions
public class Test {
public static void main(String []args){
final var x = 5;
// You can do something like this in Kotlin/Scala etc but not Java
// final var t = if (x == 0) {
// "zero";
// } else if (x > 0) {
// "pos";
// } else {
// "neg";
// }
// If you chain ? : calls you can fake it but it's harder to read especially if you have more cases
final var t = x == 0 ? "zero" : x > 0 ? "pos" : "neg";
System.out.println(t);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment