Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a "global variable" in Java such that all classes can access it?

Tags:

java

here's my problem: I have multiple classes that are part of the same package and they need access to a certain file path

String filePath = "D:/Users/Mine/School/Java/CZ2002_Assignment/src/"

Rather than declaring the same Filepath in every single class, is it possible to simply have a "global" type of variable of this FilePath so that all classes can access it and I only need to declare and update it once.

Thanks

like image 601
Chrystle Soh Avatar asked Nov 12 '13 20:11

Chrystle Soh


3 Answers

If you declare it as

public class TestClass {
    public static String filePath="D:/Users/Mine/School/Java/CZ2002_Assignment/src/";
}

It will be accessible everywhere as TestClass.filePath

This can be useful (and your use case makes sense) but public static variables are a double edged sword and shouldn't be overused to just be able to access things which change from anywhere as they can break encapsulation and make your program less clear.

If the string will never be changed for annother you can add the keyword final, which will enforce this never changing behaviour as well as allowing the JVM to make additional efficiency enhancements (that you don't need to worry about)

like image 115
Richard Tingle Avatar answered Oct 10 '22 08:10

Richard Tingle


public class Test {
  public static final String FILE_PATH = "D:/Users/Mine/School/Java/CZ2002_Assignment/src/";
}

Call it this way: Test.FILE_PATH

Note the final because you only want to declare it once.

There also used to be a code convention to name final constants all uppercase, with components separated by underscore "_" characters. In the end, it's probably a matter of preference though.

like image 24
Blacklight Avatar answered Oct 10 '22 08:10

Blacklight


A word on final - if the string field is a constant variable, its value might be duplicated in many classes that reference it. We may want to avoid that because 1) the string is too big. 2) if the string is changed, we must recompile all classes that reference it.

We can avoid it by

public static final String filePath; 

static{ filePath="D:/Users/Mine/School/Java/CZ2002_Assignment/src/"; }

see http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.4

A variable of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28), is called a constant variable.

like image 22
ZhongYu Avatar answered Oct 10 '22 06:10

ZhongYu