DEV Community

silambarasan rajendran
silambarasan rajendran

Posted on

2

Day-15: Static vs Non-Static Methods, Global vs Local Variables in Java

Static Keyword in Java:
The static keyword in Java is used to create class-level variables and methods. These members are shared across all instances of the class, meaning they are class-wide and not tied to individual object instances.

Static Variables (Fields)
Static variables, also referred to as class variables or fields, are shared among all instances of a class. These variables are initialized only once and are common to every object of that class.

Static Methods
Static methods can be called without creating an instance of the class. These methods can only access other static members (variables and methods) within the class.

Example code for Static and Local Variables in Java:

public class Clock {
    // Static
    static String timezone = "IST";
    static void setAlarm() {
        System.out.println(" Alarm set for 7:00 AM!");
    }

    // Non-static - decleartion
    int hours;
    int minutes;

    void displayTime() {
        String greeting; // Local variable
        if (hours < 12) greeting = "Good morning!";
        else if (hours < 18) greeting = "Good afternoon!";
        else greeting = "Good evening!";

        System.out.println(greeting + " Current time: " + hours + ":" + minutes + " " + timezone);
    }

    public static void main(String[] args) {
        // Static access
        System.out.println("Timezone: " + Clock.timezone);
        Clock.setAlarm();

        // Time objects
        Clock t1 = new Clock();
        t1.hours = 9;
        t1.minutes = 30;


        // Non-static calls
        t1.displayTime();
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Output:

Image description

Note: The document formatting and structure were assisted by ChatGPT.

--------------------------- End of the Blog -------------------------------

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Dive into this informative piece, backed by our vibrant DEV Community

Whether you’re a novice or a pro, your perspective enriches our collective insight.

A simple “thank you” can lift someone’s spirits—share your gratitude in the comments!

On DEV, the power of shared knowledge paves a smoother path and tightens our community ties. Found value here? A quick thanks to the author makes a big impact.

Okay