Skip to main content

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 to true 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 OperatorDefinitionExample
==Equals2==2 -> True, 2==4 -> False
!=Not Equal2!=3 -> True, 2!=2 -> False
>Larger3>2 -> True
<Smaller4 < 5 -> True
>=Larger or Equals4 >= 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.

πŸ’» Sample Program

Solve it here:​

✍ You can solve the problem here using Trinket