Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare a static variable inside the Main method?

Can we declare Static Variables inside Main method? Because I am getting an error message:

Illegal Start of Expression
like image 595
Priti Avatar asked Jul 31 '10 15:07

Priti


2 Answers

Obviously, no, we can't.

In Java, static means that it's a variable/method of a class, it belongs to the whole class but not to one of its certain objects.

This means that static keyword can be used only in a 'class scope' i.e. it doesn't have any sense inside methods.

like image 133
Roman Avatar answered Nov 07 '22 18:11

Roman


You can use static variables inside your main method (or any other method), but you need to declare them in the class:

This is totally fine:

public Class YourClass {
  static int someNumber = 5;

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

This is fine too, but in this case, someNumber is a local variable, not a static one.

public Class YourClass {

  public static void main(String[] args) {
    int someNumber = 5;
    System.out.println(someNumber);
  }
}
like image 40
Tyler Avatar answered Nov 07 '22 19:11

Tyler