Home Java javaTutorial Summary of the relationship between basic type and encapsulated type data and heap and stack in Java

Summary of the relationship between basic type and encapsulated type data and heap and stack in Java

Apr 25, 2017 am 09:56 AM

Java's heap is a runtime data area, from which class (objects allocate space. These objects are created through instructions such as new, newaray, anewarray and multianewarray, and they do not require program code to be explicitly released. The heap is composed of garbage The advantage of the heap is that it can dynamically allocate memory size, and the lifetime does not need to be told to the compiler in advance, because it dynamically allocates memory at runtime, and Java's garbage collector will automatically collect these no longer used Data. But the disadvantage is that due to the dynamic allocation of memory at runtime, the access speed is slower.

The advantage of the stack is that the access speed is faster than the heap, second only to the register, and the stack data can be shared. But the disadvantage is that the size and lifetime of the data stored in the stack must be determined, and there is a lack of flexibility. The stack mainly stores some basic types of variables (int, short, long, byte, float, double, boolean, char) and Object handle.

The stack has a very important special feature, that is, the data stored in the stack can be shared. Suppose we define at the same time:

int a = 3; 
int b = 3;
Copy after login

The compiler processes int a = 3 first. ; First, it will create a reference to the variable a in the stack, and then check whether there is a value of 3 in the stack. If it is not found, it will store 3 in, and then point a to 3; then process int b = 3; before creating. After finishing the reference variable of b, since there is already a value of 3 on the stack, b will be pointed directly to 3. In this way, a and b will both point to 3 at the same time.

At this time, if Let a=4; then the compiler will re-search whether there is a 4 value in the stack. If not, it will store 4 in and make a point to 4; if it already exists, it will directly point a to this address. Therefore, the value of a is. The change will not affect the value of b.

It should be noted that this kind of data sharing is different from the sharing of two objects' references pointing to one object at the same time, because in this case, the modification of a will not happen. Affecting b, it is done by the compiler, which helps save space. When an object reference variable modifies the internal state of this object, it will affect another object reference variable.

String is a special one. Packaging data. It can be created in two forms:

String str = new String("abc"); 
String str = "abc";
Copy after login

. The first one is to use new() to create a new object, which will be stored in the heap every time it is called. A new object will be created.
The second method is to first create an object reference variable str of the String class in the stack, and then check whether "abc" is stored in the stack. If not, store "abc". Push it onto the stack and make str point to "abc". If there is already "abc", directly make str point to "abc"

When comparing whether the values ​​in the class are equal, use the equals() method; when testing two. When the references of two package classes point to the same object, use ==. The following uses examples to illustrate the above theory.

String str1 = "abc"; 
String str2 = "abc";
Copy after login

System.out.println(str1==str2); //true
It can be seen that str1 and str2 point to the same object.

String str1 =new String ("abc"); 
String str2 =new String ("abc"); 
System.out.println(str1==str2); // false
Copy after login

Using new is to generate different objects. Generate one at a time.

Therefore, if you use the first method to create multiple "abc" strings, there is actually only one object in the memory. This way of writing is beneficial to saving memory space. At the same time, it can improve the performance of the program to a certain extent. Running speed, because the JVM will automatically determine whether it is necessary to create a new object based on the actual situation of the data in the stack. For the code of String str = new String("abc");, new objects are always created in the heap, regardless of whether their string values ​​are equal or whether it is necessary to create new objects, thus increasing the burden on the program.

On the other hand, please note: When we define a class using a format such as String str = "abc";, we always assume that the object str of the String class is created. Worry about traps! The object may not have been created! It may just point to a previously created object. Only through the new() method can we ensure that a new object is created every time.

Due to the immutable nature of the String class, when the String variable needs to frequently change its value, you should consider using the StringBuffer class to improve program efficiency. Java's heap is a runtime data area from which class objects allocate space. These objects are created through instructions such as new, newaray, anewarray, and multianewarray. They do not require program code to explicitly release. The heap is responsible for garbage collection. Yes, the advantage of the heap is that it can dynamically allocate memory size, and the lifetime does not need to be told to the compiler in advance, because it dynamically allocates memory at runtime, and Java's garbage collector will automatically collect the data that is no longer used. The disadvantage is that due to the need to dynamically allocate memory at runtime, the access speed is slow

/************************************************************************************************************************************************/

1. Data types in java: basic data types and references. Data type;

2. Although Java does not explain how memory is allocated when the program is running, usually Java developers or learners will divide the memory into three areas: stack space, heap Space, method area;

Heap area:

a. All objects are stored, and each object contains information about a corresponding class (the purpose of class is to obtain operation instructions. )

b.jvm只有一个堆区被所有线程共享,堆中不存放基本类型和对象引用,只存放对象本身

栈区:

a.每个线程包含一个栈区,栈中只保存基础数据类型的对象和自定义对象的引用(不是对象),对象都存放在堆区中

b.每个栈中的数据(原始类型和对象引用)都是私有的,其他栈不能访问。

c.栈分为3个部分:基本类型变量区、执行环境上下文、操作指令区(存放操作指令)。

方法区:

a.又叫静态区,跟堆一样,被所有的线程共享。方法区包含所有的class和static变量。

b.方法区中包含的都是在整个程序中永远唯一的元素,如class,static变量。字符串常量在方法区分配 ,数组既在栈空间分配数组名称, 又在堆空间分配数组实际的大小。

上面明白之后,接下来我们来分析 String str=new String("abc");

String str 是定义了一个String类型的变量,此时只定义了而没有创建对象,而new Sring(“abc”)到底做了什么?我们可以查看String的源码,发现如下:

public final class String
implements java.io.Serializable, Comparable, CharSequence
{
/** The value is used for character storage. */
private final char value[];
……

发现她有一个Value的属性,类型是char[],而此数组又做了什么事情?如果读源码会发现他保存了String对象的值,此时也说明String就是char[]来组织的。

当执行String a="abc";时,JAVA虚拟机会在栈中创建三个char型的值'a'、'b'和'c',然后在堆中创建一个String对象,它的值(value)是刚才在栈中创建的三个char型值组成的数组{'a','b','c'}对象,而这个新创建的String对象会被添加到字符串池中。

此时就存在了两个对象:一个在堆中;一个在字符串池中。

/**************************************************************************************************************************/

     String str1 = "abc";
   String str2 = new String("abc");
Copy after login

The above is the detailed content of Summary of the relationship between basic type and encapsulated type data and heap and stack in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles