Search code examples
javafinalmain-method

error: illegal start expression. when placing a final string` statement in the `public static void main` method


I have just started learning Java a few weeks ago. I'm trying to learn the key word final in java language. I wrote a final string statement in the public static void main method. However, the IDE is displaying the error: illegal start expression. However, the IDE did not provide any additional information. Because I'm relatively new to Java, I am unable to understand why this is happening. Could someone please explain the reason to me?

public static void main(String[] args) {
    private final String s1 = "hello world";
}

Solution

  • There is no such thing as a private field within a method, and this only makes sense within class scope, not method scope. Get rid of the private modifier.

    To get a handle on this, ask yourself, what would it mean? The variable s1 is local to he method regardless and so cannot be seen outside of the method scope, so adding a private modifier would be senseless as it wouldn't change anything.