What Is the Static Keyword in Java?
The term "static" in Java serves as a Non Access Modifier, indicating that a field, method, block, or nested class is associated with the type itself rather than any specific instance of the type. This distinction emphasizes the behavior or characteristic of the entity in question in relation to the entire class rather than individual instances.
When a member (field, method, block, or nested class) is declared as static, it implies that it is not tied to a specific object or instance of the class. Instead, it exists as a single entity shared by all instances of the class. The behavior or state represented by the static member remains consistent across all instances, allowing for a unified and class-wide representation.
For instance, a static field in a class would possess the same value across all instances, as any modification to the static field would be reflected universally. Similarly, a static method can be invoked without the need for object instantiation, as it pertains to the class itself and does not rely on any specific instance.
The Static keyword can be applied to:
- Static Method
- Static Variable
- Initialization Block
- Nested class
Java Static Method
In Java, static methods can be called without creating an object of the class.
In normal case we call a method from the instance of that class.
ExampleWhen we create a static method inside a class, methods can be called without creating an object of class.
ExampleIn Java, a static method is limited to accessing only the static variables of a class and invoking solely the static methods of the class. Typically, static methods serve as utility methods intended for external usage by other classes without the requirement of instantiating an object. These class methods often serve as globally accessible functions within Java programs, providing functionality that transcends specific instances. An illustrative example of class methods is found in the java.lang.Math package, where they play a prominent role. As static methods do not pertain to any particular instance, they are unable to reference instance members; they can solely refer to other static members.
Features of static method
- A static method is a method which belongs to the class and not to the instance(object)
- A static method can be invoked without the need for creating an instance of a class
- A static method can call only other static methods and cannot call a non-static method from it
- A static method can access static data member and can change the value of it
- A static method cannot refer to this or super keywords in anyway
Java Static variable
A static variable in Java is associated with the class itself rather than any specific instance (object) of that class. It is initialized only once at the beginning of the program's execution and remains unchanged throughout its runtime. This single instance is shared among all instances of the class, and it can be accessed directly using the class name without the need for an object reference. One common application of static variables is to define constant values that are inherent to the class.
For instance, consider the declaration of a static variable: private static int stc = 0;. If this variable is incremented (stc++) in one instance of the class, the change will be reflected across all instances. Consequently, the value of stc will become 1 in all instances, demonstrating the shared nature of static variables.
By utilizing static variables, developers can establish class-level data that is accessible globally and consistent across all instances. This enables the storage of information that pertains to the class as a whole rather than individual objects.
Initialization Block
The static initializer in Java is a block of code denoted by the static {} construct within a class. This code block is executed only once, prior to the invocation of the class's constructor or main method. It serves as a class initializer, responsible for performing any necessary setup or initialization tasks specific to the class itself.
The static initializer block is denoted by the keyword static, indicating that it pertains to the class as a whole rather than any specific instance. This allows it to initialize static variables or perform other operations that are independent of object creation.
It is important to note that the static initializer block is executed in the order they appear in the class, ensuring proper sequencing of initialization tasks. This block is typically used to initialize static variables, set up static data structures, or perform any other one-time initialization steps required by the class.
In contrast, an instance initializer block is similar in structure but does not have the static modifier. It is executed when an instance of the class is created, before the constructor is called. Instance initializer blocks are useful when there is shared initialization logic required by multiple constructors of the class.
It's automatically invoked when the class is loaded. A static block executes once in the life cycle of any program, and there's no other way to invoke it
From Java 7 , however, this does not work anymore, even though it compiles, the following error will appear when you try to execute it:
Nested class
Nested classes are classified into two categories: static and non-static. When a nested class is declared with the static modifier, it is known as a static nested class.
A static nested class is a nested class that exists independently of any instance of the enclosing class. It is essentially a top-level class that is nested within another class for organizational purposes. Unlike non-static nested classes (also known as inner classes), a static nested class does not have direct access to the instance variables and methods of the enclosing class.
Static nested classes are typically used when there is a logical relationship between the nested class and the enclosing class, but the nested class does not require access to the instance-specific members of the enclosing class. They provide a way to logically group classes together, enhancing code organization and encapsulation.
To use a static nested class, you can access it using the enclosing class name, followed by the nested class name. For example, if a class named Outer contains a static nested class named Nested, you can instantiate Nested using the following syntax: Outer.Nested nestedObject = new Outer.Nested();
Static nested classes have their own separate namespace and can contain static members, such as static fields, static methods, and static nested classes of their own. They can be accessed independently without requiring an instance of the enclosing class.
ExampleIn order to create an object for the static nested class, use the following syntax:
The key difference between them, you can't create an NonStaticNestedClass instance without an OuterClass whereas you can create an StaticNestedClass object independently.
Conclusion
The static keyword in Java is used to define class-level members that are associated with the class itself rather than individual instances, allowing them to be accessed without the need for object instantiation.
- Java Interview Questions-Core Faq - 1
- Java Interview Questions-Core Faq - 2
- Java Interview Questions-Core Faq - 3
- What are the major features of Java programming
- Difference between Java and JavaScript?
- What is the difference between JDK and JRE?
- What gives Java its 'write once and run anywhere' nature?
- What is JVM and is it platform independent?
- What is Just-In-Time (JIT) compiler?
- What is the garbage collector in Java?
- What is NullPointerException in Java
- Difference between Stack and Heap memory in Java
- How to set the maximum memory usage for JVM?
- What is numeric promotion?
- Why do we need Generic Types in Java?
- What are final variables in Java?
- How Do Annotations Work in Java?
- How do I use the ternary operator in Java?
- What is instanceof keyword in Java?
- How ClassLoader Works in Java?
- What are fail-safe and fail-fast Iterators in Java
- What are method references in Java?
- "Cannot Find Symbol" compile error
- Difference between system.gc() and runtime.gc()
- How to convert TimeStamp to Date in Java?
- Does garbage collection guarantee that a program will not run out of memory?
- How setting an Object to null help Garbage Collection?
- How do objects become eligible for garbage collection?
- How to calculate date difference in Java
- Difference between Path and Classpath in Java
- Is Java "pass-by-reference" or "pass-by-value"?
- Difference between static and nonstatic methods java
- Why Java does not support pointers?
- What is a package in Java?
- What are wrapper classes in Java?
- What is singleton class in Java?
- Difference between Java Local Variable, Instance Variable and a Class Variable?
- Can a top level class be private or protected in Java
- Are Polymorphism , Overloading and Overriding similar concepts?
- How to Use Locks in Java
- Why Multiple Inheritance is Not Supported in Java
- Why Java is not a pure Object Oriented language?
- Static class in Java
- Difference between Abstract class and Interface in Java
- Why do I need to override the equals and hashCode methods in Java?
- Why does Java not support operator overloading?
- What’s meant by anonymous class in Java?
- Static Vs Dynamic class loading in Java
- Why am I getting a NoClassDefFoundError in Java?
- How to Generate Random Number in Java
- What's the meaning of System.out.println in Java?
- What is the purpose of Runtime and System class in Java?
- The finally Block in Java
- Difference between final, finally and finalize
- What is try-with-resources in java?
- What is a stacktrace?
- Why String is immutable in Java ?
- What are different ways to create a string object in Java?
- Difference between String and StringBuffer/StringBuilder in Java
- Difference between creating String as new() and literal | Java
- How do I convert String to Date object in Java?
- How do I create a Java string from the contents of a file?
- What actually causes a StackOverflow error in Java?
- Why is char[] preferred over String for storage of password in Java
- What is I/O Filter and how do I use it in Java?
- Serialization and Deserialization in Java
- Understanding transient variables in Java
- What is Externalizable in Java?
- What is the purpose of serialization/deserialization in Java?
- What is the Difference between byte stream and Character streams
- How to append text to an existing file in Java
- How to convert InputStream object to a String in Java
- What is the difference between Reader and InputStream in Java
- Introduction to Java threads
- What is synchronization Java?
- Static synchronization Vs non static synchronization in Java
- Deadlock in Java with Examples
- What is Daemon thread in Java
- Difference between implements Runnable and extends Thread in Java
- What is the volatile keyword in Java
- What are the basic interfaces of Java Collections Framework
- What are the differences between ArrayList and Vector in Java
- What is the difference between ArrayList and LinkedList?
- What is the difference between List and Set in Java
- Difference between HashSet and HashMap in Java
- Difference between HashMap and Hashtable in Java?
- How does the hashCode() method of java works?
- Difference between capacity() and size() of Vector in Java
- What is a Java ClassNotFoundException?
- How to fix java.lang.UnsupportedClassVersionError