== on String in Java is not as expected?

Possible Duplicate:
Equal Row Versus Equal Location

I just got my first evaluated coursework with a mark of 97.14%, and the comment "When comparing strings you need to use the .equals () String == method, does not work as you might expect."

How does == work on Strings, and if so, why do my tests all work correctly?

+3
source share
8 answers

You're lucky. "==" compares two objects to see which memory address they are referencing. This has nothing to do with what is actually in the string.

, , (?) .

String a = "abc";
String b = "abc";

(a == b) true. ,

String a = new String("abc");
String b = new String("abc");

(a == b) true.

+14

, == , , . . .equals() , .

: reference value.

( , ): http://leepoint.net/notes-java/data/expressions/22compareobjects.html

+5

==, Java , . , , .

. .

+2
class test{
public static void main(String[] args)
{
String a =new String("ABC");
String b =new String("ABC");
System.out.println(a==b); //prints False
System.out.println(a.equals(b)); //prints true
}
}
+1

Java : .

, float .. == , . , ==, , , , .

, ; == . equals(), .

, Java - , , . , , , , 3.add(4). , , , -, Integer. , autoboxing. , int ArrayList, autoboxing int , ArrayList ; Java 5.

+1

, . Operator == , equals() . .

, . java C. , C.

, 97. 25. 27.:)

+1

== , true, .

equals(Object) ( Object) ==, , .

String , (, , JVM ), , , String, , String.

:

String a = "xxx";
String b = "xxx";

System.out.println(a == b);  // usually "true"

"true", "xxx" , a b . , a b , , .

0

:

String a = new String("foo");
String b = new String("foo");

if(a == b) {
  // Does not execute
}

if(a.equals(b)) {
  // Executes
}

// Now make a reference the same memory location as b
a = b;

if(a == b && a.equals(b)) {
  // Executes
}

, , . , . ...

"==" . , - . "" - "", . , "==" [So Bob == father].

". equals" is true when you compare similar objects. So, if you just bought a 2008 Honda Accord, and your friend just bought a 2008 Honda Accord, you would say that you both have the same car. Despite this, they are NOT the EXACT same car [So yourCar.equals (yourFriendsCar)]. This changes a lot because a programmer can decide what makes two objects the same.

0
source

Source: https://habr.com/ru/post/1776533/


All Articles