Global variables in java

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:

Create another class named CSVOutputMain.java to use Global variables.

Output:

Name
Gender

You can also create a interface and put public static final variables as global variables.

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.

When you run CSVOutputMain.java again, you will get same output.
Output:

Name
Gender

That’s all about Global variables in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *