Question interview in java

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

if(a == b) { 
  System.out.println ("TRUE"); 
} else {
 System.out.println ("FALSE"); 
}

I tried, and he printed FALSE, I want to know the exact reason.

Thanks in advance.

+3
source share
6 answers

He is typing FALSE.

The operator ==compares references to objects, aand bare links to two different objects, therefore FALSE.

Guido said:
In addition, the links are different because the lines are created using the new operator. If you create them as String a = "TEST"; String b = "TEST";, then the output will probably be TRUEbecause the JVM checks for the existence of the corresponding String object in the String pool that it stores, so the same object will be reused.

+14

FALSE. .equals() ==

String a = new String ("TEST");

String b = new String ("TEST");

if(a.equals(b)) { 
  s.o.p ("TRUE"); 
} else {
 s.o.p ("FALSE"); 
}
+1

, :

String a = new String ("TEST").intern();

String b = new String ("TEST").intern();

System.out.println(a == b);

true.

:

public static void main(String [] args) {
    // will return true
    System.out.println(compare("TEST", "TEST"));
}

public static boolean compare (String a, String b) {
    return a == b;
}
+1

( , ), , , .

, == true.

.

Object o = new Object();
Object p = o; //<-- assigning the same reference value
System.out.println("o == p ? " + (o == p ) ); //<-- true

:

Object a = new Object();
Object b = new Object();
System.out.println("o == p ? " + (o == p ) ); //<-- false

.

, :

String x = "hello";
String y = "hello";

System.out.println("x == y ? " + (x == y ) ); //<-- true

, , , .

( ), equals().

.

, intern(), , .

 String a = "world";
 String b = new String("world");
 String c = new String("world").intern();//<-- returns the reference value in the pool.


 System.out.println("a == b ? "  + (a==b) ); //<-- false
 System.out.println("b == c ? "  + (b==c) ); //<-- false
 System.out.println("a == c ? "  + (a==c) ); // true!
+1

String , ,

, u , . , true, , false

0

Here we use two new keywords. A new object is created for each new keyword.

The method ==checks the object of the hashcodeobject, in this case we get falseas the answer.

-1
source

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


All Articles