Docsity

Boolean Logic and Operators in Java: A Study Guide for CMPU-101 Students - Prof. Marc L. S, Study notes of Computer Science

Toggle sidebar
bg1
Chapter 8
boolean
CMPU-101: Problem-Solving and Abstraction
Marc Smith
Vassar College
Spring 2007
2
Up Until Now …
George Boole (1815-1864)
logic — true, false
Order of presentation:
literals
relational operators
logical operators
3
boolean Literals
true
false
System.out.println(true);
boolean b = false;
System.out.println(b);
4
Relational Operators
< less than
<= less than or equal
== equal
!= not equal
>= greater than or equal
> greater than
5
Prog0801
System.out.print("\nEnter int 1: ");
int i1 = kb.nextInt();
System.out.print("Enter int 2: ");
int i2 = kb.nextInt();
System.out.println("\ni1 == i2? " + (i1 == i2));
System.out.println("\ni1 < i2? " + (i1 < i2));
6
Watch Out for Precedence
Suppose i1 is 17 and i2 is 99:
System.out.println("\ni1 == i2? " + i1 == i2);
System.out.println("\ni1 == i2? 17" == i2);
Error!
+ is done before ==.
pf3
pf4

Partial preview of the text

Download Boolean Logic and Operators in Java: A Study Guide for CMPU-101 Students - Prof. Marc L. S and more Study notes Computer Science in PDF only on Docsity!

Chapter 8

boolean

CMPU-101: Problem-Solving and Abstraction Marc Smith Vassar College Spring 2007 2

Up Until Now …

George Boole (1815-1864)

logic — true, false

Order of presentation: literals relational operators logical operators 3

boolean Literals

true false System.out.println(true); boolean b = false; System.out.println(b); 4

Relational Operators

< less than <= less than or equal == equal != not equal

= greater than or equal greater than

Prog 0801

System.out.print("\nEnter int 1 : "); int i1 = kb.nextInt(); System.out.print("Enter int 2 : "); int i2 = kb.nextInt(); System.out.println("\ni1 == i2? " + (i1 == i2)); System.out.println("\ni1 < i2? " + (i1 < i2));

Watch Out for Precedence

Suppose i 1 is 17 and i 2 is 99 : System.out.println("\ni1 == i2? " + i1 == i2); System.out.println("\ni1 == i2? 17" == i2); Error!

  • is done before ==.

7

Logical Operators

and && or || not! These are defined by truth tables. 8

Logical And

false false false false true false true false false true true true x y x && y 9

Logical Or

false false false false true true true false true true true true x y x || y 10

Logical Negation

false true true false x !x

Operators We've Learned

arithmetic operators + , - , ***** , / , % relational operators <= , < , == , != , >= , > logical operators && , || ,!

Precedence

Predicates for Later

public static boolean isPrime ( int n ) public static boolean isPalindrome ( String s )

Short-Circuiting

Also known as lazy evaluation Java only evaluates what it has to evaluate. false && booleanExpression booleanExpression is not evaluated. true || booleanExpression booleanExpression is not evaluated.