Java Booleans: By: Milbert B. Bechayda

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 7

JAVA

BOOLEANS
BY: MILBERT B. BECHAYDA
Java Booleans

Very often, in programming, you will need a data type that can only have one of
two values like:
YES / NO
ON / OFF
TRUE / FASLE
For these, Java has a “Boolean” data type , which can take the values “true” or
“false”.
Boolean Values
A Boolean type is declared with “boolean” keyword and can only take the values
“true” or “false”.

Example:
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun); //Output is true
System.out.println(isFishTasty); //Output is false

However, its is more common to return boolean values from boolean expressions, for
conditional testing.
Boolean Values
A “Boolean Expression” is a Java expression that returns a Boolean value: “true”
or “false”.
You can use comparison operator, such as the greater that ( > ) operator to find
out if an expression or variable is true.
Example:
int x = 10;
int y = 9;
System.out.println(x > y); //returns true because 10 is higher than 9
Or even easier:
System.out.println(10 > 9); //returns true
Boolean Values
In the example below, we use the equal to ( == ) operator to evaluate an expression.
Example:
Int x = 10;
System.out.println( x == 10 ); //returns true because the value of x is equal to 10
System.out.println( 10 == 15); //returns false because 10 is not equal to 15
Strings with Boolean Result
Method name Description
string.equals(string) whether the two strings are identical
string.equalsIgnoreCase(string) whether the two strings are identical, ignoring
capitalization
string.startsWith(string) whether this string begins with the characters of the
given string
string.endsWith(string) whether this string ends with the characters of the
given string
string.contains(string) whether the characters of the given string occur
within this string
Exercise 1
Tell whether the output is “true” or “false” based on the declared variables.
int x = 12; int y = 7; int z = 28; String s = “mid term”;
1. X < 14;
2. !(x % 2 < 1)
3. x < y || x < z
4. z / x < x / y * x
5. s.length() == y
6. s.toUpperCase().equals("MID TERM")
7. !s.equals("mid term") || x * y != z
8. s.substring(z / x).length() > y

You might also like