Home >Java >javaTutorial >Detailed explanation of examples of relational operators in Java
This article mainly introduces the relational operators in Java programming, and also gives a brief introduction to the comparison class. Friends who need it can refer to it
In the process of Java programming, we often encounter To compare basic types or the size relationship between objects, let's take a look at how to compare. The source code is as follows:
package object; class Value{ int i; } public class E08_StaticTest { public static void main(String[] args) { Integer n1= new Integer(47); Integer n2= new Integer(47); int n3=12; int n4=12; System.out.println(n1==n2);//比较的是对象的引用而非对象的内容 System.out.println(n1!=n2); System.out.println(n3==n4); System.out.println(n3!=n4); System.out.println(n1.equals(n2)); Value n5=new Value(); Value n6=new Value(); n5.i=n6.i=67; System.out.println(n5.equals(n6));//比较的是对象的引用而非对象的内容 } }
Output result:
false true true false true false
When comparing basic types, such as int, double (n3 ,n4) etc. Use ==,! =Compare the size between the two; but for new objects (n1, n2), the equals() method must be used to compare the size relationship between the two objects.
For classes (n5, n6) created by users themselves, the equals() method must be overloaded when comparing size relationships. This is because the default behavior of the equals() method is to compare references, not comparisons. The contents of the object.
Most Java class libraries implement the equals() method so that it can be used to compare the contents of objects instead of comparing object references.
Summarize
The above is the detailed content of Detailed explanation of examples of relational operators in Java. For more information, please follow other related articles on the PHP Chinese website!