Java static variable instance variable static method explanation

Source: Internet
Author: User
Tags stub

First, the syntax definition difference: the static keyword must be added before the static variable, but not before the instance variable.

Differences during program running: instance variables belong to the attributes of an object. You must create an instance object. Only instance variables in the instance can be allocated space to use this instance variable. Static variables do not belong to a certain instance object but belong to a class, so they are also called class variables. As long as the program loads the class bytecode, no instance object needs to be created, static variables are allocated space, and static variables can be used. In short, instance variables must be created before they can be used.

The code is as follows: Copy code


Package staticVar;
 
Public class svar {
Public int var = 1000;
Public static void main (String [] args ){
Svar = new svar ();
System. out. println ("var =" + svar. var );
     }
 }

Static variables can be referenced directly by class names.

The code is as follows: Copy code


Package staticVar;
 
Public class svar {
Public static int var = 1000;
Public static void main (String [] args ){
System. out. println ("var =" + svar. var );
     }
 }

The class has only one static variable in the memory. The Java virtual machine allocates memory for the static variable during the class loading process. The static variable is located in the method area and is shared by all instances of the class. 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.
The instance variable depends on the instance of the class. Each time an instance is created, the Java virtual machine allocates memory for the instance variable once. The instance variable is located in the heap area, and its life cycle depends on the life cycle of the instance.

Static variables have a long life cycle and are not easily recycled by the system. Therefore, if you cannot properly use static variables, it will be counterproductive, resulting in a large amount of memory waste. Therefore, we recommend that you use static variables whenever possible with all of the following conditions:

(1) the variable contains a large volume of objects, occupying a large amount of memory.

(2) the variable contains a long object lifecycle.

(3) the object data contained in the variable is stable.

(4) the object instances of this class need to share the objects contained in this variable.

 

You can declare both methods and variables as static. The most common example of static members is main (). Because the main () must be called when the program starts execution, it is declared as static. Variables declared as static are actually global variables. The method declared as static has the following restrictions :·

A. They can only call other static methods.

B. They can only access static data.

C. They cannot reference this or super in any way (this involves objects, and super is related to inheritance)

Example: If you need to initialize your static variable through calculation, you can declare a static block. The Static block is executed only once when the class is loaded. The following example shows that the class has a static method, and some static changes
And a static initialization block.

The code is as follows: Copy code


Public class TestNew {
Static int a = 3;
Static int B;
Static void meth (int x ){
System. out. println ("x =" + x );
System. out. println ("a =" + );
System. out. println ("B =" + B );
    } 
Static {
System. out. println ("static block initialized ");
B = a * 4;
    } 
Public static void main (String [] args ){
// TODO Auto-generated method stub
Meth (42 );
    } 
}

The execution result is:

Static block initialized
X = 42
A = 3
B = 12

The execution sequence of the above class TestNew is: first, a is set to 3, then static block execution (print a message), and finally B is initialized to a * 4 to 12. Then, call main () and main () to call meth () and pass the value 42 to x. The three println () statements reference two static variables a and B, and the local variable x.

Use static variables or static methods externally

Outside the class that defines them, static methods and variables can be used independently of any object. You only need to add an operator after the class name. As you can see, this format is similar to calling a non-static method or variable format through the object reference variable. This is a control version of how Java implements global functions and global variables. Example:

The code is as follows: Copy code

