Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Understanding Boolean Expressions and Operators in Java Programming - Prof. Kenrick J. Moc, Study notes of Computer Science

The concept of boolean expressions and operators in java programming. It covers the use of relational operators and boolean operators to create complex expressions. The document also discusses the importance of comparing floating point values for near equality and the precedence of common java operators. Additionally, it provides examples of if statements and the short-circuit evaluation in java.

Typology: Study notes

2009/2010

Uploaded on 03/28/2010

koofers-user-2p5
koofers-user-2p5 🇺🇸

3

(1)

10 documents

1 / 13

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
CS201, Mock
Boolean Conditions, If-Then
Boolean Expressions and Conditions
The physical order of a program is the order in which the statements are listed. The
logical order of a program is the order in which the statements are executed. With
conditional structures and control structures that we will examine soon, it is possible to
change the order in which statements are executed.
Boolean Data Type
To ask a question in a program, you make a statement. If your statement is true, the
answer to the question is yes. If your statement is not true, the answer to the question is
no. You make these statements in the form of Boolean expressions. A Boolean
expression asserts (states) that something is true. The assertion is evaluated and if it is
true, the Boolean expression is true. If the assertion is not true, the Boolean expression is
false.
In Java, data type boolean is used to represent Boolean data. Each boolean constant or
variable can contain one of two values: true or false.
Relational Operators
A Boolean expression can be a simple Boolean variable or constant or a more complex
expression involving one or more of the relational operators. Relational operators take
two operands and test for a relationship between them. The following table shows the
relational operators and the Java symbols that stand for them.
Java Symbol Relationship
== Equal to (not =)
!= Not equal to (since no key for ≠)
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
For example, the Boolean expression
number1 < number2
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Partial preview of the text

Download Understanding Boolean Expressions and Operators in Java Programming - Prof. Kenrick J. Moc and more Study notes Computer Science in PDF only on Docsity!

CS201, Mock Boolean Conditions, If-Then

Boolean Expressions and Conditions

The physical order of a program is the order in which the statements are listed. The logical order of a program is the order in which the statements are executed. With conditional structures and control structures that we will examine soon, it is possible to change the order in which statements are executed.

Boolean Data Type

To ask a question in a program, you make a statement. If your statement is true, the answer to the question is yes. If your statement is not true, the answer to the question is no. You make these statements in the form of Boolean expressions. A Boolean expression asserts (states) that something is true. The assertion is evaluated and if it is true, the Boolean expression is true. If the assertion is not true, the Boolean expression is false.

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

Relational Operators

A Boolean expression can be a simple Boolean variable or constant or a more complex expression involving one or more of the relational operators. Relational operators take two operands and test for a relationship between them. The following table shows the relational operators and the Java symbols that stand for them.

Java Symbol Relationship == Equal to (not =) != Not equal to (since no key for ≠) > Greater than < Less than >= Greater than or equal to <= Less than or equal to

For example, the Boolean expression

number1 < number

evaluates to true if the value stored in number1 is less than the value stored in number2 , and evaluated to false otherwise.

Examples:

boolean b; b = 3 < 1; System.out.println(b); // Outputs “false” b = 3 > 1; System.out.println(b); // Outputs “true”

When a relational operator is applied between variables of type char , the assertion is in terms of where the two operands fall in the collating sequence of a particular character set. For example,

character1 < character

is evaluated to true if the character stored in character1 comes before the character stored in character2 in the collating sequence of the machine on which the expression is being evaluated. Although the collating sequence varies among machines, you can think of it as being in alphabetic order. That is, A always comes before B and a always before b , but the relationship of A to a may vary. This is an artifact of the way the alphabet was defined in the ASCII code. For ASCII, it turns out the A < a.

boolean b; b = 'a' < 'b'; System.out.println(b); // Outputs “true”, ASCII a = 96, b = 97 b = 'a' < 'B'; System.out.println(b); // Outputs “false”, ASCII a = 96, B=

We must be careful when applying the relational operators to floating point operands, particularly equal ( == ) and not equal ( != ). Integer values can be represented exactly; floating point values with fractional parts often are not exact in the low-order decimal places. Therefore, you should compare floating point values for near equality. For now, do not compare floating point numbers for equality.

For example consider the program below:

class NumberTest { public static void main(String[] argv) throws Exception { float f = 1111111111; f = f + 1; System.out.println(f); } }

If relational operators and Boolean operators are combined in the same expression in Java, the Boolean operator NOT (! ) has the highest precedence, the relational operators have next higher precedence, and the Boolean operators AND ( && ) and OR ( || ) come last (in that order). Expressions in parentheses are always evaluated first.

For example, given the following expression ( stop is a bool variable)

count <= 10 && sum >= limit || !stop

!stop is evaluated first, the expressions involving the relational operators are evaluated next, the && is applied, and finally the || is applied. Java uses short-circuit evaluation. The evaluation is done in left-to-right order and halts as soon as the result is known. For example, in the above expression if both of the arithmetic expressions are true, the evaluation stops because the left operand to the OR operation ( || operator) is true. There is no reason to evaluate the rest of the expression: true OR anything is true. Short-circuit evaluation raises some subtleties that experienced programmers can take advantage of.

It is a good idea to use parenthesis to make your expressions more readable, e.g: (((count <=10) && (sum>=limit)) || (!stop)) This also helps avoid difficult-to-find errors if the programmer forgets the precedence rules.

The following table summarizes the precedence of some of the common Java operators:.

Operator Type Order of Evaluation ( )

[ ]

.

Parentheses

Array subscript

Member access

left to right

++ -- Prefix increment, decrement right to left ++ --

Postfix increment, decrement

Unary minus

right to left

  • / % Multiplicative left to right
    • Additive left to right < > <= >= Relational left to right == != Equality left to right && And left to right || Or left to right ? : Conditional right to left = += -= *= /= %= Assignment right to left

If-Then and If-Then-Else Statements

The If statement allows the programmer to change the logical order of a program; that is, make the order in which the statements are executed differ from the order in which they are listed in the program. The If-Then statement uses a Boolean expression to determine whether to execute a statement or to skip it. The format is as follows:

if (boolean_expression) statement;

The statement will be executed if the Boolean expression is true. If you wish to execute multiple statements, which is called a block , use curly braces:

if (boolean_expression) { statement1; statement2; … statement99; }

Although the curly braces are not needed when only a single statement is executed, some programmers always use curly braces to help avoid errors such as:

if (boolean_expression) statement1; statement2;

This is really the same as:

if (boolean_expression) statement1; statement2;

Such a condition commonly arises when initially only a single statement is desired, and then a programmer goes back and adds additional statements, forgetting to add curly braces.

We can also add an optional else or else if clause to an if statement. The else statement will be executed if all above statements are false. Use else if to test for multiple conditions:

There is a point of Java syntax that you should note: There is never a semicolon after the right brace of a block (compound statement).

Finally here is an example using else-if, also referred to as a nested if statement :

if (y==false) if (z < 50) { } else { …. }

There may be confusion as to what the final else statement goes to. Does it match up with z<50? or with y==false? The rule is that the else is paired with the most recent if statement that does not have an else. In this case, the final else statement is paired with (z < 50). The above is equivalent to:

if (y==false) { if (z < 50) { … } else { …. } }

If we wanted the else to match up with y==false, we should change the braces accordingly:

if (y==false) { if (z<5) { … } } else { … }

In nested If statements, there may be confusion as to which if an else belongs. In the absence of braces, the compiler pairs an else with the most recent if that doesn't have an else. You can override this pairing by enclosing the preceding if in braces to make the then clause of the outer If statement complete.

Compound Statements and Short Circuit

We can use relational operators to make more complicated if-then statements. Consider the following:

int i=0,j=2,k=4;

if (((k/j)<10) && ((k*j)<9)) { System.out.println ("foo"); } else { System.out.println ("bar"); }

This will evaluate 4/2 as being less than 10. Also 4*2 is less than 9. Consequently, “foo” should be printed.

Now consider the following:

int i=0,j=2,k=4;

if (((k/j)<10) || ((k*j)<9)) { System.out.println ("foo"); } else { System.out.println ("bar"); }

