Summary of static Static static Keyword in Java

Keywords: Java jvm less

static keyword in java

I. Static overview
We can create multiple objects based on a class, each object has its own members, and the values of all member variables exist according to the object. Sometimes we want all objects of a class to share a member, which uses the static static keyword.
Members modified by static keywords belong to static members, which belong to the whole class, but not only to members of an object. When the system first uses this class, it allocates memory space for them. It does not recycle until the class is destroyed. Static members also have their own unique visitors. Law.  
static can modify variables, methods, and code blocks.

1. static variable:

For static variables, there is only one copy in memory, which saves memory. Java Virtual Machine allocates memory only once for static variables. It completes the memory allocation of static variables in the process of loading classes. It is convenient to access class names directly, and of course it can also be accessed through objects, but there is no static existence. Meaning.
For instance variables, each instance created will allocate memory for instance variables once. Instance variables can have multiple copies in memory, so it is flexible to not affect each other.
So static variables are usually used when you need to implement the following two situations:

2. static method:

Static methods can be invoked directly by class names, and any instances can also be invoked. Therefore, this and super keywords can not be used in static methods. They can not directly access instance variables and instance methods of their classes, but only static member variables and member methods of their classes.
Because the static method is independent of any instance, the static method must be implemented, not abstract.
For example, in order to facilitate method invocation, all methods in Math class in Java API are static, and static methods in general classes are also convenient for other classes to call this method.
Static methods are a special class of methods within a class. The corresponding methods are declared static only when needed. The methods within a class are generally non-static.

3. static code block:

Static code blocks, also known as static code blocks, are static statement blocks independent of class members in a class. They can be multiple and can be placed randomly. It is not in any method body. When a JVM loads a class, it executes these static code blocks. If there are multiple static code blocks, the JVM will follow the sequence in which they appear in the class. They are executed sequentially, and each block of code is executed only once.
Static variables can be assigned by using static code blocks. Finally, take a look at these examples. They all have a main method of static, so that JVM can call the main method directly without creating an instance.

II. Static Characteristics

1. A member variable modified by static belongs to a class, not an object of that class. (That is to say, when multiple objects access or modify member variables modified by static, one of them modifies the value of the static member variable, and the value of the static member variable in other objects changes accordingly, that is, multiple objects share the same static member variable)
2. Members modified by static can and recommend direct access through class names
Format for accessing static members:
Class name. Static member variable name
Class name. Static member method name (parameter)
3. Static loading takes precedence over objects and loads with class loading

Case code

package com.test;
/*
 *static:Is a keyword used to modify member variables and member methods
 *static Characteristics:
 *      Shared by all objects
 *      Calls can be made using class names
 *      Static loading takes precedence over objects
 *      Load as classes are loaded
 * 
 */
public class StaticDemo {
	public static void main(String[] args) {
		Person.comeFrom = "Chengdu";
		
		Person p = new Person();
		p.name = "Zhang San";
		p.age = 18;
		//p.comeFrom = Chengdu;
		p.speak();
		
		Person p2 = new Person();
		p2.name = "Li Si";
		p2.age = 20;
		//GradFrom = Chengdu;
		p2.speak();
	}
}

class Person {
	String name;
	int age;
	static String comeFrom;
	
	public void speak() {
		System.out.println(name + "---" + comeFrom);
	}
}

II. Static Notices

1. Static members can only access static members directly.
2. Non-static members can access both non-static members and static members.

Case code

 package com.test;
/*
 * static Notes:
 * 			Static method:
 * 				Static member variables can be invoked
 * 				Static member methods can be invoked
 * 				Non-static member variables cannot be invoked
 * 				Non-static member methods cannot be invoked
 * 				Static methods can only call static members
 * 			Non-static method:
 * 				Static member variables can be invoked
 * 				Static member methods can be invoked
 * 				Non-static member variables can be invoked
 * 				Non-static member methods can be invoked
 * 		
 * 	Is there this object in the static method? No
 * 				
 * 
 */
public class StaticDemo2 {
	public static void main(String[] args) {
		Student.comeFrom = "Chengdu";
		Student.study();
	}
}


class Student {
	String name;
	int age;
	static String comeFrom;
	
	public static void study() {
		System.out.println(name);		
		eat();		
	}
	
	public void eat() {
		System.out.println("eat");		
		System.out.println(comeFrom);				
	}
	
}

3. Advantages and disadvantages of static state

1. Static advantages:
It saves space by providing separate storage for shared data of objects. It is not necessary for each object to store a copy that can be called directly by class name without creating objects in heap memory.
Static members can be accessed directly by class names, which is more convenient than creating objects to access members.
2. Static drawbacks:
Visits have limitations. (Static is good, but it can only be accessed)

IV. Static Applications

Math class uses:
1. Math classes contain methods for performing basic mathematical operations. Classes commonly used in mathematical operations.
2. The construction method of Math class is private, and it is impossible to create objects and access members of Math class through objects.
3. All members of the Math class are statically modified, so we can access them directly through the class name.

Case code

package com.test;

public class MathDemo {
	public static void main(String[] args) {
		//Math: Includes some basic mathematical operations
		//static double PI  
		//System.out.println(Math.PI);
		
		//static double abs(double a) / / returns absolute value
		//System.out.println(Math.abs(15));
		//System.out.println(Math.abs(-10));
		
		//static double ceil(double a)//Ceiling up
		//System.out.println(Math.ceil(1.2));
		//System.out.println(Math.ceil(1.6));
		//static double floor(double a) / / floor downward rectification
		//System.out.println(Math.floor(1.2));
		//System.out.println(Math.floor(1.6));
		
		//static long round(double a)//rounding
		//System.out.println(Math.round(1.2));
		//System.out.println(Math.round(1.6));
		
		//static double max(double a, double b) 
		//System.out.println(Math.max(3, 4));
		
		//static double pow(double a, double b) / / Returns the second parameter power of the first parameter
		//System.out.println(Math.pow(3, 2));
		
		//static double random()// Returns a random number, greater than zero and less than one
		System.out.println(Math.random());	 
	}
}

Custom Tool Class:

Requirements: Customize a tool class for array operations, with the following functions
1. Define a method that returns the largest element in an array
2. Define a method that looks for the existence of the value in an array based on the specified value
Existence, returns the index of the value in the array
No, return - 1

Case code

package com.test;

public class MyArrays {
	private MyArrays() {} 
		
	/*
	 * Returns the largest element in an array
	 */
	public static int getMax(int[] arr) {
		int max = 0;//Object of reference
		//foreach
		for(int x = 0;x < arr.length;x++) {
			if(arr[x] > max) {
				max = arr[x];//Replacement reference
			}
		}	
		return max;
	}
	
	/*
	 * Returns the index of the specified parameter in the array
	 */	
	public static int getIndex(int[] arr,int a) {
		//foreach
		for(int x = 0;x < arr.length;x++) {
			if(arr[x] == a) {
				return x;
			}
		}		
		return -1;//If the parameters are not found, return - 1
	}
}
package com.test;

public class MyArraysDemo {
	public static void main(String[] args) {
		int[] arr = {3,5,8,10,2};
		int max = MyArrays.getMax(arr);
		System.out.println(max);
		
		int index = MyArrays.getIndex(arr, 8);
		System.out.println(index);		
	}
}

V. Analysis of Class Variables and Example Variables

1. Class variables: Actually, they are static variables.
Define Location: Define Outside of Method in Class
Located memory area: method area
Lifecycle: Loading as classes are loaded
Feature: No matter how many objects are created, class variables are only in the method area and have only one copy.
2. Instance variables: Actually, they are non-static variables.
Define Location: Define Outside of Method in Class
Memory area: heap
Lifecycle: Loaded as objects are created
Feature: For every object created, there is an instance variable in the heap

Code case

package com.test

public class Classmate {
    static String name = "Zhang San";  //Modified by static, is a class variable
    public int age = 18;         //Instance variables

}
class Print {
    public static void main(String[] args) {
        Classmate classmateA = new Classmate();
        classmateA.name = "Li Si";
        classmateA.age = 21;
        //Modified value of instance variable
        System.out.println(classmateA.name+"..."+classmateA.age);
        Classmate classmateB = new Classmate();
        //name is a class variable, has been changed, int is an instance object, and follows the original value of classmate
        System.out.println(classmateB.name+"..."+classmateB.age);
    }
}

6. Code Block

1. Local code block:
Local code blocks are defined in methods or statements.

Case code

package com.test;

public class BlockDemo {
	public static void main(String[] args) {
		
		//Local code blocks: Existing in methods that control the lifecycle (scope) of variables
		 {
			for(int x = 0;x < 10;x++) {
				System.out.println("I love Java");
			}
			int num = 10;
		}
		//System.out.println(num); // unable to access num, beyond the scope of num 
	}
}

2. Construct code blocks:
Constructing code blocks is a code block that defines the location of members in a class.

Case code

class Teacher {
	String name;
	int age;
	
	{
		for(int x = 0;x < 10;x++) {
			System.out.println("I am Java");
		}
		System.out.println("I am Java");
	} 
		
	public Teacher() {
		System.out.println("I am an empty structure.");
	}
	
	public Teacher(String name,int age) {
		System.out.println("I have parametric structure.");		
		this.name = name;
		this.age = age;
	}	
}

3. Static code block:
Static code blocks are code blocks defined at member locations and modified with static.

Case code

class Teacher {
	String name;
	int age;
 
	//Static Code Block: Loaded as the class is loaded, only once. Some initialization is needed when loading the class, such as load driver.
	static {
		System.out.println("I am Java");
	}
	
	public Teacher() {
		System.out.println("I am an empty structure.");
	}
	
	public Teacher(String name,int age) {
		System.out.println("I have parametric structure.");		
		this.name = name;
		this.age = age;
	}
	
}

4. The characteristics of each code block:

4.1 Local code block:
Code areas delimited with "{}" need only focus on different scopes.
Both methods and classes delimit boundaries in block-by-block fashion
4.2 Construct code blocks:
Priority to constructor execution, constructor blocks are used to perform initialization actions required by all objects
Each creation of an object executes a block of construction code.
4.3 Static code block:
It takes precedence over the execution of the main method, over the execution of the construction code block, when it is first used in any form.
No matter how many objects are created in this class, static code blocks are executed only once.
It can be used to assign static variables and initialize classes.

Case code

package com.test;

/*
 *   Coder Static Code Block Execution - Coder Construction Code Block Execution - Coder Nonparametric Construction Execution
 *    
 *   BlockTest Static Code Block Execution - - BlockTest's main function executes - - Coder Static Code Block Execution - - Coder Construction Code Block Execution - - Coder Parametric Construction Execution
 *   Coder Construction code block execution - - Coder parametric construction execution
 * 
 */
public class BlockTest {
	static {
		System.out.println("BlockTest Static code block execution");
	}
	
	{
		System.out.println("BlockTest Construct code block execution");
	}
	
	public BlockTest(){
		System.out.println("BlockTest The parametric construct is executed");
	}
	
	public static void main(String[] args) {
		System.out.println("BlockTest The main function is executed.");
		Coder c = new Coder();
		Coder c2 = new Coder();
	}
}

class Coder {	
	static {
		System.out.println("Coder Static code block execution");
	}
	
	{
		System.out.println("Coder Construct code block execution");
	}
	
	public Coder() {
		System.out.println("Coder Nonparametric construction execution");
	}	
	
}

Posted by pyc on Sat, 07 Sep 2019 02:42:11 -0700