[Java] When to use "static"? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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"; } }

3rd May 2017, 7:26 PM
Thanh Le
Thanh Le - avatar
2 Answers
+ 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.
3rd May 2017, 7:31 PM
Tashi N
Tashi N - avatar
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.
3rd May 2017, 7:31 PM
Nikunj Pansari
Nikunj Pansari - avatar