[Updated, sorry about the change but now to the real problem] I cannot include try-catch-loop there for the exception from the method getCanonicalPath(). I tried to solve the problem earlier with method and then declaring the value there. The problem is that it is Final, I am unable to change it. So how to have startingPath as "public static final".
$ cat StartingPath.java
import java.util.*;
import java.io.*;
public class StartingPath {
public static final String startingPath = (new File(".")).getCanonicalPath();
public static void main(String[] args){
System.out.println(startingPath);
}
}
$ javac StartingPath.java
StartingPath.java:5: unreported exception java.io.IOException; must be caught or declared to be thrown
public static final String startingPath = (new File(".")).getCanonicalPath();
^
1 error
Just initialize it in the static block(the variable is final). You can't catch exceptions on declaring a variable.
You can provide a static method to initialize your static variable:
Or you can initialize your variable in a static block:
EDIT: In this case your variable is
static
so there is no way to declare the exception thrown. Just for reference, if the variable is non-static
you could do this by declaring the thrown exception in the constructor, like so:You are missing the type of your variable, it should be
The name is fine; you forgot to declare the type.
Fixing that, you of course realize the harder problem of how to deal with the possible
IOException
andstartingPath
beingfinal
. One way is to use astatic
initializer:JLS 8.7 Static Initializers
Another way is to use a
static
method (see Kevin Brock's answer). That approach actually results in better readability, and is the recommended approach by Josh Bloch in Effective Java.See also
You are missing the type of variable
startingPath