What Is the Static Keyword in Java?
Static is a Non Access Modifier. It means that something (a field, method, block or nested class) is related to the type rather than any particular instance of the type. 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. Example
public class TestClass {
public static void main(String[] args) {
TestClass tc = new TestClass();//create a class instance
tc.ShowMessage(); //call method using instance
}
void ShowMessage() {
System.out.println("Here is the message");
}
}
When we create a static method inside a class, methods can be called without creating an object of class.
Example
public class TestClass {
public static void main(String[] args) {
ShowMessage(); //calling without creting instance
}
static void ShowMessage() {
System.out.println("Here is the message using static");
}
}
In Java, a static method can access only static variables of class and invoke only static methods of the class. Usually static methods are utility methods that we want to expose to be used by other classes without the need of creating an instance . Class methods are often used to provide global functions for Java programs. For example, Methods in the java.lang.Math package are Class methods. Since static methods also do not belong to a specific instance, they can't refer to instance members .The static members can only refer to 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 is one that's associated with a class, not instance (object) of that class. They are initialized only once , at the start of the execution . A single copy to be shared by all instances of the class and it can be accessed directly by the class name and doesn't need any object. One common use of static is to create a constant value that's attached to a class.For example, if you have a variable: private static int stc = 0; and you increment it (stc++) in one instance, the change will be reflected in all instances. stc will now be 1 in all instances.
Initialization Block
The static initializer is a static {} block of code inside java class, and run only one time before the constructor or main method is called. The code block with the static modifier signifies a class initializer; without the static modifier the code block is an instance initializer.
public class TestClass {
static {
System.out.println("Hello before main");
}
}
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:
Main class should contain method: public static void main (String[] args).
Nested class
Nested classes in Java are divided into two categories: static and non-static . Nested classes that are declared static are simply called static nested classes. Example
public class OuterClass {
public static class StaticNestedClass {
}
public class NonStaticNestedClass {
}
}
In order to create an object for the static nested class, use the following syntax:
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
The key difference between them, you can't create an NonStaticNestedClass instance without an OuterClass whereas you can create an StaticNestedClass object independently.
Difference between Static Nested Class and Nonstatic Nested class
A Static Nested Class can't access enclosing class instance and invoke methods on it, so should be used when the nested class doesn't require access to an instance of the enclosing class . A common use of static nested class is to implement a components of the outer object.A Nonstatic Nested class is implicitly associated with the enclosing instance of the containing class, this means that it is possible to invoke methods and access variables of the enclosing instance. One common use of a nonstatic nested class is to define an Adapter class.
Related Topics
- Java Interview Questions-Core Faq - 1
- Java Interview Questions-Core Faq - 2
- Java Interview Questions-Core Faq - 3
- Important features of Java
- 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?
- "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
- Is Java "pass-by-reference" or "pass-by-value"?
- Difference between static and nonstatic methods java
- Why Java does not support pointers?
- What is package in Java?
- What are wrapper classes?
- 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?
- Why can't a Java class be declared as static?
- 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 integers within a specific range in Java
- What's the meaning of System.out.println in Java?
- What is the purpose of Runtime and System class?
- What is finally block in Java?
- What is difference between final, finally and finalize?
- What is try-with-resources in java?
- What is a stacktrace?
- What is the meaning of immutable in terms of String?
- What are different ways to create a string object in Java?
- Difference between String and StringBuffer/StringBuilder in Java
- What is the difference between creating String as new() and literal?
- 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
- Read/convert an InputStream 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
- Java Thread Deadlock Tutorial
- 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