+ 2
[Java] When to use "static"?
How come I can write "static" here: public class Main { final static String MY_CONST = "hello"; public static void main(String[] args) { } } but not here: public class Main { public static void main(String[] args) { final String MY_CONST = "hello"; } } Why can't I use static within my main method like this: public class Main { public static void main(String[] args) { final static String MY_CONST = "hello"; } }
2 Antworten
+ 13
The static keyword is used to make a variable/method belong to a class, so that you can use the variable/method without creating an object of the class. This is called static access.
It doesn't make sense to declare a static variable inside a method. Variables you declare inside a method are only accessible inside the method (they are local variables), so they cannot belong to the class, only to the method inside the class.
0
static keyword is used when value of a particular class or its corresponding variable has to be made fixed throught the execution of a particular function.