简体   繁体   中英

Can't create a public static final String in java

This code:

public class CommandPrompt {
  public static void main(String[] args) {
    public static final String prompt = System.getProperty("user.name")+">";
      System.out.println(prompt);
    }
  }

Returns this error message:

CommandPrompt.java:5: error: illegal start of expression
public static final String prompt = System.getProperty("user.name")+">";
^
CommandPrompt.java:5: error: illegal start of expression
public static final String prompt = System.getProperty("user.name")+">";
       ^
CommandPrompt.java:5: error: ';' expected
public static final String prompt = System.getProperty("user.name")+">";
             ^
3 errors

I have seen public static final String been used before, why can't I use it here?

Explanation

You can't use public and static inside a method.
Both are reserved for class attributes: public is an access modifier and static declares a class scoped variable.

Correction

public class CommandPrompt {
    public static void main(String[] args) {
      final String prompt = System.getProperty("user.name")+">";
      System.out.println(prompt);
    }
}

or

public class CommandPrompt {
    public static final String prompt = System.getProperty("user.name")+">";

    public static void main(String[] args) {
      System.out.println(prompt);
    }
}

Related question

You cannot declare variables as public or static within a method. Either remove them or move it out of the method block to turn it into a field

Static variables cannot be declared in a method.

It should be delcared in the class level.

Please try

public class CommandPrompt {

public static  String prompt;

public static void main(String[] args) {

prompt=System.getProperty("user.name")+">";

System.out.println(prompt);

}

}

It's because you can only create class level variable inside your class, you don't say, but outside of a method :)

public class CommandPrompt {
 public static final String prompt = System.getProperty("user.name")+">";
 public static void main(String[] args) {
  System.out.println(prompt);
 }
}

Something like that should work. See this tutorial for more information

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM