The relational operator generates a "Boolean" (Boolean) result. They evaluate the relationship between the values of the arithmetic objects. If the relationship is true, the relationship expression generates true (True) and False (false) if the relationship is not true. Relational operators include less than (<), greater than (>), less than or equal to (<=), greater than or equal to (>=), equal to (= =), and not equal to (!=). equal to and not equal to all of the built-in data types, but other comparisons do not apply to Boolean types.
1. Check if objects are equal
relational operators = = and!= are also applicable to all objects, but their meaning usually makes it less likely for people in the first Java domain to find north. Here is an example:
: Equivalence.java public
class equivalence {public
static void Main (string[] args) {
Integer n1 = new inte GER (a);
Integer n2 = new Integer (a);
SYSTEM.OUT.PRINTLN (n1 = = n2);
System.out.println (N1!= n2);
}
///:~
The expression System.out.println (n1 = = n2) prints out the internal Boolean comparison results. The average person would think that the output must be true first, then false, since two integer objects are the same. But although the content of the object is the same, the handle is different, and = = and!= is just the object handle. So the output is actually first false and then true. This naturally surprises the first person in contact.
What if you want to compare the actual content of two objects to the same thing? At this point, you must use the Special method equals () that all objects apply to. But this method does not apply to "main type", those types directly use = = and!= can be. The following examples illustrate how to use:
: Equalsmethod.java public
class Equalsmethod {public
static void Main (string[] args) {
Integer n1 = new in Teger (a);
Integer n2 = new Integer (a);
System.out.println (N1.equals (N2));
}
///:~
As we expected, the result at this point is true. But that's not the end of it! Let's say you created your own class, like this:
: Equalsmethod2.java
class Value {
int i;
}
public class EqualsMethod2 {public
static void Main (string[] args) {
value V1 = new value ();
Value v2 = new value ();
v1.i = v2.i = m;
System.out.println (V1.equals (v2));
}
///:~
And then the results turned back to false!. This is because the default behavior of equals () is the comparison handle. So unless you change equals () in your new class, it's impossible to show the behavior we want. Unfortunately, the 7th chapter will not learn how to change behavior. But pay attention to this behavior of equals () and perhaps avoid some "catastrophic" events.
Most Java class libraries implement Equals (), so it actually compares the contents of objects, not their handles.