Java static keyword
In this chapter you will learn:
- How to declare a static method and use it
- Syntax for static keyword
- Restrictions for Java static keyword
- Example - static methods
- Example - static variables
- How to use static initialization block
Description
A static class member can be used independently of any object of that class.
A static member that can be used by itself, without reference to a specific instance.
Syntax
Here shows how to declare static
method and static
variable.
/*from ww w. j a v a 2 s.co m*/
static int intValue;
static void aStaticMethod(){
}
Restrictions
Methods declared as static have several restrictions:
- They can only call other static methods.
- They must only access static data.
- They cannot refer to this or super in any way.
All instances of the class share the same static variable. You can declare a static block to initialize your static variables. The static block gets only called once when the class is first loaded.
Example
The following example shows a class that has a static method
public class Main {
static int a = 3;
static int b;
/*from w w w . ja va 2 s. co m*/
static void meth(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
public static void main(String args[]) {
Main.meth(42);
}
}
The output:
Example 2
The following example shows a class that has the static variables.
public class Main {
static int a = 3;
static int b;
}
We can reference the static variables defined above as follows:
Main.a
Example 3
The following example shows a class that has a static initialization block.
public class Main {
/* w w w. j av a 2 s .c o m*/
static int a = 3;
static int b;
static {
System.out.println("Static block initialized.");
b = a * 4;
}
}
Next chapter...
What you will learn in the next chapter:
- What is method overloading
- Note for Java Method Overload
- Example - How to overload methods with different parameters
- Example - How does automatic type conversions apply to overloading
Java Object
Java Object Reference Variable
Java Methods
Java Method Return
Java Method Parameters
Java Class Constructors
Java Default Constructor
Java Constructor Parameters
Java this Keyword
Java static keyword
Java Method OverloadJava Constructors Overload
Java Method Argument Passing
Java Method Recursion
Java Nested Class
Java Anonymous Classes
Java Local Classes
Java Member Classes
Java Static Member Classes
Java Class Variables
Java main() Method
Java Class Inheritance
Java super keyword
Java Method Overriding
Java Constructor in hierarchy
Polymorphism
Java final keyword
Java Abstract class
Java Class Access Control
Java Package
Java Packages Import
Java Interface
Java Interface as data type
Java interface as build block
Java instanceof operator
Java Source Files