search
HomeJavajavaTutorialDetailed method analysis of the difference between ==, equals() and intern() in Java

This article mainly introduces the difference between the == operator and the equals method in Java and the relevant information on the detailed explanation of the intern method. Friends in need can refer to

The == operator and the equals method in Java The difference between equals method and detailed explanation of intern method

1. == operator and equals() method
2. Application of hashCode() method
3. intern() method

/* 
Come from xixifeng.com 
Author: 习习风(StellAah) 
*/ 
public class AboutString2  
{ 
  public static void main(String[]arsgs) 
  { 
    String myName="xixifeng.com"; 
    String myName3="xixifeng";  
    String myName4=".com"; 
    String myName5=myName3+myName4; 
    String myName6="xixifeng.com"; 
     
    if(myName==myName5) 
    { 
       
      System.out.println("myName==myName5"); 
    } 
    else 
    { 
      System.out.println("myName="+myName); 
      System.out.println("myName5="+myName5); 
      System.out.println("myName!=myName5"); 
    } 
    //经运行打印出: myName!=myName5 
     
    if(myName==myName6) 
    { 
      System.out.println("myName==myName6"); 
    } 
    else 
    { 
      System.out.println("myName!=myName6"); 
    } 
    //经运行得出: myName!=myName5,myName==myName6 
     
    //myName,myName5(myName5的值是由myName3+myName4得到的),myName6 这三个对象的值是相等的, 为什么 它们之间用==进行运算的结果是 myName!=myName5,myName==myName6呢? 
    //原因在于==运算符 
    //显然==参与String运算中不是用来比较值的,而是用来比较对象是否相等的. 
    //那么在String运算中,通过什么方法来比较它们的值是否相等呢,java 提供了equals()方法 ,主要用于比较对象的值是否相等 
    //示例如下: 
    //myName==myName5 是false (不是同一个对象) 
    if(myName.equals(myName5)) 
    { 
      System.out.println("myName.equals(myName5) 比较的结果是true !"); 
    } 
    else 
    { 
      System.out.println("myName.equals(myName5) 比较的结果是false !"); 
    } 
    //经运行输出:myName.equals(myName5) 比较的结果是true ! 在由于myName与myName5不是同一个对象,充分说明: 
    //equals()方法[是用来比较对象的值是否相等] 
     
    //再抛出疑问:是不是两个对象的哈希值相等就说明这两个对象相等呢? 
    //(由上述测试myName==myName5 得出false ①表明myName与myName5不是同一个对象) 
    System.out.println(myName.hashCode()); 
    System.out.println(myName5.hashCode()); 
    //经测试 ②myName与myName5的哈希值相等 
    //由①,② 得出: 两个对象的hashCode值相等,不能表明其对象也相等. 
 
    //抛出疑问: 怎样使myName与myName5的对象相等呢? 
    //引入intern()方法 
    myName5=myName5.intern(); 
    if(myName==myName5) 
    { 
       
      System.out.println("(myName==myName5) 得true"); 
    } 
    else 
    { 
      System.out.println("(myName==myName5) 得false"); 
    } 
    //经运行打印出: (myName==myName5) 得true 
    //结论: intern()方法能使两个(对象不相等而值相等的)对象变得相等 
    //myName5.intern();的意思,可以解释为: myName5在内存中查找对象嫁给自己,条件是,该对象要与自己的值相等. 找到了,就指定该对象. 
    //myName5找到对象,并认定,就不必再创建对象了,所以说这样做,可以节约内存资源. 
     
    //抛出疑问: 什么样的对象建议使用intern()呢? 
    // myName="xixifeng.com" myName6="xixifeng.com", myName与myName6的对象是相等的,上述已经证实. 
    // 所以说,对象在直接赋予同样的值的时候没有必要用intern(). 
    //myName="xixifeng.com" myName5=myName3+myName4,它们的值相等,但是对象不相等,上述已经证实. 
    //所以说, 对象在间接赋予(有可能与已有对象)同样的值的时候,建议用一下intern()方法,从而可公用内存中存在的对象. 
     
     
    //==参与int型运算中,也营造类似的比较 
    int i=8; 
    int j=3; 
    int k=5; 
    int m=j+k; 
    int n=8; 
    if(i==m) 
    { 
      System.out.println("i="+i); 
      System.out.println("m="+m); 
      System.out.println("i==m"); 
    } 
    else 
    { 
      System.out.println("i!=m"); 
    } 
     
    if(i==n) 
    { 
      System.out.println("... ... ... ..."); 
      System.out.println("i="+i); 
      System.out.println("n="+n); 
      System.out.println("i==n"); 
    } 
    else 
    { 
      System.out.println("i!=n"); 
    } 
    //经运行得出i=m(m的值由j+k得到),i=n 
    //i,m,n的值都相等 , 由于i==m 得出true i==n得出true  
    //所以可以得出结论: ==参与非对象类型运算时,是用来比较常量的值是否相等    
  } 
}

