How to use If,Else Statements in Android Studio

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.

  1. if(meetsCondition){ 
  2. // Have a party 
  3. } else { 
  4. // 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:

  1. if(true){ 
  2. // Have another party 
  3. } else { 
  4. // 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:

  1. if(false){ 
  2. // Watch some Adventure Time 
  3. } else { 
  4. // 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:

  1. if(x == y) // If x is equal to y 
  2. if(x != y) // If x is not equal to y 
  3. if(x > y) // If x is greater than y 
  4. if(x < y) // If x is less than y 
  5. if(x >= y) // If x is greater than or equal to y 
  6. if(x <= y) // If x is less than or equal to y 

For example:

  1. int x = 0; 
  2. if(x < 6) // Will return true cause 0 is less than 6 

Or:

  1. String password = "foobar"; 
  2. 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.