Remember the first Java code we wrote?
public class Main {
public static void main(String[] args) {
System.out.println("Hello, WOrld!");
}
}
copy the code
our method is marked with a modifier, so what does this modifier mean? main
static
static
static variables
if a field is defined as static, then there is only one such field per class.
let’s first look at classes that don’t have static static traversal:
class Student {
int stuId;
String name;
String school = "HY No.1 High School";
}
copy the code
assuming there are 1500 students in high school, the above code now gives all instance data members memory each time the object is created.
All students have their own unique stuIds and names, and these instance data members are correct in this case, after all are unique.
however, the “school” here is a common property of all objects. if not declared as a static variable, it can also consume multiple memory. but if we make it static, this field will only get memory once.
static variable declarations
class Student {
int stuId; // 实例变量
String name;
static String school = "HY No.1 High School"; // 静态变量
}
copy the code
if you declare any variable to be static, it is called a static variable.
- static variables can be used to refer to properties common to all objects (not unique to each object), for example, the company name of an employee, the name of a student’s college, etc.
- static variables get memory in the class area only once when the class is loaded.
static variable testing
code testing:
package com.yuzhou1su.RelearnJava;
class Student {
int stuId;
String name;
static String school = "HY No.1 High School";
Student(int id, String n) {
stuId = id;
name = n;
}
void display() {
System.out.println("Student id:" + stuId + ", Name:" + name + " is from " + school);
}
}
public class TestVariable {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student s1 = new Student(001, "Karsa");
Student s2 = new Student(002, "Ellen");
s1.display();
s2.display();
}
}
copy the code
execution result:
Student id:1, Name:Karsa is from HY No.1 High School
Student id:2, Name:Ellen is from HY No.1 High School
copy the code
a static variable gets memory only once, and if any object changes the value of a static variable, it retains its value. look at the following code:
package com.yuzhou1su.RelearnJava;
public class StaticVariableCount {
static int count = 0;
StaticVariableCount() {
count++;
System.out.println(count);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
StaticVariableCount svc1 = new StaticVariableCount();
StaticVariableCount svc2 = new StaticVariableCount();
StaticVariableCount svc3 = new StaticVariableCount();
}
}
copy the code
test results:
1
2
3
copy the code
static methods
A static method in Java is a method that belongs to a class, but is not considered an instance of that class; instead, a static method in Java can be easily created and implemented without the need for any instance calls. A static method can access any data member of the class, can perform any operation on the data member, or take any numeric value as input, although the member variable to be accessed should have a range of variables in the class, while the method can only be static.
public static void syntax_ex (String_name) {
Body of the program for execution.
}
copy the code
- public。 the access modifier for the class is public.
- static。 the scope of a method is static, which means that all member variables and return types are in a static scope.
- void。 this keyword in the syntax flow indicates that no return type is handled in the current method.
- syntax_ex。 the name of the class, which represents a static method as part of the currently defined class, followed by a string name.
- body。 it includes the entire core logic or business logic (if required in static mode).
if you use the static keyword on any method, it is called a static method.
- static methods belong to the class, not to objects that belong to the class.
- static methods can be called without creating an instance of a class.
- a static method can access a static data member and can change its value.
static method testing
what if we want to change the operation of the learning name? it is possible to declare a static method.
package com.yuzhou1su.RelearnJava;
class Student {
int stuId;
String name;
static String school = "HY No.1 High School";
static void changeSchool() {
school = "HY No.5 High School";
}
Student(int id, String n) {
stuId = id;
name = n;
}
void display() {
System.out.println("Student id:" + stuId + ", Name:" + name + " is from " + school);
}
}
public class TestVariable {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student.changeSchool();
Student s1 = new Student(001, "Karsa");
Student s2 = new Student(002, "Ellen");
s1.display();
s2.display();
}
}
copy the code
test results:
Student id:1, Name:Karsa is from HY No.5 High School
Student id:2, Name:Ellen is from HY No.5 High School
copy the code
how static methods work
- Static methods and instance methods are two methods in Java that create some confusion among programmers, but this is just a misunderstanding. There is a big difference between static and instance methods. Let’s see how static methods work in Java. A static method in Java is a method that resides in a class and can be accessed even if no object is created or instantiated. Any instance of the class can be accessed by appending the name of the class to the name of the method and passing parameters.
- it can be represented as . in addition, the composition of these methods has a goal, that is, the method should be shared with all member variables in the class and with everyone’s object, and its scope is defined by the modifier. these methods do not have any ability to overload; instead, they can be overloaded at compile time using the compiler’s static bindings, and whenever a programmer needs to share a common code snippet across all instances, objects, or member variables of a class, the static method becomes a savior because it creates a shared provision for all members, objects, and variables by creating a common static scope.
ClassName.methodName(arguments)
static
- all static fields of a class can be accessed using static fields as part of a static method of a class. in addition, static methods are also related to memory allocation functions and are also supported. it stores parts of static method fields and variables in memory with some permanently generated heap for associating values. memory allocation does not support the creation of objects as static method heaps, or instantiation is not supported by the methods themselves. but the next question is how static methods work by sharing and creating scopes of all members as part of a class.
Why the Java Main method is a static method
THIS IS BECAUSE THE OBJECT DOES NOT NEED TO CALL A STATIC METHOD. IF IT IS A NON-STATIC METHOD, THE JVM CREATES AN OBJECT AND THEN CALLS THE METHOD, WHICH CAUSES PROBLEMS WITH ADDITIONAL MEMORY ALLOCATION.main()
the main method does not operate on any objects, in fact, there are no objects when the program is started. the static main method executes and constructs the objects required by the program.
static constants
Static variables are used less often, but static constants are commonly used. For example, a static constant is defined in the Math class:
public class Math {
public static final double PI = 3.14159265358979;
}
copy the code
Then in the program, you can use Math.PI to access this constant.
summary
- Why do I need static variables in Java?
a: whenever we want to have a common property for all objects of a class, we use a class-level variable, a static variable.
When a class is loaded, this variable is loaded only once in memory. Because it is not defined by object in Java, it saves memory.
- Why is it not a good habit to create static variables in Java?
A: Static variables are common to all objects of a class. If you create a new object, you do not need to test the values of the static variables. Any code that uses static variables can be in any state. It can be within the new object or at the class level. Therefore, the scope of static variables is open-ended in Java classes.
if we want tighter control over the scope, the variable should be created at the object creation level.
similarly, defining static variables is not a good habit because they violate the principles of object-oriented programming.
- What is the purpose of static methods in Java?
A: Java provides the ability to create behaviors at the class level with static methods. Static methods are common to all objects of a class. We don’t need to create any objects of the class to call static methods. Therefore, it provides the convenience of not creating objects for invoking it.
static methods can also access and modify static data members. this also helps maintain behavior and state at the class level.
- Why is the main method marked as static in Java?
A: The main method in Java is marked as static, so the JVM can call it to start the program. If the main method is not static, which constructor will the Java process call?
Therefore, it is well-known convention in Java to mark the primary method as static. However, if we remove static, there will be ambiguity. The Java process may not know which class of method to call to start the program.
Therefore, this convention helps the Java process identify the startup code in the class that is passed as a parameter to the program of the Java process.
- under what circumstances do we use static blocks?
a: sometimes, there is a class with static member variables. these variables require some complex initialization. in this case, the static block can be used as a tool to initialize complex static member variables. static blocks execute even before main. sometimes, we can also replace static blocks with static class methods.
- is it possible to execute a program without defining the main() method?
A: No, starting with Java 7, you need the main() method to execute the program. In earlier versions of Java, there was a workaround available for static block execution. But now that gap has narrowed.
- what happens when the static modifier is not mentioned in the signature of the main method?
A: According to the Java specification, the main method must be marked as static. It only requires the parameters of an array of strings.
Programs can be compiled using non-static methods. But noSuchMethodError is given at the time of execution.
- What is the difference between static methods and instance methods in Java?
a: in general, you need to define behavior for classes that do not depend on object member variables. this behavior is captured through static methods. if there is behavior that depends on an object member variable, we do not mark it as static, but leave it as an instance method.
to call a static method, we don’t need to create an object. we only call it by the class name. but to call the instance method, we need to first create/get an object.
instance member variables cannot be accessed through static methods. but instance methods can call both instance variables and static variables.