How to create a global variable in Java so that all classes can access it?

here is my problem: I have several classes that are part of the same package and they need access to a specific file path

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

Instead of declaring the same file path in each individual class, is it possible to just have a β€œglobal” variable type of this FilePath so that all classes can access it, and I only need to declare and update it once.

thanks

+7
java
source share
4 answers

If you declare it as

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

It will be available everywhere as TestClass.filePath

This may be useful (and your use case makes sense), but public static variables are a double-edged sword and cannot be overestimated to be able to access things that change from anywhere, as they can break encapsulation and make your program less understandably.

If the string is never changed for annother, you can add the final keyword, which will ensure that this never-changing behavior is executed, and also allow the JVM to make additional performance improvements (which you need not worry about)

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

Name it like this: Test.FILE_PATH

Pay attention to final because you want to declare it only once.

It also used conditional code to denote the final constants of all uppercase letters with components separated by underscores "_". In the end, it's probably a matter of preference, though.

+9
source share

Final word - if the string field is a constant variable, its value can be duplicated in many classes that reference it. We can avoid this because 1) the string is too big. 2) if the string is changed, we must recompile all the classes that reference it.

We can avoid it

 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 String type, which is final and initialized by the expression of the compile-time constant (Β§15.28), is called a constant variable.

+1
source share
 public class One { public final static String FILEPATH = "D:/Users/Mine/School/Java/CZ2002_Assignment/src/"; }//class one public class Two { public static void main(String[] args) { //sample operation to access the filePath value System.out.println(One.FILEPATH); }//main }//class Two 

Note:

1) It is ideally better to use a configuration file / properties file - this way you can change the path without recompiling.
2) Avoid using static variables! (almost always) http://www.offthehill.org/articles/2011/06/03/java-static-variables-are-wrong-almost-always/

0
source share

All Articles