What is the function of java static keyword?
In Java, static is a modifier, used to modify class member methods and class member variables. In addition, static code blocks can be written to optimize program performance; methods or variables modified by the static keyword are not It needs to rely on the object for access. As long as the class is loaded, it can be accessed through the class name.

(Recommended tutorial: java introductory tutorial)
1. Characteristics of the static keyword:
There is this passage on page P86 of "Java Programming Thoughts":
"A static method is a method without this. Non-static methods cannot be called inside a static method, and the reverse is possible. And You can call the static method only through the class itself without creating any objects. This is actually the main purpose of the static method."
Although this paragraph only explains the static method Special feature, but you can see the basic function of the static keyword. In short, the description in one sentence is:
It is convenient to call (method/variable) without creating an object.
Obviously, methods or variables modified by the static keyword do not need to rely on objects for access. As long as the class is loaded, it can be accessed through the class name.
static is a modifier used to modify class member methods and class member variables. In addition, static code blocks can be written to optimize program performance;
(Video tutorial recommendation: java video tutorial)
1. Static modified member method
Static modified methods are generally called static methods. Since static methods can be accessed without relying on any object, so for For static methods, there is no this, because it is not attached to any object. Since there is no object, there is no this. And due to this feature, non-static member variables and non-static member methods of the class cannot be accessed in static methods, because non-static member methods/variables must rely on specific objects before they can be called.
But it should be noted that although non-static member methods and non-static member variables cannot be accessed in static methods, static member methods/variables can be accessed in non-static member methods. For example:

#In the above code, since the print2 method exists independently of the object, it can be called directly with the class name.
If non-static methods/variables can be accessed in static methods, then if there is the following statement in the main method:
MyObject.print2();
At this time, there are no objects, and str2 does not exist at all, so a contradiction will occur. The same is true for methods. Since you cannot predict whether non-static member variables are accessed in the print1 method, accessing non-static member methods in static member methods is also prohibited.
For non-static member methods, there is obviously no restriction on accessing static member methods/variables.
Therefore, if you want to call a method without creating an object, you can set this method to static. Our most common static method is the main method. As for why the main method must be static, it is now clear. Because the program does not create any objects when executing the main method, it can only be accessed through the class name.
2. Static modified member variables
Static modified variables are also called static variables. The difference between static variables and non-static variables is that static variables are shared by all objects and there is only one in the memory. A copy that will be initialized if and only if the class is first loaded. Non-static variables are owned by objects and are initialized when the object is created. There are multiple copies, and the copies owned by each object do not affect each other.
The initialization order of static member variables is initialized in the order defined.
3. Static modified code block
Another important role of the static keyword is to form a static code block to optimize program performance. A static block can be placed anywhere in a class, and there can be multiple static blocks in a class. When a class is loaded for the first time, each static block will be executed in the order of the static blocks, and will only be executed once.
Static block can optimize program performance because of its characteristics: it will only be executed once when the class is loaded for the first time. As follows:
class Person{
private Date birthDate;
public Person(Date birthDate) {
this.birthDate = birthDate;
}
boolean isBornBoomer() {
Date startDate = Date.valueOf("1946");
Date endDate = Date.valueOf("1964");
return birthDate.compareTo(startDate)>=0 && birthDate.compareTo(endDate) < 0;
}
}isBornBoomer is used to determine whether a person was born between 1946 and 1964. Every time isBornBoomer is called, two objects, startDate and birthDate, will be generated, causing a waste of space. If you change It will be more efficient as follows:
class Person {
private Date birthDate;
private static Date startDate, endDate;
static {
startDate = Date.valueOf("1946");
endDate = Date.valueOf("1964");
}
public Person(Date birthDate) {
this.birthDate = birthDate;
}
boolean isBornBoomer() {
return birthDate.compareTo(startDate) >= 0 && birthDate.compareTo(endDate) < 0;
}
}Therefore, many initialization operations that only need to be performed once are placed in static code blocks.
二、static关键字的误区
1. 与C/C++中的static不同,Java中的static关键字不会影响到变量的变量或者方法的作用域。在Java中能够影响到访问权限的只有private、public、protected这几个关键字。示例如下:

提示错误,说明static关键字并不会改变变量和方法的访问权限。
2. 虽然对于静态方法来说没有this,但是我们在非静态方法中能够通过this访问静态方法成员变量。如下:
public class Test {
static int value = 11;
public static void main(String[] args) {
new Test().printValue();
}
private void printValue() {
int value = 22;
System.out.println(this.value);
}
}输出的结果是:11
这里的this表示的是当前对象,那么通过new Test()来调用printValue的话,当前对象就是通过new Test()生成的对象。而static变量是被对象所享有的,因此在printValue中的this.value的值毫无疑问是11。在printValue方法内部的value是局部变量,根本不可能与this关联,所以输出11。需要记住的是:静态成员变量虽然独立于对象,但是不代表不可以通过对象去访问,所有的静态方法和静态变量都可以通过对象访问(只要权限足够)。
3. 在C/C++中static关键字是可以作用于局部变量的,但是在Java中是不允许使用static修饰局部变量的。这是Java语法的规定。
更多编程相关知识,请访问:编程教学!!
The above is the detailed content of What is the function of java static keyword?. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
What is a deadlock in Java and how can you prevent it?
Aug 23, 2025 pm 12:55 PM
AdeadlockinJavaoccurswhentwoormorethreadsareblockedforever,eachwaitingforaresourceheldbytheother,typicallyduetocircularwaitcausedbyinconsistentlockordering;thiscanbepreventedbybreakingoneofthefournecessaryconditions—mutualexclusion,holdandwait,nopree
How to use Optional in Java?
Aug 22, 2025 am 10:27 AM
UseOptional.empty(),Optional.of(),andOptional.ofNullable()tocreateOptionalinstancesdependingonwhetherthevalueisabsent,non-null,orpossiblynull.2.CheckforvaluessafelyusingisPresent()orpreferablyifPresent()toavoiddirectnullchecks.3.Providedefaultswithor
Java Persistence with Spring Data JPA and Hibernate
Aug 22, 2025 am 07:52 AM
The core of SpringDataJPA and Hibernate working together is: 1. JPA is the specification and Hibernate is the implementation, SpringDataJPA encapsulation simplifies DAO development; 2. Entity classes map database structures through @Entity, @Id, @Column, etc.; 3. Repository interface inherits JpaRepository to automatically implement CRUD and named query methods; 4. Complex queries use @Query annotation to support JPQL or native SQL; 5. In SpringBoot, integration is completed by adding starter dependencies and configuring data sources and JPA attributes; 6. Transactions are made by @Transactiona
Java Cryptography Architecture (JCA) for Secure Coding
Aug 23, 2025 pm 01:20 PM
Understand JCA core components such as MessageDigest, Cipher, KeyGenerator, SecureRandom, Signature, KeyStore, etc., which implement algorithms through the provider mechanism; 2. Use strong algorithms and parameters such as SHA-256/SHA-512, AES (256-bit key, GCM mode), RSA (2048-bit or above) and SecureRandom; 3. Avoid hard-coded keys, use KeyStore to manage keys, and generate keys through securely derived passwords such as PBKDF2; 4. Disable ECB mode, adopt authentication encryption modes such as GCM, use unique random IVs for each encryption, and clear sensitive ones in time
LOL Game Settings Not Saving After Closing [FIXED]
Aug 24, 2025 am 03:17 AM
IfLeagueofLegendssettingsaren’tsaving,trythesesteps:1.Runthegameasadministrator.2.GrantfullfolderpermissionstotheLeagueofLegendsdirectory.3.Editandensuregame.cfgisn’tread-only.4.Disablecloudsyncforthegamefolder.5.RepairthegameviatheRiotClient.
How to use the Pattern and Matcher classes in Java?
Aug 22, 2025 am 09:57 AM
The Pattern class is used to compile regular expressions, and the Matcher class is used to perform matching operations on strings. The combination of the two can realize text search, matching and replacement; first create a pattern object through Pattern.compile(), and then call its matcher() method to generate a Matcher instance. Then use matches() to judge the full string matching, find() to find subsequences, replaceAll() or replaceFirst() for replacement. If the regular contains a capture group, the nth group content can be obtained through group(n). In actual applications, you should avoid repeated compilation patterns, pay attention to special character escapes, and use the matching pattern flag as needed, and ultimately achieve efficient
Edit bookmarks in chrome
Aug 27, 2025 am 12:03 AM
Chrome bookmark editing is simple and practical. Users can enter the bookmark manager through the shortcut keys Ctrl Shift O (Windows) or Cmd Shift O (Mac), or enter through the browser menu; 1. When editing a single bookmark, right-click to select "Edit", modify the title or URL and click "Finish" to save; 2. When organizing bookmarks in batches, you can hold Ctrl (or Cmd) to multiple-choice bookmarks in the bookmark manager, right-click to select "Move to" or "Copy to" the target folder; 3. When exporting and importing bookmarks, click the "Solve" button to select "Export Bookmark" to save as HTML file, and then restore it through the "Import Bookmark" function if necessary.
'Java is not recognized' Error in CMD [3 Simple Steps]
Aug 23, 2025 am 01:50 AM
IfJavaisnotrecognizedinCMD,ensureJavaisinstalled,settheJAVA_HOMEvariabletotheJDKpath,andaddtheJDK'sbinfoldertothesystemPATH.RestartCMDandrunjava-versiontoconfirm.


