Java Booleans
A description of Java booleans is provided with examples in an effort to meet educational purposes.
Syntax:
boolean variable_name = True/False;
Java Booleans – What are they?
It is common in programming to need a data type with only two valid values, such as:
- YES / NO
- ON / OFF
- TRUE / FALSE
Java has a boolean data type that can take either true or false values.
Boolean Values
A Java boolean type is declared with the boolean keyword and can take only true or false values:
public class Main {
public static void main(String[] args) {
boolean isJavaFun = true;
boolean isJavaHard = false;
System.out.println("Java is fun: "+isJavaFun);
System.out.println("Java is a difficult programming language: "+isJavaHard);
}
}
public class Main {
public static void main(String[] args) {
boolean earthIsRound = true;
boolean earthIsFlat = false;
System.out.println("Is Earth Round: "+earthIsRound);
System.out.println("Is Earth Flat: "+earthIsFlat);
}
}
When it comes to conditional testing, however, boolean expressions more commonly return boolean values
Boolean Expression
Boolean expressions are Java expressions that return true or false values.
To determine if an expression (or variable) is true, you can use a comparison operator, such as less than (<):
public class Main {
public static void main(String[] args) {
int mrx = 20;
int ample = 19;
System.out.println(mrx < ample); // returns false, because mrx is higher than ample
}
}
public class Main {
public static void main(String[] args) {
int mrx = 65;
int ample = 25;
System.out.println(ample < mrx); // returns true, because mrx is higher than ample
}
}
Additionally, you may try this:
public class Main {
public static void main(String[] args) {
System.out.println(9 < 14); // returns true, because 9 is less than 14
}
}
The equal to (==) operator is used to evaluate expressions in the following examples:
public class Main {
public static void main(String[] args) {
int mrx = 20;
int ample= 20;
System.out.println(mrx == ample);
// returns true, because the value of mrx is equal to that of ample
}
}
public class Main {
public static void main(String[] args) {
int ample_num = 11;
int mrx_num= 11;
System.out.println(ample_num == mrx_num);
// the outcome will come out as true as the value of ample_num is equal to mrx_num
}
}
The not equals to (!=) operator is used to evaluate expressions in the following examples:
public class Main {
public static void main(String[] args) {
System.out.println(25 != 10); // returns true, because 25 is not equal to 10
}
}
We can also compare two variables, to check whether both are equal or not:
public class Main {
public static void main(String[] args) {
int mrx=51;
int ample=74;System.out.println(mrx!=ample);
}
// Output : The result will come out as true because 51 is not equals to 74
}
All Java comparisons and conditions are based on the Boolean value of an expression.
In the next chapter, you will learn more about Java If-Else conditions.