Java Reference
In-Depth Information
Float and Double classes have an isNaN() method, which accepts a float and a double argument, respectively.
It returns true if the argument is NaN , Otherwise, it returns false . For example, to test if d1 is NaN , the above expression
can be rewritten as shown:
double d1 = Double.NaN;
// Assigns true to b. Correct way to test for a NaN value
b = Double.isNaN(d1);
You should not use == operator to test two strings for equality. For example,
String str1 = new String("Hello");
String str2 = new String("Hello");
boolean b;
b = (str1 == str2); // Assigns false to b
The new operator always creates a new object in memory. Therefore, str1 and str2 refer to two different objects
in memory and this is the reason that str1 == str2 evaluates to false . It is true that both String objects in memory
have the same text. Whenever == operator is used with reference variables, it always compares the references of the
objects its operands are referring to. To compare the text represented by the two String variables str1 and str2 , you
should use the equals() method of the String class, as shown:
// Assigns true to b because str1 and str2 have the same text of "Hello"
b = str1.equals(str2);
// Assigns true to b because str1 and str2 have the same text of "Hello"
b = str2.equals(str1);
I will discuss more about strings comparison in the chapter on Strings.
Inequality Operator (!=)
The inequality operator ( != ) is used in the form
operand1 != operand2
The inequality operator returns true if operand1 and operand2 are not equal. Otherwise, it returns false .
The rules for the data types of the operands of inequality ( != ) operator are the same that of equality operator ( == ).
int i = 15;
int j = 10;
int k = 15;
boolean b;
b = (i != j); // Assigns true to b
b = (i != k); // Assigns false to b
b = (true != true); // Assigns false to b
b = (true != false); // Assigns true to b
b = (false != true); // Assigns true to b
If either operand is NaN ( float or double ), inequality operator returns true . If d1 is a floating-point variable
( double or float ), d1 == d1 returns false and d1 != d1 returns true if and only if d1 is NaN .
 
Search WWH ::




Custom Search