Friday, February 4, 2011

Chapter 23: Relational Operators

Relational Operators are those that are used to identify the relationship between two parameters that are on either side of the operator. The exam covers six relational operators (<, <=, >, >=, ==, and !=). Relational operators always result in a boolean (true or false) value. This boolean value is most often used in an if test, as follows,

int x = 8;
if (x < 9) { // do something } but the resulting value can also be assigned directly to a boolean primitive: class TestRelOperators { public static void main(String [] args) { boolean b = 100 > 99;
System.out.println("The value of b is " + b);

Java has four relational operators that can be used to compare any combination of integers, floating-point numbers, or characters:
• > greater than

• >= greater than or equal to

• < less than

• <= less than or equal to

Let’s look at some legal comparisons:

class FindWhichAnimal {

public static void main(String[] args) {

String animal = "unknown";

int animalWeight = 700;

char sex = 'm';

double colorWaveLength = 1.630;

if (animalWeight >= 500) { animal = "elephant"; }

if (colorWaveLength > 1.621) { animal = "gray " + animal; }

if (sex <= 'f') { animal = "female " + animal; }

System.out.println("The animal is a " + animal);



In the preceding code, we are using a comparison between characters. It’s also legal to compare a character primitive with any number (though it isn’t great programming style). Running the preceding class will output the following:

The animal is a gray elephant

We mentioned that characters can be used in comparison operators. When comparing a character with a character, or a character with a number, Java will use the Unicode value of the character as the numerical value, for comparison.

“Equality” Operators

Java also has two relational operators (sometimes called “equality operators”) that compare two similar “things” and return a boolean the represents what’s true about the two “things” being equal. These operators are

• == equals (also known as “equal to”)

• != not equals (also known as “not equal to”)

Each individual comparison can involve two numbers (including char), two boolean values, or two object reference variables. You can’t compare incompatible types. There are four different types of things that can be tested:

• numbers

• characters

• boolean primitives

• Object reference variables

So what does == look at? The value in the variable — in other words, the bit pattern.

Equality for Primitives

Most programmers are familiar with comparing primitive values. The following code shows some equality tests on primitive variables:

class ComparePrimitiveValues {
public static void main(String[] args) {
System.out.println("char 'a' == 'a'? " + ('a' == 'a'));
System.out.println("char 'a' == 'b'? " + ('a' == 'b'));
System.out.println("5 != 6? " + (5 != 6));
System.out.println("5.0 == 5L? " + (5.0 == 5L));
System.out.println("true == false? " + (true == false));

This program produces the following output:
char 'a' == 'a'? true
char 'a' == 'b'? false
5 != 6? true
5.0 == 5L? true
true == false? false

As we can see, usually if a floating-point number is compared with an integer and the values are the same, the == operator returns true as expected.

Equality for Reference Variables

As we saw earlier, two reference variables can refer to the same object, as the following code snippet demonstrates:
JButton a = new JButton("Save");
JButton b = a;

After running this code, both variable a and variable b will refer to the same object (a JButton with the label Save). Reference variables can be tested to see if they refer to the same object by using the == operator. Remember, the == operator is looking at the bits in the variable, so for reference variables this means that if the bits in both reference variables are identical, then both refer to the same object. Look at the following example:

import javax.swing.JButton;
class CompareReferenceVariables {
public static void main(String[] args) {
JButton a = new JButton("Exit");
JButton b = new JButton("Exit");
JButton c = a;
System.out.println("Is reference a == b? " + (a == b));
System.out.println("Is reference a == c? " + (a == c));

This code creates three reference variables. The first two, a and b, are separate JButton objects that happen to have the same label. The third reference variable, c, is initialized to refer to the same object that a refers to. When this program runs, the following output is produced:

Is reference a == b? false
Is reference a == c? true

This shows us that a and c reference the same instance of a JButton. The == operator will not test whether two objects are “meaningfully equivalent,” a concept we’ll cover in much more detail in Chapter 7, when we look at the equals() method (as opposed to the equals operator we’re looking at here).

Exam Tip:
Don’t mistake = for == in a boolean expression. The following is legal:
1. boolean b = false;
2. if (b = true) { System.out.println("b is true");
3. } else { System.out.println("b is false"); }

Look carefully! You might be tempted to think the output is b is false but look at the boolean test in line 2. The boolean variable b is not being compared to true, it’s being set to true, so the println executes and we get b is true. The result of any assignment expression is the value of the variable following the assignment. This substitution of = for == works only with boolean variables, since the if test can be done only on boolean expressions. Thus, this does not compile:
4. int x = 1;
5. if (x = 0) { }

Because x is an integer (and not a boolean), the result of (x = 0) is 0 (the result of the assignment). Primitive ints cannot be used where a boolean value is expected, so the code in line 6 won’t work unless changed from an assignment (=) to an equality test (==) as follows:
6. if (x == 0) { }

Equality for Enums

Once you’ve declared an enum, it’s not expandable. At runtime, there’s no way to make additional enum constants. Of course, you can have as many variables as you’d like refer to a given enum constant, so it’s important to be able to compare two enum reference variables to see if they’re “equal”, i.e. do they refer to the same enum constant. You can use either the == operator or the equals() method to determine if two variables are referring to the same enum constant:

class CompareEnums {
enum Color {RED, BLUE} ;
public static void main(String[] args) {
Color c1 = Color.RED; Color c2 = Color.RED;
if(c1 == c2) { System.out.println("=="); }
if(c1.equals(c2)) { System.out.println("dot equals"); }
} }

(We know } } is ugly, we’re prepping you). This produces the output:
dot equals

As mentioned earlier, you can use both the “==” operator or the .equals() to compare two enums for equality.

Previous Chapter: Chapter 22 - Assignment Operators

Next Chapter: Chapter 24: InstanceOf Operator

No comments:

Post a Comment

© 2013 by All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.


Google+ Followers