“foo” will still be printed. However, since we have a logical OR this means that we only need one of the top expressions to be evaluated to true. Java works left to right, so once it finds that k/j < 10 is true, it skips the (k*j)<9 expression. This helps save processing time and also lets us have potentially “invalid” expressions:

int i=0,j=2,k=4; if (((k/i)<10) || ((k*j)<9)) { System.out.println ("foo"); } else { System.out.println ("bar"); }

This will crash, resulting in a division by 0 error.

This code will also be flagged as an error by the compiler. i=1 does not return a Boolean, and we must make a Boolean comparison in the if-statement.

Fortunately, these common problems are discovered by the Java compiler. However, if you start to program in C or C++, these statements will not be flagged as errors by the compiler because they are valid statements. Unfortunately, they are probably not statements you wish to make and will likely result in a program that does not function correctly.

Common Bug #2: Using == with Strings and Objects

Fortunately, the compiler catches the previous bugs (unless the data types happen to be Boolean). Not so for the next common bug, using == with Strings. Although == correctly tests two values for primitive data types like numbers and chars, it has a different meaning when applied to objects.

First, let’s see how == works correctly on primitive data types. All variables are stored at some memory address. For variables of primitive data types, the value is stored directly in memory at that address. For example, say that we create two integers:

int x=1,y=1;

Let’s say that the compiler decides to place variable x at address 1000 and variable y at address 2000. A snapshot of memory looks something like this:

When Java executes x == y, the == operator checks to see if the contents of memory corresponding to variables x and y are the same. In this case, we compare 1 from address 1000 with 1 from address 2000, they are identical, and Java correctly returns the boolean value true.

Objects such as strings are stored differently, resulting in a different behavior when we use ==. An object really occupies a number of bytes of memory. These bytes store data associated with the object (e.g., a string of characters). The variable that represents the object is really storing the memory address where the data is stored.

Memory Address Contents

x

y

For example, say that we create a String object s1:

String s1 = “hi”, s2 = “hi”;

The variable s1 is also stored somewhere in memory, let’s say at address 1000. The variable s2 is also stored somewhere, let’s say at address 2000. The contents of the two object variables contains the memory address of the place where we are putting the object. Let’s say we have “hi” for s1 stored at address 3000, and “hi” for s2 stored at address 4000:

What happens now if we execute: s1 == s2? Java will do the same thing it did before: it compares the contents of s1 with the contents of s2. In this case, it is comparing 3000 with 4000. These are actually memory addresses, and they are different, so Java will return back the value false. In this case, the == operator isn’t smart enough to know that we actually want to go look at the data stored at the memory addresses and compare them instead.

Whenever we create variables for objects that actually store memory addresses, these variables are called references or pointers. Graphically, we can depict them a bit more conveniently using arrows and boxes:

Memory Address Contents

3000: h

3002: i

4000: h

4002: i

s

s

Using our hypothetical values from earlier, we now have a picture that looks like:

Both variables are now referring to the same location due to the assignment, so the program now prints out “Equal”. You might wonder why such behavior might be useful. This will become much more useful later on when we discuss linked data structures.

For now then, how do we compare strings to see if they are the same? We need to compare every character of each string to see if they match. Fortunately, there is already a string method defined that does this for us, called equals():

s1 = keyboard.readLine(); s2 = keyboard.readLine();

System.out.println("S1 = " + s1); System.out.println("S2 = " + s2); if (s1.equals(s2)) System.out.println("Equal"); else System.out.println("Not equal");

There is also a method called equalsIgnoreCase() that checks for equality but treats upper and lower case the same.

There is also a method called compareTo() that compares two strings and returns a number based on lexicographic ordering (i.e. if one is alphabetically greater than or less than the other). This will be useful later when we do things like sort lists of names.

Sample Exercises

Given an integer n with some value, determine if the number n is even or odd.

Given three numbers, a, b, and c, with some values in them, copy the largest of all three numbers into the variable "biggest"

Given a string variable s with some data in it, print out "A" if the first letter is an 'a' or 'A' and "Not A" otherwise.

Memory Contents

hi

s

s