2

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?

1
  • 7
    final is a reserved keyword in java. You can't use it as variable name Commented Jul 17, 2018 at 17:08

3 Answers 3

6

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?

Sign up to request clarification or add additional context in comments.

Comments

1

final is a keyword (reserved word) in java. You can't use keywords as a variable name. Try some another name.

Try this code :-

public class Test
{
  public static void main(String[] args)
  {
    String Final = new String("");
    Final = "sample";                 // final is keyword so use Final or some other names
    System.out.println(Final);
   }
 }

Output :-

sample

Comments

0

final is a reserved keyword in Java. Rename the varriable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.