The Boolean (logical) data type boolean

Download Report

Transcript The Boolean (logical) data type boolean

The Boolean (logical) data
type boolean
Logical data type: boolean
• The boolean data type:
• is a built-in (primitive) data type of Java
• is used to represent the logical values
• There are 2 logical values:
• true
• false
Logical data type: boolean (cont.)
• Encoding scheme used in the boolean data type:
• 0 represents true
• 1 represents false
• uses 1 byte of memory (to store 0 or 1)
Boolean literals
• There are 2 boolean literals (= logical constants) in Java:
• true and,
• false
These 2 words are keywords (reserved words) in Java
Defining boolean typed variables
• Syntax to define an boolean typed variable:
• boolean NameOfVariable
;
• Notes:
•The keyword boolean announces the variable definition
clause
•The NameOfVariable is an identifier which is the name
of the variable.
•The variable definition clause is must be ended with a
semi-colon ";"
•A boolean typed variable can store true (1) or false (0)
Defining boolean typed variables (cont.)
• Example:
public class Boolean01
{
public static void main(String[] args)
{
boolean a;
// boolean typed variable
a = true;
System.out.println(a); // prints true
a = false;
System.out.println(a); // prints false
a = (3 > 1);
// 3 > 1 evals to true, so: a = true
System.out.println(a); // prints true
a = (3 <= 1);
// 3 <= 1 evals to false, so: a = false
System.out.println(a); // prints false
}
}
Defining boolean typed variables (cont.)
• Example Program: (Demo above code)
– Prog file:
http://mathcs.emory.edu/~cheung/Courses/170/Syllabus/06/Progs/
Boolean01.java
• How to run the program:
• Right click on link and save in a scratch directory
• To compile: javac Boolean01.java
• To run:
java Boolean01
Operations that return a boolean result
• There are 2 types of operators that return a boolean result
(true or false):
• Compare operators:
• A compare operator compares 2 numerical
expressions and return a Boolean result.
• Example:
• the compare operation 3 > 1 returns the
Boolean value true
Operations that return a boolean result
(cont.)
• Logical operators:
• A logical operator compares 2 Boolean
(logical) expressions and return a Boolean
result.
• Example:
• the logical operation true AND false
returns the Boolean value false
Operations that return a boolean result
(cont.)
• We will discuss the compare operators next and discuss the
logical operators after a few webpages.