Condition is expression that must result in true/false. Code block can be any code.
if (YOUR-CONDITION) {
//your-code-for-true-result
}
else {
//your-code-for-false-result
}
Condition True
Here we hard-code the condition to true, so we print true!
if (true) {
prn("true!");
}
else {
prn("false!");
Condition False
Here we hard-code the condition to false, so we print false!
if (false) {
prn("true!");
}
else {
prn("false!");
Using Vars
We'll often use variable(s) in the condition like we do here
public void play(boolean isFun) {
if (isFun) {
prn("Yes fun");
}
else {
prn("Not so fun");
}
}
Using Logical Expression
Here we use a logical expression (evaluates to true/false)
public void logicPlay() {
int a=10, b=15;
//If a < b, print
if (a < b) {
prn("a is smaller");
}
else {
prn("a is equal or greater");
}
}
Using Logical Operator
Java uses && and || for logical AND and OR
public void logicPlay() {
int a=502, b=205;
//if a > 500 AND b < 300
if ((a > 500) && (b > 300)) {
prn("Both conditions true");
}
else {
prn("Both conditions NOT true");
}
}
With Proper Objects
We'll often use proper objects in both the condition and the code block
public void drawSquare(Rectangle rec, Graphics g, Color c) {
//If rec is a square, ask it to draw
if (rec.isSquare()) {
rec.draw(g, c);
}
else {
prn("Did not draw: " + rec.toString());
}
}
Introduction To Objects With Java
(Chapter 602 - Logic)