Advertisement
Google Ad Slot: content-top
Java Static Keyword
In Java, the static keyword is used for memory management and applies to variables, methods, and blocks. Anything declared static belongs to the class rather than any specific object.
Static Variables:
- Definition: A
staticvariable is shared among all objects of a class. It belongs to the class and is initialized only once, at the time of class loading. - Access: Can be accessed directly using the class name (
ClassName.variableName). - Use Case: To share common data between all objects.
Syntax:
class ClassName {
static DataType variableName;
}
Example
class Mobile{
String brand;
static String name;
public void show() {
System.out.println(brand+" : "+price+" : "+name);
}
}
public class Demo {
public static void main(String[] args)
{
Mobile obj1=new Mobile();
obj1.brand="Apple";
Mobile.name="SmartPhone";
Mobile obj2=new Mobile();
obj2.brand="Samsung";
Mobile.name="phone";
obj1.show();
obj2.show();
}
}
Static Methods:
- Definition: A
staticmethod belongs to the class and does not require an object to be called. - Access: Can be called using the class name (
ClassName.methodName()).
Syntax:
class ClassName {
static ReturnType methodName(Parameters) {
// Method logic
}
}
Example
class Mobile{
String brand;
static String name;
public void show() {
System.out.println(brand+" : "+name);
}
public static void show1(Mobile obj)
{
System.out.println(obj.brand+" : "+obj.name);
}
}
public class Main {
public static void main(String[] args) {
Mobile obj1=new Mobile();
obj1.brand="Apple";
Mobile.name="SmartPhone";
Mobile obj2=new Mobile();
obj2.brand="Samsung";
Mobile.name="Phone";
obj1.show();
obj2.show();
Mobile.show1(obj1);
}
}
Static Block:
- Definition: A
staticblock is used to initialize static variables or execute code during class loading. - Execution: Runs once, when the class is loaded into memory.
- Order: Static blocks execute before the
main()method or any static method.
Syntax:
class ClassName {
static {
// Static block logic
}
}
Example
class Mobile{
static {
System.out.println("in static block");
}
public Mobile() {
System.out.println("in constructor");
}
}
public class Main {
public static void main(String[] args) {
Mobile obj1=new Mobile();
}
}