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 static variable 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();
}
}

Try it yourself


Static Methods:

  • Definition: A static method 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);
}
}

Try it yourself


Static Block:

  • Definition: A static block 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();
}
}

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.