Class StaticDemo {
Static int a = 42;
Static int B = 99;
Static void callme (){
System. out. println ("a =" + );
    } 

Public class TestNew {
Public static void main (String [] args ){
// TODO Auto-generated method stub
StaticDemo. callme ();
System. out. println ("B =" + StaticDemo. B );
    } 
}

Execution result:

A = 42
B = 99

What is the difference between static variables and instance variables?

/**
 *
*/
Package com. b510.test;

The code is as follows: Copy code

/**
* 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 ();
    }
}

Static variables and instance variables for thread security issues

Static variable: the thread is not secure.
Static variables are class variables and are located in the method area. They are shared with all objects and share one copy of memory. Once the static variables are modified, other objects are visible to the changes, so the thread is not safe.

Instance variables: in Singleton mode (only one object instance exists), the thread is not secure, and the thread is not secure.

The instance variable is private to the object instance. It is allocated in the heap of the virtual machine. If only one instance of this object exists in the system, in the multi-threaded environment, it is "like" static variable, after being modified by a thread, other threads can be viewed for modification, so the thread is not safe. If each thread is executed in a different object, the modification of instance variables between the object and the object will not affect each other, so the thread is secure.

 

The code is as follows: Copy code
/**
* Simulate thread security issues
*------------------------------
* Thread 1 | thread 2
*------------------------------
* Static_ I = 4; | wait
* Static_ I = 10; | wait
* Waiting | static_ I = 4;
* Static_ I * 2; | wait
*-----------------------------
**/
Public class Test implements Runnable

Private static int static_ I; // static variable
     
Public void run ()
    { 
Static_ I = 4;
System. out. println ("[" + Thread. currentThread (). getName ()
+ "] Get the static_ I value:" + static_ I );
Static_ I = 10;
System. out. println ("[" + Thread. currentThread (). getName ()
+ "] Get the value of static_ I * 3:" + static_ I * 2 );
    } 
     
Public static void main (String [] args)
    { 
Test t = new Test ();
// Start as many threads as possible to simulate problems easily
For (int I = 0; I <3000; I ++)
        { 
// T can be changed to new Test () to ensure that each thread is executed in different objects and the result is the same
New Thread (t, "Thread" + I). start ();
        } 
    } 

 

 
According to the simulation in the code comment, when Thread 1 executes static_ I = 4; static_ I = 10;, thread 2 obtains the execution permission, static_ I = 4; then, when Thread 1 obtains the execution right to execute static_ I * 2, the result 4*2 = 8 is output. According to this simulation, we may see the output result as 8 on the console.
Write
[Thread 27] get static_ I value: 4
[Thread 22] get the static_ I * 2 value: 20
[Thread 28] get static_ I value: 4
[Thread 23] get the static_ I * 2 value: 8
[Thread 29] get static_ I value: 4
[Thread 30] get static_ I value: 4
[Thread 31] get static_ I value: 4
[Thread 24] get the static_ I * 2 value: 20
Looking at the red part shows our expectation and proves our conclusion.
 
Simulation of thread security issues with instance variables:
----------------------------------------------------------------------------------

The code is as follows: Copy code
Java code
Public class Test implements Runnable

Private int instance_ I; // instance variable
     
Public void run ()
    { 
Instance_ I = 4;
System. out. println ("[" + Thread. currentThread (). getName ()
+ "] Get the instance_ I value:" + instance_ I );
Instance_ I = 10;
System. out. println ("[" + Thread. currentThread (). getName ()
+ "] Get the value of instance_ I * 3:" + instance_ I * 2 );
    } 
     
Public static void main (String [] args)
    { 
Test t = new Test ();
// Start as many threads as possible to simulate problems easily
For (int I = 0; I <3000; I ++)
        { 
// Each thread runs in object t to simulate the Singleton situation
New Thread (t, "Thread" + I). start ();
        } 
    } 

 


 
According to the analysis at the beginning of this article, as with static variables, every thread is modifying the instance variables of the same object, and thread security issues will certainly occur.
Write
[Thread 66] get instance_ I value: 10
[Thread 33] get the value of instance_ I * 2: 20
[Thread 67] get instance_ I value: 4
[Thread 34] get the value of instance_ I * 2: 8
[Thread 35] get the value of instance_ I * 2: 20
[Thread 68] get instance_ I value: 4
 
Looking at the red font, we can see that the instance variable thread is not safe in the case of a singleton.
 
Set new Thread (t, "Thread" + I ). change start (); to new Thread (new Test (), "Thread" + I ). start (); when simulating non-singleton cases, no thread security issues will be found

Related Article

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.