Differences between static variables and instance variables in java

Source: Internet
Author: User

Running effect:

Console effect:

========================================================== ============

Code Section

========================================================== ============

/Hello_test/src/com/b510/test/StaticTest. java
Copy codeThe Code is as follows :/**
*
*/
Package com. b510.test;

/**
* Differences during program running: instance variables belong to the attributes of an object, and an instance object must be created. <br>
* The instance variable is allocated space before the instance variable can be used. Static variables do not belong to a certain <br>
* Instance objects, but belong to the class, so it is also called a class variable, as long as the program loads the class bytecode, <br>
* Without creating any instance object, static variables are allocated space and can be used. <Br>
* In short, instance variables can be used only after an object is created. Static variables can be used. <br>
* Directly use the class name for reference. For example, no matter how many instance objects are created for the following program, <br>
* Only One <code> staticInt </code> variable is always assigned, and each time an instance object is created, <br>
* This <code> staticInt </code> adds 1. However, each time an instance object is created, a <code> random </code>, <br>
* Multiple <code> random </code> may be allocated, and each <code> random </code> value is added only once. <Br>
*
* @ Author <a href = "mailto: hongtenzone@foxmail.com"> hongten </a>
* @ Date 2013-3-2
*/
Public class StaticTest {

Private static int staticInt = 2;
Private int random = 2;

Public StaticTest (){
StaticInt ++;
Random ++;
System. out. println ("staticInt =" + staticInt + "random =" + random );
}

Public static void main (String [] args ){
StaticTest test = new StaticTest ();
StaticTest test2 = new StaticTest ();
}
}

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.