简体   繁体   中英

How to declare a private integer?

I am getting an

"Illegal start of expression"

error in the following code at the location marked by a comment. How can I correct this error?

public static void main(String[] args) {
    private int w=5; //Problem here"Illegal start of expression"//
    private int Pw=0xb7e15163, Qw=0x9e3779b9;
    private int[] S;
  • Firstly, a point on question title: declaring private integer in netbeans. Netbeans is an IDE and you are actually trying to declare private integer in Java source code , this is happening irrespective of IDE's used.
  • Secondly, what is private keyword in Java? It is a access level modifier. And access level modifiers determine whether other classes can use a particular field or invoke a particular method. So, it is getting applied to members of a class - instance fields, instance methods.
  • In your case,

     public static void main(String[] args) { // TODO code application logic here private int w=5; 
  • Variable w is getting declared and defined within the method main . And main method is within your class. So, variable w does not qualify to become a member of the class . It is a local variable which has scope within main method. So, access level modifier cannot be applied to variable w which has been defined within method main() . That is the reason why you get "Illegal start of expression" . Within a method, it is not syntactically/semantically correct to specify access to a variable.

private variables have access modifiers because they are instance fields. They go outside the method. You'll need an instance to use them, and you'd normally need accessor and mutator methods (because they're private , only this class can access them; that does include main ) -

private int w=5; 
private int Pw=0xb7e15163, Qw=0x9e3779b9;
private int[] S;

public static void main(String[] args) {
    ThisClass tc = new ThisClass();
    System.out.println(tc.w);
}

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