Java static life cycle and scope

Source: Internet
Author: User

There are two types of member variables for a class: A variable that is modified by the static keyword, called a class variable or a static variable, and is not modified by static, called an instance variable.

The difference between the syntax definitions: Static variables are added with the static keyword, and the instance variable is not added before.

The difference when the program runs: instance variables belong to an object's properties, and an instance object must be created where the instance variable is allocated space before the instance variable can be used.

A static variable is not part of an instance object, but belongs to a class, so it is also called a class variable, as long as the program loads the bytecode of the class without creating any instance objects

Static variables are allocated space, and static variables can be used. In summary, an instance variable must be created before it can be used by the object, and a static variable can be referenced directly using the class name.

The Java virtual machine allocates memory for static variables during class loading, and static variables are located in the method area

is shared by all instances of the class, and static variables can be accessed directly through the class name.

The life cycle of a static variable depends on the life cycle of the class, and when the class is loaded, the static variable is created and allocated memory space, and when the class is unloaded, the static variable is destroyed and the occupied memory is freed.

Each instance of the class has a corresponding instance variable, each of which creates an instance of the class, the Java virtual machine allocates memory for the instance variable once, and the instance variable is in the heap area

Java static life cycle and scope

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.