CATEGORII DOCUMENTE |
Asp | Autocad | C | Dot net | Excel | Fox pro | Html | Java |
Linux | Mathcad | Photoshop | Php | Sql | Visual studio | Windows | Xml |
Relational operators generate a boolean result. They evaluate the relationship between the values of the operands. A relational expression produces true if the relationship is true, and false if the relationship is untrue. The relational operators are less than (<), greater than (>), less than or equal to (<=), greater than or equal to (>=), equivalent (==) and not equivalent ( ). Equivalence and nonequivalence works with all built-in data types, but the other comparisons won't work with type boolean.
The relational operators == and != also work with all objects, but their meaning often confuses the first-time Java programmer. Here's an example:
//: Equivalence.java
public class Equivalence
} ///:~
The expression System.out.println(n1 == n2) will print out the result of the boolean comparison within it. Surely the output should be true and then false, since both Integer objects are the same. But while the contents of the objects are the same, the handles are not the same and the operators == and != compare object handles. So the output is actually false and then true. Naturally, this surprises people at first.
What if you want to compare the actual contents of an object for equivalence? You must use the special method equals( ) that exists for all objects (not primitives, which work fine with == and !=). Here's how it's used:
//: EqualsMethod.java
public class EqualsMethod
} ///:~
The result will be true, as you would expect. Ah, but it's not as simple as that. If you create your own class, like this:
//: EqualsMethod2.java
class Value
public class EqualsMethod2
} ///:~
you're back to square one: the result is false. This is because the default behavior of equals( ) is to compare handles. So unless you override equals( ) in your new class you won't get the desired behavior. Unfortunately, you won't learn about overriding until Chapter 7, but being aware of the way equals( ) behaves might save you some grief in the meantime.
Most of the Java library classes implement equals( ) so that it compares the contents of objects instead of their handles.
Politica de confidentialitate | Termeni si conditii de utilizare |
Vizualizari: 710
Importanta:
Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved