I am trying to compile the following code:
public class Test {
public static void main(String[] args) {
String final = new String("");
final = "sample";
System.out.println(final);
}
}
Apparently, the compiler shows me the following errors:
Test.java:5: error: not a statement
String final = new String("");
^
Test.java:5: error: ';' expected
String final = new String("");
^
Test.java:5: error: illegal start of type
String final = new String("");
^
Test.java:6: error: illegal start of type
final = "sample";
^
Test.java:7: error: illegal start of expression
System.out.println(final);
^
Test.java:7: error: illegal start of type
System.out.println(final);
^
I've tried replacing String final = new String("");
with String final;
but the compiler is still showing these errors. Any idea what might cause this?
final
is the reserved Java keyword. You can't use it as a variable name. Read more about the naming of variables in Java. Do this:
String string = new String("");
string = "sample";
System.out.println(string);
However, this is possible, since it still respects the rule to assign the value once:
final String string;
string = "sample";
System.out.println(string);
On the other hand, if you mean to make String final
, not as a variable name, but as characteristics, you have to place it to the left side of String definition. However, the second line would not compile because you can't modify the variable marked as final
.
final String string = new String("");
string = "sample"; // not possible, string already has a value
System.out.println(string);
The behavior of variable which is final
is that you can initialize it only once. Read more at How does the “final” keyword in Java work?