Unlike C/C++, static local variables are not allowed in Java. For example, following Java program fails in compilation with error “Static local variables are not allowed”
class Test { public static void main(String args[]) { System.out.println(fun()); } static int fun() { static int x= 10; //Error: Static local variables are not allowed return x--; } } |
chevron_right
filter_none
In Java, a static variable is a class variable (for whole class). So if we have static local variable (a variable with scope limited to function), it violates the purpose of static. Hence compiler does not allow static local variable.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
Recommended Posts:
- Static and non static blank final variables in Java
- Difference between static and non-static variables in Java
- Understanding storage of static methods and static variables in Java
- Final local variables in Java
- Difference between static and non-static method in Java
- Why non-static variable cannot be referenced from a static method in Java
- Understanding "static" in "public static void main" in Java
- Assigning values to static final variables in Java
- Output of Java Programs | Set 45 (static and instance variables)
- Static Variables in Java with Examples
- Local Inner Class in Java
- Local Variable Type Inference or LVTI in Java 10
- Initialization of local variable in a conditional block in Java
- Java Program to Check if a Given Class is a Local Inner Class
- Shadowing of static functions in Java
- Comparison of static keyword in C++ and Java
- Static blocks in Java
- Static class in Java
- Static vs Dynamic Binding in Java
- Static methods vs Instance methods in Java
Improved By : KarthickManickam

