Chapter 4a - Conditionals
Boolean Expressionβ
public class Main {
public static void main(String[] args) {
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun);
System.out.println(isFishTasty);
}
}
π§ͺ Try the code out~!
Practice
- Now you like fish: Change
isFishTasty
totrue
and see what happens.
Simple Comparison to get Boolean expressionsβ
class Main{
public static void main (String args[]){
int my_age = 21;
int age_marie = 25;
System.out.println("Am I older than Marie? " + (my_age < age_marie));
}
}
π§ͺ Try the code out~!
Comparison Operatorβ
== (equal to; example: x == 5)
!= (not equal to; example: x != 5)
> (greater than; example: y > 3)
< (less than; example: x < 5 )
>= (greater than or equal to; example: x >= y)
<= (less than or equal to; example: x <= y)
Comparison Operators
Comparison Operator | Definition | Example |
---|---|---|
== | Equals | 2==2 -> True, 2==4 -> False |
!= | Not Equal | 2!=3 -> True, 2!=2 -> False |
> | Larger | 3>2 -> True |
< | Smaller | 4 < 5 -> True |
>= | Larger or Equals | 4 >= 2 -> True, 2>=2 -> Tru |
Example Use
is_greater_than = 10 > 5 // True
In this case, 10 > 5 is a Boolean expression that evaluates to True because 10 is greater than 5
is_less_than = 10 < 5 // False
In this case, 10 < 5 is a Boolean expression that evaluates to False because 10 is not less than 5
class Main{
public static void main (String args[]){
//heights are in inches
//create variables for heights of the five friends
int ht_tom = 61;
int ht_marie = 53;
int ht_darell = 60;
int ht_alisha = 55;
int ht_joe = 66;
//boolean expression evaluates to True or False
System.out.println("Tom is of the same height as Marie: " + (ht_tom != ht_marie));
System.out.println("Tom is as tall as Marie or taller: " + (ht_tom >= ht_marie));
System.out.println("Darell is shorter or the same height as Joe: "+ (ht_darell <= ht_joe));
System.out.println("Alisha is shorter than Tom: " + (ht_alisha < ht_tom));
}
}
π§ͺ Try the code out!
Activityβ
Age Comparison
Write code that takes two values from the user, userβs age and his/her friendβs age. The code should compare the ages in this manner:
(i) if one is greater than the other.
(ii) if one is less than or equal to the other age.
(iii) if both the ages are equal. Ensure that the output shown is user friendly.