Two class objects belong to the same memory cell?

I am starting to learn some Java, and I read a lot about how the memory is allocated by the JVM and therefore how this memory is freed using the garbage collector.

One thing that I could not figure out is to create two new objects that would be exactly the same if they all refer to the same place in memory? Similar to how String Pool works.

+4
source share
3 answers

One thing that I could not figure out is to create two new objects that would be exactly the same if they all refer to the same place in memory? Similar to how String Pool works

Answer No :

  • new, .
  • String. String, new, .
  • String - . String String. , String String .
  • Java , Integer. Integer a = 100; Integer b = 100; System.out.println(a==b); true, Integer -128 127 JVM. ( -128 127 JVM. JVM )
+7

new, , , . , (, factory), , , . Integer.valueOf(int), :

Integer a = Integer.valueOf(10);
Integer b = Integer.valueOf(10);
// a and b is the same object
Integer c = new Integer(10);
Integer d = new Integer(10);
// c and d are two distinct objects

, JVM , , , . , . , JVM , .

+2

, . ==, , .

String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2);

false, , String ( , ) == (ref ). () - equals(Object that).

-1
source

All Articles