Thursday 2 April 2020

How to define global variables in Java?

Using ‘public’ and ‘static’ keywords, you can define global variables.

public class GlobalVariable {
    public static int readCount = 0;
    public static int writeCount = 0;
    public static int appAccessCount = 0;
}

You can access the global variable using classname.

Example
'GlobalVariable.readCount'

If you want to define global constants, you can define an interface and define the variables inside the interface.

public interface GlobalConstants {
    float PI = 3.14F;
    float ERROR_RATE = 0.001f;
}

Note:
Variables in interface are ‘public’ ‘static’ ‘final’ by default.

You may like

No comments:

Post a Comment