Home Java JavaBase The difference between heap and stack java

The difference between heap and stack java

Nov 13, 2019 pm 02:32 PM
java the difference stack

The difference between heap and stack java

The difference between heap and stack java

Before talking about heap and stack, let’s talk about JVM (virtual Machine) memory division:

Java programs must allocate space when they are running. Any software must allocate space in the memory when they are running. The Java virtual machine also must allocate space when it is running. The JVM opens up a memory area in the memory when it is running, and divides it more carefully in its own memory area when it starts. Because each piece of memory in the virtual machine is processed in a different way, it must be managed separately.

The JVM memory is divided into five parts:

1. Register;

2. Local method area;

3. Method area;

4. Stack memory;

5. Heap memory.

Let’s focus on the heap and stack:

Stack memory: Stack memory is first of all a memory area, which stores local variables, all defined in methods All are local variables (global variables outside the method). Local variables are also defined inside the for loop. The function must be loaded first before local variables can be defined. Therefore, the method first stacks the stack and then defines the variables. The variables have their own scope. , the variable will be released once it leaves the scope. The stack memory is updated very quickly because the life cycle of local variables is very short.

Heap memory: stores arrays and objects (in fact, arrays are objects). Everything created by new is in the heap. Entities (objects) are stored in the heap. Entities are used to encapsulate data, and It encapsulates multiple (multiple attributes of an entity). If one piece of data disappears, the entity does not disappear and can still be used, so the heap will not be released at any time, but the stack is different. The stack stores only a single variable. Once the variable is released, it is gone. Although the entities in the heap will not be released, they will be treated as garbage. Java has a garbage collection mechanism to collect them from time to time.

Let’s talk about the heap and stack in detail through an illustration:

For example, the statement in the main function int [] arr=new int [3]; in memory How it is defined:

The main function goes to the stack first, defines a variable arr in the stack, and then assigns a value to arr, but the right side is not a specific value, but an entity. The entity is created in the heap. First, a space is opened in the heap through the new keyword. When the memory stores data, it is reflected by the address. The address is a continuous binary, and then a memory address is allocated to the entity. Arrays have an index. After the array entity is generated in the heap memory, each space will be initialized by default (this is a characteristic of heap memory. Uninitialized data cannot be used, but it can be used in the heap. Because it has been initialized but not on the stack), different types have different initialized values. So variables and entities are created in the heap and stack:

The difference between heap and stack java

So how are the heap and stack connected?

We just said that we allocate an address to the heap, assign the address of the heap to arr, and arr points to the array through the address. So when arr wants to manipulate the array, it uses the address instead of assigning entities to it directly. We no longer call this a basic data type, but a reference data type. It is called arr and refers to the entity in the heap memory. (Can be understood as a pointer to c or c. Java grew up from c and is very similar to c, optimizing c)

The difference between heap and stack java

If when int [] arr=null;

arr does not point to anything, and the function of null is to dereference the pointer of the data type.

When an entity is not pointed to by a reference data type, it will not be released in the heap memory, but will be treated as garbage and automatically recycled at an irregular time, because Java has an automatic recycling mechanism. , (while c does not, the programmer needs to manually recycle. If it is not recycled, the heap will grow until it is full and the memory overflows, so Java is better than c in memory management). The automatic recycling mechanism (program) automatically monitors whether there is garbage in the heap. If there is garbage, it will automatically perform garbage collection, but it is not certain when it will be collected.

So the difference between heap and stack is obvious:

1. Stack memory stores local variables while heap memory stores entities;

2. The update speed of stack memory is faster than that of heap memory, because the life cycle of local variables is very short;

3. The variables stored in stack memory will be released once their life cycle ends, while the entities stored in heap memory will be released. It will be collected by the garbage collection mechanism from time to time.

php Chinese website, a large number of free Java introductory tutorials, welcome to learn online!

The above is the detailed content of The difference between heap and stack 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

deepseek What is the difference between r1 and v3 version deepseek What is the difference between r1 and v3 version Feb 19, 2025 pm 03:24 PM

DeepSeek: In-depth comparison between R1 and V3 versions helps you choose the best AI assistant! DeepSeek already has tens of millions of users, and its AI dialogue function has been well received. But are you confused when facing the R1 and V3 versions? This article will explain the differences between the two in detail to help you choose the most suitable version. The core difference between DeepSeekR1 and V3 version: Features The design goal of the V3 version focuses on complex problem reasoning, deep logic analysis, multi-functional large language model, focusing on scalability and efficiency architecture and parameter reinforcement learning optimization architecture, parameter scale 1.5 billion to 70 billion MoE hybrid Expert architecture, total parameters are as high as 671 billion, each token is activated by 37 billion

Summary of FAQs for DeepSeek usage Summary of FAQs for DeepSeek usage Feb 19, 2025 pm 03:45 PM

DeepSeekAI Tool User Guide and FAQ DeepSeek is a powerful AI intelligent tool. This article will answer some common usage questions to help you get started quickly. FAQ: The difference between different access methods: There is no difference in function between web version, App version and API calls, and App is just a wrapper for web version. The local deployment uses a distillation model, which is slightly inferior to the full version of DeepSeek-R1, but the 32-bit model theoretically has 90% full version capability. What is a tavern? SillyTavern is a front-end interface that requires calling the AI ​​model through API or Ollama. What is breaking limit

Does Bitcoin have stocks? Does Bitcoin have equity? Does Bitcoin have stocks? Does Bitcoin have equity? Mar 03, 2025 pm 06:42 PM

The cryptocurrency market is booming, and Bitcoin, as a leader, has attracted the attention of many investors. Many people are curious: Do Bitcoin have stocks? The answer is no. Bitcoin itself is not a stock, but investors can indirectly invest in Bitcoin-related assets through various channels, which will be explained in detail in this article. Alternatives to Bitcoin Investment: Instead of investing directly in Bitcoin, investors can participate in the Bitcoin market by: Bitcoin ETF: This is a fund traded on the stock trading market, whose asset portfolio contains Bitcoin or Bitcoin futures contracts. This is a relatively convenient option for investors who are accustomed to stock investments, without having to hold Bitcoin directly. Bitcoin Mining Company Stocks: These companies' business is Bitcoin mining and holding Bitcoin

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

What is the difference between pre-market and after-market trading? Detailed explanation of the differences between pre-market and after-market trading What is the difference between pre-market and after-market trading? Detailed explanation of the differences between pre-market and after-market trading Mar 03, 2025 pm 11:54 PM

In traditional financial markets, pre-market and after-market trading refers to trading activities outside the regular trading period. Although the cryptocurrency market is trading around the clock, trading platforms like Bitget also offer similar features, especially some comprehensive platforms that trade stocks and cryptocurrencies at the same time. This article will clarify the differences in pre-market and after-market trading and explore its impact on currency price. Four major differences between pre-market and after-market trading: The main differences between pre-market and after-market trading and regular trading periods are in four aspects: trading time, liquidity, price fluctuations and trading volume: Trading time: Pre-market trading occurs before the official trading starts, and after-market trading is carried out after the regular trading ends. Liquidity: The liquidity of pre- and after-hours trading is low, there are few traders, and the bid and offer price difference is large; while the liquidity is high during the regular trading period, the price is

Why is Bittensor said to be the 'bitcoin' in the AI ​​track? Why is Bittensor said to be the 'bitcoin' in the AI ​​track? Mar 04, 2025 pm 04:06 PM

Original title: Bittensor=AIBitcoin? Original author: S4mmyEth, Decentralized AI Research Original translation: zhouzhou, BlockBeats Editor's note: This article discusses Bittensor, a decentralized AI platform, hoping to break the monopoly of centralized AI companies through blockchain technology and promote an open and collaborative AI ecosystem. Bittensor adopts a subnet model that allows the emergence of different AI solutions and inspires innovation through TAO tokens. Although the AI ​​market is mature, Bittensor faces competitive risks and may be subject to other open source

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

Is there any difference between South Korean Bitcoin and domestic Bitcoin? Is there any difference between South Korean Bitcoin and domestic Bitcoin? Mar 05, 2025 pm 06:51 PM

The Bitcoin investment boom continues to heat up. As the world's first decentralized digital asset, Bitcoin has attracted much attention on its decentralization and global liquidity. Although China was once the largest market for Bitcoin, policy impacts have led to transaction restrictions. Today, South Korea has become one of the major Bitcoin markets in the world, causing investors to question the differences between it and its domestic Bitcoin. This article will conduct in-depth analysis of the differences between the Bitcoin markets of the two countries. Analysis of the differences between South Korea and China Bitcoin markets. The main differences between South Korea and China’s Bitcoin markets are reflected in prices, market supply and demand, exchange rates, regulatory supervision, market liquidity and trading platforms. Price difference: South Korea’s Bitcoin price is usually higher than China, and this phenomenon is called “Kimchi Premium.” For example, in late October 2024, the price of Bitcoin in South Korea was once

See all articles