This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
List<Object> myList = new ArrayList<>(); | |
//This line will throw an ERROR incompatible types required: boolean found: List<Object> | |
if(myList){//basically you need a boolean expression inside the if... | |
} | |
if(myList != null){//works fine because checking against null returns a boolean | |
//do stuff | |
} | |
//the one trick you can do, is to check for a truthy boolean | |
boolean bool = true; | |
if(bool){ | |
//this code will get run even without checking for (bool == true) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var x; | |
if(x){ | |
//this will not run because x is undefined, (kind of like null in Java) | |
} | |
x = null; | |
if(x){ | |
//this will not run because x is null, even though it is defined | |
} | |
x = true; | |
if(x){ | |
//this will run, because x is defined AND true | |
} | |
x = false; | |
if(x){ | |
//this will NOT run, because although x is defined, its value is still false | |
} |
This begs the question... Why can't the Java if be more like the JavaScript if? Thousands of checks for null could be removed if the Java if inherently checked for null when presented with a Object.
No comments:
Post a Comment