Java Conditionals

Conditionals:

int myInteger = 4; if (myInteger < 3) { // Your code here }

- The code between the {} will only be activated if the specified condition is true, otherwise will be ignored

Alternative Conditionals:

int myInt = 4; if (myInt > 2) { // Your code here } else if (myInt < 0) { // Code for alternative condition } else { // Code to be executed if none of the specified conditions are met }

- You can have as many "else if" conditions as you want (or none)

Types of Conditions:

true !false // ! means "not" 3 == 3 // == checks if values are equal 3 != 4 // != checks if not equal 3 < 4 // < checks if value on left is less than value on right 3 > 2 // > checks if value on left is greater than value on right 3 <= 4 // <= means less than or equal to 3 >= 2 // >= means greater than or equal to !(3 == 4) // !() will negate the value within parenthesis 3 == 9 || 3 < 7 // || means OR, true if the conditions on EITHER side are true 3 > 2 && 3 < 5 // && means AND, true if the conditions on BOTH sides of it are true 3 > 2 && (3 > 5 || 6 > 2 || 1 < 4) // Complex combinations can be made

- All of the above examples have the value of true

Challenge

Write a program that stores an age as a variable; if it is less than 18, have it display "Must be 18 to pass"; if it is an invalid value (negative) have it say "Invalid input", otherwise have it say "Welcome!". Run it with different values for the age.

Quiz

Completed