What is the difference between the constant and the heap regions in Java?

Asked 2 years ago, Updated 2 years ago, 110 views

If declared as below, it is stored in the constant area.

String str1 = "hello";
String str2 = "hello";

If you declare it as below, it will be stored in the heap area.

String str3 = new String("hello");
String str4 = new String("hello");

Is the constant area the same or the hip area different? What's the difference if it's different?

java memory

2022-09-22 08:57

2 Answers

If you create with new, it is created as an object in heap memory every time. However, in the case of the String, it is treated as literal if it is used without using new. String str1 = "hello"; String str2 = "hello"; If you used it like above, only one memory will go up.
but, String str3 = new String("hello"); String str4 = new String("hello");

When used in this way, two objects are raised on the heap.

Java doesn't manage memory directly, so it doesn't matter if you don't know the very deep part of the memory, but in a nutshell

There is a Runtime Data Area (the amount of memory allocated by the OS to run the program) and that space exists Class, stack, heap, native meshed, pc register area. Among them, constants are stored in the class area. The class area is also divided into several parts, where the constants are stored in the constant pool, which uses the existing constants when there are overlapping values.

For this reason, if you do not use new, only one hello will be in memory.


2022-09-22 08:57

In both cases, technically, the string itself is stored in a constant region. The difference is whether you make a direct reference or an indirect reference using a String object. For example...

It's like this. If you look at the picture in the link below, it will help you understand.

link


2022-09-22 08:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.