Last modified: January 07, 2023
Like JavaScript, logic can be achieved in Java via if
, else if
, and else
.
Examples:
// public static stuff omitted
boolean isCHSStudent = false;
boolean isLynbrookStudent = true;
if (isCHSStudent) {
System.out.println("Hello Pioneer!");
} else if (isLynbrookStudent) {
System.out.println("Hello Lynbrook!");
} else {
System.out.println("Hello!");
}
One trick is that when the code inside an IF ELSE statement is only one line, you can remove the brackets and condense them into the same line. The above example can be trimmed into:
if (isCHSStudent) System.out.println("Hello Pioneer!");
else if (isLynbrookStudent) System.out.println("Hello Lynbrook!");
else System.out.println("Hello!");
Like JavaScript, to compare two pieces of data, you can use:
syntax | name |
---|---|
== | equals |
!= | not equals |
a > b | a bigger |
a < b | a smaller |
a >= b | a bigger or equal |
a <= b | a smaller or equal |
The above comparison operators work perfectly fine on numeric data, such as double and integers.
However, they won't work on String. See the lesson on String for more information.
"NOT something" can be achieved via !
if (!isCHSStudent){
System.out.println("You are not a Pioneer :(");
}
One cool feature in Java is the Switch operator, which allows many == to be evaluted.
For example, we can convert the following...
// public static stuff omitted
int day = 1;
String dayName;
if (day == 1) {
dayName = "Monday";
} else if (day == 2) {
dayName = "Tuesday";
} else if (day == 3) {
...
else {
dayName = "this day does not exist";
}
... into something like this:
int day = 4;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break; // you need to add a break here, otherwise the switch statement will go on to evaluate the default value "this day does not exist"
case 2:
dayName = "Tuesday";
break;
...
default:
dayName = "this day does not exist";
}