I used to declare a final String inside a constructor. Now I want to insert an if-statement in order to declare it differently if needed.
I used to do:
public Config(){
final String path = "<path>";
doSomething(path);
}
Now I'm trying
public Config(String mode){
if (mode = "1") {
final String path = "<path1>";
} else {
final String path = "<path2>";
}
doSomething(path);
}
Unfortunately path cannot be found now (cannot find symbol error) and I'm really lost with my research understanding this. The following works though, I just cannot explain... I must have a deep miss conception about something here.
public Config(String mode){
final String path;
if (mode = "1") {
path = "<path1>";
} else {
path = "<path2>";
}
doSomething(path);
}
Can you explain me what is going on here, what should I read about to get this.
Can you explain me what is going on here,
Snippet 2: path
declared in the scope of the if
statement. It's not accessible outside that if
.
Snippet 3: path
declared in the scope of the constructor. It's accessible within that constructor.
what should I read about to get this.
The JLS, of course: https://docs.oracle.com/javase/specs/jls/se12/html/jls-6.html#jls-6.3 It's quite complicated, find the right part, read it thoughtfully and go with
doSomething("1".equals(mode) ? "<path1>" : "<path2>");