I recently learned Java, and today I'm programming with a tricky question about judging whether two strings are equal. In programming, expressions that typically compare two strings for the same expression are "= =", but cannot be written in Java. In Java, Equals () is used;
String name = new String ("Sunzhiyan"); String age = New String ("Sunzhiyan"), if (name ==age) {System.out.print ("equal");} Else{system.out.print ("unequal");}
The output here is: Not equal, because new comes out will apply a different address, and the = = number is to compare their address (Java no pointer, assuming the address)
String name = "Sunzhiyan"; String age = "Sunzhiyan", if (name.equals (age)) {System.out.print ("equal");} Else{system.out.print ("unequal");}
This will be equal, because the Java default string is constant, that is, the address of A and B (Java without pointers, assuming addresses) consistent
and using
Attention:
Equals () compares the contents of the object (which distinguishes the case of letters), but is not equal if you compare two objects with "= =", compared to the memory addresses of two objects. Even though their contents are equal, the memory addresses of different objects are not the same.
The question of whether two strings are equal in Java