If... (Conditionals)
Use if when you want to ask the computer a question. In Java, you use both parentheses () and braces {}.
Ask a question
int energy = 100;
if (energy > 50) {
System.out.println("I feel great!");
}
Translation:
Remember that energy is 100.
If (energy is greater than 50) {
print "I feel great!" and move to the next line;
}
The question goes inside (), and the actions go inside {}.
Otherwise? (else)
If the question is false, use else.
if (energy > 50) {
System.out.println("Feeling awesome!");
} else {
System.out.println("A bit sleepy...");
}
Translation:
Remember that energy is 100.
If (energy is greater than 50) {
print "Feeling awesome!" and move to the next line;
} otherwise {
print "A bit sleepy..." and move to the next line;
}
Ask multiple questions (else if)
If you have multiple situations, you can ask another question.
if (energy > 80) {
System.out.println("Overflowing with energy!");
} else if (energy > 40) {
System.out.println("Feeling okay.");
} else {
System.out.println("Too tired...");
}
Translation:
If (energy is greater than 80) { ... }
Otherwise, if (energy is greater than 40) { ... }
Otherwise { ... }
Recap
( )afterifis the question{ }is the block of actions- The question ends when the braces close
Now you have given Java the ability to make decisions.