Java – Global variable examples

In Java, there is no global keyword, but we can use public static variable to referring a global variable.

For example :

MagicUtils.java

package com.mkyong.example;

public class MagicUtils {

    public static final String NAME = "mkyong"; // global
    public static final int LUCKY_NUMBER = 7;   // global

}
JavaExample.java

package com.mkyong.example;

public class JavaExample {

    public static void main(String[] args) {

        System.out.println(MagicUtils.NAME);
        System.out.println(MagicUtils.LUCKY_NUMBER);

    }

}

Output


mkyong
7

References

  1. Java doc – Static keyword

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar