Search code examples
javastaticpathfinal

Static String path in Java


I've got only a main class in my small program and it's using a lot of path. As they will not change while the program is running, I think I can put static in their declaration but not sure for the final. Moreover, I'm not sure where is the best place to declare my paths. Is it in the main class or just before?

Here's an example of my code:

package classtest;

public class ClassTest {
    // Should I put the path here?
    public static void main(String[] args) {
        String dirPath = "C:/Users/test1/"; 
        String pathOut = "C:/Users/stats.csv"; 
        // or here?
    }   
}

Solution

  • You can do this kind of refactoring:

    public class ClassTest {
        // Specify a base path for all paths to be used
        public static final String BASE_PATH = "C:/Users";
        // 1. If these paths will be used in several methods, declare them here
        public static final String dirPath = BASE_PATH + "/test1/"; 
        public static final String pathOut = BASE_PATH + "/stats.csv"; 
    
        public static void main(String[] args) {
            // 2. If those paths will be used in the main method only, declare them here
            final String dirPath = BASE_PATH + "/test1/"; 
            final String pathOut = BASE_PATH + "/stats.csv"; 
        }   
    }
    

    Static members of a class should be declared outside the scope of any class method.