Java Conditionals
/*
Example 1:
If condition is not true, else is executed
*/
int x = 5; // variable x
if (x<4){ // the line of code within the if statement will not be executed as x is not less than 4
System.out.println("X is less than 4");
}
else { // the line of code within the else statement is executed because first condition is not true
System.out.println("X is greater than 4");
}
/*
Example 2:
If condition is true, else is not executed
*/
int x = 3; // variable x
if (x<4){ // the line of code within the if statement will be executed as x is less than 4
System.out.println("X is less than 4");
}
else { // the line of code within the else statement is not executed because first condition is true
System.out.println("X is greater than 4");
}
/*
Example 3:
If condition false, else if condition true. Else if code is executed
*/
int x = 2; // variable x
if (x<4 && x>3 ){ // the line of code within the if statement will not be executed, as x is not between 3 and 4
System.out.println("X is less than 4");
}
else if (x == 2){ // the line of code within the else if statement is executed as x is equal to 2
System.out.println("X is equal to 2");
}
else { // the line of code within the else statement is not executed because the previous condition is true
System.out.println("X is greater than 4");
}
// this is an if-else-else statement
String cheese = "Gouda";
if (cheese == "Cheddar"){ // tests if cheese = cheddar
System.out.println("Cheddar originated in Somerset");
}
else if (cheese == "Gouda"){ // tests if cheese = gouda
System.out.println("Gouda originated in the Netherlands");
}
else if (cheese == "Milk"){ // tests if cheese = milk
System.out.println("Milk is made from cows, goats, and other mammals");
}
else if (cheese == "Cheese"){ // tests if cheese = cheese
System.out.println("Cheese is very yummy");
}
else{ // if cheese is none of these
System.out.println("Sorry, I don't have any information about " + cheese);
}
//the statement above can also be written like:
String cheese = "Gouda";
switch(cheese) {
case "Cheddar": // tests if cheese = cheddar
System.out.println("Cheddar originated in Somerset");
break;
case "Gouda": // tests if cheese = gouda
System.out.println("Gouda originated in the Netherlands");
break;
case "Milk": // tests if cheese = milk
System.out.println("Milk is made from cows, goats, and other mammals");
break;
case "Cheese": // tests if cheese = cheese
System.out.println("Cheese is very yummy");
default: // if cheese is none of these
System.out.println("Sorry, I don't have any information about " + cheese);
}
boolean a = true;
boolean b = false;
if (!(a && b)){
System.out.println("!(true && false) is true");
}
else {
System.out.println("!(true && false) is false");
}