The if, else statement is used to check if something meets a condition, and if it does, great, but if it doesn’t, do something else.
- if(meetsCondition){
- // Have a party
- } else {
- // Be really, really sad
- }
The meetsCondition part is called a boolean, it’s either true or false. So you can read that code like this:
- if(true){
- // Have another party
- } else {
- // Why you always lying?
- }
So the // Have a party part would only be executed if the boolean in the if brackets is true. So if you had this:
- if(false){
- // Watch some Adventure Time
- } else {
- // Watch Green Lantern
- }
Since the boolean in the brackets is false, you’d have to watch Green Lantern.
Okay, but where do you get booleans from? Well a lot of the time you get booleans by comparing stuff. To compare stuff you use these:
- if(x == y) // If x is equal to y
- if(x != y) // If x is not equal to y
- if(x > y) // If x is greater than y
- if(x < y) // If x is less than y
- if(x >= y) // If x is greater than or equal to y
- if(x <= y) // If x is less than or equal to y
For example:
- int x = 0;
- if(x < 6) // Will return true cause 0 is less than 6
Or:
- String password = «foobar»;
- if(password.length > 6) // Will return false cause the length of the string is not greater than 6
So yeah if a statement meets your condition, do something about that, and if it doesn’t, do something else.