To sum up the above, we draw the following conclusions:

1) The == operator is used to compare whether the object is desirable when participating in object type operations.
2) = The = operator is used to compare whether the values ​​are equal when participating in non-object type operations.
3) The equals() method is used to compare whether the values ​​​​of two objects are equal.
4) The hashCode() value of the two objects Equality does not mean that the objects are also equal
5) The intern() method can make two objects (with unequal objects but equal values) equal, so that existing objects in the memory can be shared, which can save memory. Resources.
6) When an object is indirectly assigned the same value (possibly as an existing object), it is recommended to use the intern() method, so that the object existing in the memory can be shared.

The above is the detailed content of Detailed method analysis of the difference between ==, equals() and intern() in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Java Platform Independence: Differences between OSJava Platform Independence: Differences between OSMay 16, 2025 am 12:18 AM

There are subtle differences in Java's performance on different operating systems. 1) The JVM implementations are different, such as HotSpot and OpenJDK, which affect performance and garbage collection. 2) The file system structure and path separator are different, so it needs to be processed using the Java standard library. 3) Differential implementation of network protocols affects network performance. 4) The appearance and behavior of GUI components vary on different systems. By using standard libraries and virtual machine testing, the impact of these differences can be reduced and Java programs can be ensured to run smoothly.

Java's Best Features: From Object-Oriented Programming to SecurityJava's Best Features: From Object-Oriented Programming to SecurityMay 16, 2025 am 12:15 AM

Javaoffersrobustobject-orientedprogramming(OOP)andtop-notchsecurityfeatures.1)OOPinJavaincludesclasses,objects,inheritance,polymorphism,andencapsulation,enablingflexibleandmaintainablesystems.2)SecurityfeaturesincludetheJavaVirtualMachine(JVM)forsand

Best Features for Javascript vs JavaBest Features for Javascript vs JavaMay 16, 2025 am 12:13 AM

JavaScriptandJavahavedistinctstrengths:JavaScriptexcelsindynamictypingandasynchronousprogramming,whileJavaisrobustwithstrongOOPandtyping.1)JavaScript'sdynamicnatureallowsforrapiddevelopmentandprototyping,withasync/awaitfornon-blockingI/O.2)Java'sOOPf

Java Platform Independence: Benefits, Limitations, and ImplementationJava Platform Independence: Benefits, Limitations, and ImplementationMay 16, 2025 am 12:12 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM)andbytecode.1)TheJVMinterpretsbytecode,allowingthesamecodetorunonanyplatformwithaJVM.2)BytecodeiscompiledfromJavasourcecodeandisplatform-independent.However,limitationsincludepotentialp

Java: Platform Independence in the real wordJava: Platform Independence in the real wordMay 16, 2025 am 12:07 AM

Java'splatformindependencemeansapplicationscanrunonanyplatformwithaJVM,enabling"WriteOnce,RunAnywhere."However,challengesincludeJVMinconsistencies,libraryportability,andperformancevariations.Toaddressthese:1)Usecross-platformtestingtools,2)

JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool