0

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?

Jack Pettersson
  • 1,606
  • 4
  • 17
  • 28

4 Answers4

5

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

Community
  • 1
  • 1
NiziL
  • 5,068
  • 23
  • 33
1

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

Dragondraikk
  • 1,659
  • 11
  • 21
1

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);

}

}
Nithin Varghese
  • 258
  • 3
  • 12
0

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

damus4
  • 148
  • 2
  • 7