In this post, we will see how to define global variables in java.
Unlike C/C++, there are no standard global variables in java but you can still define global variables that can be used across all classes.
Global variables
are those variables that can be accessed across all the classes. Java does not support global variables explicitly, you need to create a class and global variables can be part of this class.
You can use static variables to create global variables. static variables belong to class and can be accessed across all instances of the class.
Let’s see this with the help of example:
1 2 3 4 5 6 7 8 9 |
package org.arpit.java2blog; public class StringConstants { public static String HEADER_NAME ="Name"; public static String HEADER_GENDER ="Gender"; } |
Create another class named CSVOutputMain.java
to use Global variables.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package org.arpit.java2blog; public class CSVOutputMain { public static void main(String[] args) { System.out.println(StringConstants.HEADER_NAME); System.out.println(StringConstants.HEADER_GENDER); } } |
Output:
Gender
You can also create a interface and put public static final variables as global variables.
1 2 3 4 5 6 7 8 9 |
package org.arpit.java2blog; public interface StringConstants { String HEADER_NAME ="Name"; String HEADER_GENDER ="Gender"; } |
As you can see, you don’t have to use public static final with HEADER_NAME
and HEADER_GENDER
as they are public static final by default. You can use public static final explictly if you want.
1 2 3 4 5 6 7 8 9 |
package org.arpit.java2blog; public interface StringConstants { public static final String HEADER_NAME ="Name"; public static final String HEADER_GENDER ="Gender"; } |
When you run CSVOutputMain.java
again, you will get same output.
Output:
Gender
That’s all about Global variables in java.