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?

4 Answers 4

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

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

Comments

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

Comments

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

}

}

Comments

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

1 Comment

class-level (static) and instance-level (non-static)

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.