Summary of problems related to Java local variables and member variables

Source: Internet
Author: User

Summary of problems related to Java local variables and member variables2013-02-03 12:39 156 people read Comments (0) favorite reports

All variables in Java can be divided into local variables and member variables. The difference between them:

1. Definition

Member variables: variables defined within the class body are called member variables;

Local variables: Parameters, methods, variables defined in code blocks, are local variables.

(Note: The local variable definition must be inside the method!) )

2. Detailed classification

Member variables: 1) class variable (static variable)--there is static modification;

2) instance variable (non-static variable)-no static modifier.

Local variables: 1) Formal parameters--variables defined in the method signature;

2) method local variable--defined within the method (function);

3) code block local variable--defined within a code block (for example, a variable inside a for loop).

3. Initialization

Member variable: No explicit initialization is required, as long as a class variable or instance variable is defined for a class, the system

class, or create an instance of this class for default initialization.

Local variables: Except for formal parameters, they must be explicitly initialized.

4. Scope of Action

Member variables: Acting on the entire class;

Local variable: In a method (function), or in a statement.

5. In-memory location

Member variable: in heap memory. exists in memory because of the existence of a class or object;

Local variables: In the stack memory. Because he does not belong to any class or instance, he is always saved in the stack memory of the method in which it resides. If the local variable is a variable of the basic type, the value of the variable is stored directly in the corresponding memory of the variable, and if it is a variable of reference type, the variable holds the address, which refers to the object or array that the variable actually refers to.

The difference between a class variable and an instance variable:

1. References

Class variables: can be referenced forward;

Instance variable: Can not forward reference, if forward reference, becomes illegal forward reference.

2. Attribution and Life cycle

Class variable: belongs to the class itself. Can be understood as a class member variable. As a member of a class, it survives with the class;

Instance variable: an instance object that belongs to a class. Can be understood as instance member variables. It acts as a member of an instance,

And the example of a common survival.

3. Space allocation

Class variable: an instance of a class that is not dependent, and is allocated only once in the stack memory at initialization time. Regardless of the instance of the class

Are created several times, no longer allocate space for class variables;

Instance variable: Allocates memory space when an instance is created

4. Storage location

Class variables: As classes are loaded, they exist in the method area;

Instance variable: exists in heap memory as the object is established.

The sample code is as follows:

[Java]View Plaincopyprint?
  1. Class Person
  2. {
  3. String name; //Instance variable
  4. static String country = "CN"; Class variables
  5. public static void country ()//static member function
  6. {
  7. System.out.println ("My country is" + country);
  8. }
  9. public void Shout ()
  10. {
  11. System.out.println ("My name is" + name);
  12. }
  13. public void calculation (int num)//num as formal parameters
  14. {
  15. int sum = 0; Sum is a method local variable
  16. for (int i=0;i<=num;i++)//i is a code block local variable
  17. {
  18. sum = sum + i;
  19. }
  20. System.out.println ("The result is" + sum);
  21. }
  22. }
  23. Class Staticdemo
  24. {
  25. public static void Main (string[] args)
  26. {
  27. Person.country (); //class can access class variables directly
  28. Person p = new person ();
  29. P.name = "Zhagnsan";
  30. P.shout ();
  31. P.calculation (100);
  32. }
  33. }
Class person{string name;//instance variable static String country = "CN";//class variable public static void country ()//static member function { System.out.println ("My country is" + country);} public void Shout () {System.out.println ("My name is" + name);} public void calculation (int num)//num is the parameter {int sum = 0;//sum is the method local variable for (int i=0;i<=num;i++)//i is a code block local variable {sum = sum + i;} SYSTEM.OUT.PRINTLN ("The result is" + sum);}} Class Staticdemo {public static void main (string[] args) {person.country ();//class can directly access the class variable person p = new person ();p. Name = "Z Hagnsan ";p. Shout ();p. calculation (100);}


Some key points of each variable:

1. Initialization of member variables and operating mechanism in memory: during the preparation phase of the class, the system allocates memory space (heap memory) for the class variables of the classes, and the default initial values are set. When the initialization is complete, the memory in the heap is divided

With a piece of memory area.

2. Consider usage scenarios for member variables:

1) variables that describe the inherent information of an object, such as the height of a person;

2) A variable that holds a class, or an instance state information;

3) If a message needs to be shared among multiple methods of a class, this information should use a member variable.

3. When the scope of the member variable expands to the scope of the class or the scope of the object, there are two disadvantages to the enlargement of this range:

1) Increase the lifetime of the variable, which will lead to greater overhead;

2) Expand the scope of the variable, which is not conducive to improve the cohesion of the program.

4. Java allows local variables and member variables to have the same name, if local variables and member variables have the same name, local variables override member variables, and if you need to use member variables in this method, you need this (for

Instance property) or the class name (for class properties) as the caller to restrict access to this member variable.

5. Class variables can also be used to access an instance of the class: instance. Class variable. (This is actually an illusion, in fact, it is a class.) that is, if you modify the value of a class variable by an instance, because this class

The variable does not belong to it, but belongs to its corresponding class. Therefore, the modification is still a class variable of the class, and the result of modifying the class variable through the class is exactly the same, so that other instances of the class will gain access to the class variable

The value that was modified.

6. Scope of three types of local variables:

1) Formal parameters: valid throughout the method;

2) method local variable: From the place where the variable is defined, to expire at the end of the method;

3) code block local variable: takes effect from the place where the variable is defined, and expires at the end of the code block.

7. In Java, a method cannot define two local variables with the same name, even if one is a method variable, and one is a code block variable or a parameter.

8. Initialization of formal parameters: When a method is called through a class or object, the system allocates memory space for all parameters within the method area and assigns the value of the argument to the corresponding parameter, which completes the initialization of the formal parameter.

9. The member variable is in the heap memory, because the object exists in memory, and the local variable exists in the stack memory, the member function is not in the heap memory, but in the Java method area, the member function's local variable is in heap memory.

Iv. stack memory and heap memory summary:

        1. Stack memory: When a function is called, the function applies a space in the stack memory, and the variables defined inside the function will be assigned to the stack that the function applies to. When the function is finished, the stack space allocated to the function is retracted, and the variables defined in the function are freed and gone.

2. Heap Memory: Arrays and objects generated by new are allocated in heap memory. The memory allocated in heap memory, which is managed by the JVM-provided GC (garbage collection mechanism). After generating an array object in heap memory, we can also define a variable in the stack that is equal to the first address of the object in the heap. The variable in the stack memory is a reference variable in the heap memory array or object. We can use this variable in the stack to access the array or object we allocate in the heap, which is equivalent to an alias, or a code name, from an array or object.
         V. Reference variables:

A reference variable is a normal variable that is allocated in the stack when defined, and the reference variable is freed when it is run outside its scope, and our array and object itself are allocated in the heap, even after the program runs to the function or code that contains the statement that generated the object using new. The arrays and objects we just generated are not released. Arrays and objects simply point to it without a reference variable, that is, the value of no reference variable equals its first address, it becomes garbage will not be used, but it still occupies the memory space (which is the reason we Java compare to eat memory), at a subsequent uncertain time by the garbage collector away.
The public void calculation (int num)//num is the formal parameter {int sum = 0;//sum is the method local variable for (int i=0;i<=num;i++)//i is a code block local variable {sum = sum + I } System.out.println ("The result is" + sum);}} Class Staticdemo {public static void main (string[] args) {person.country ();//class can be accessed directly from the classes variable person p = new person (); p.name = "Zhagnsan"; P.shout (); P.calculation (100); } }


Some key points of each variable:

1. Initialization of member variables and operating mechanism in memory: during the preparation phase of the class, the system allocates memory space (heap memory) for the class variables of the classes, and the default initial values are set. When the initialization is complete, the memory in the heap is divided

With a piece of memory area.

2. Consider usage scenarios for member variables:

1) variables that describe the inherent information of an object, such as the height of a person;

2) A variable that holds a class, or an instance state information;

3) If a message needs to be shared among multiple methods of a class, this information should use a member variable.

3. When the scope of the member variable expands to the scope of the class or the scope of the object, there are two disadvantages to the enlargement of this range:

1) Increase the lifetime of the variable, which will lead to greater overhead;

2) Expand the scope of the variable, which is not conducive to improve the cohesion of the program.

4. Java allows local variables and member variables to have the same name, if local variables and member variables have the same name, local variables override member variables, and if you need to use member variables in this method, you need this (for

Instance property) or the class name (for class properties) as the caller to restrict access to this member variable.

5. Class variables can also be used to access an instance of the class: instance. Class variable. (This is actually an illusion, in fact, it is a class.) that is, if you modify the value of a class variable by an instance, because this class

The variable does not belong to it, but belongs to its corresponding class. Therefore, the modification is still a class variable of the class, and the result of modifying the class variable through the class is exactly the same, so that other instances of the class will gain access to the class variable

The value that was modified.

6. Scope of three types of local variables:

1) Formal parameters: valid throughout the method;

2) method local variable: From the place where the variable is defined, to expire at the end of the method;

3) code block local variable: takes effect from the place where the variable is defined, and expires at the end of the code block.

7. In Java, a method cannot define two local variables with the same name, even if one is a method variable, and one is a code block variable or a parameter.

8. Initialization of formal parameters: When a method is called through a class or object, the system allocates memory space for all parameters within the method area and assigns the value of the argument to the corresponding parameter, which completes the initialization of the formal parameter.

9. The member variable is in the heap memory, because the object exists in memory, and the local variable exists in the stack memory, the member function is not in the heap memory, but in the Java method area, the member function's local variable is in heap memory.

Iv. stack memory and heap memory summary:

        1. Stack memory: When a function is called, the function applies a space in the stack memory, and the variables defined inside the function will be assigned to the stack that the function applies to. When the function is finished, the stack space allocated to the function is retracted, and the variables defined in the function are freed and gone.

2. Heap Memory: Arrays and objects generated by new are allocated in heap memory. The memory allocated in heap memory, which is managed by the JVM-provided GC (garbage collection mechanism). After generating an array object in heap memory, we can also define a variable in the stack that is equal to the first address of the object in the heap. The variable in the stack memory is a reference variable in the heap memory array or object. We can use this variable in the stack to access the array or object we allocate in the heap, which is equivalent to an alias, or a code name, from an array or object.
         V. Reference variables:

A reference variable is a normal variable that is allocated in the stack when defined, and the reference variable is freed when it is run outside its scope, and our array and object itself are allocated in the heap, even after the program runs to the function or code that contains the statement that generated the object using new. The arrays and objects we just generated are not released. Arrays and objects simply point to it without a reference variable, that is, the value of no reference variable equals its first address, it becomes garbage will not be used, but it still occupies the memory space (which is the reason we Java compare to eat memory), at a subsequent uncertain time by the garbage collector away.

Summary of problems related to Java local variables and member variables

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.