
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Declare Static Variable Within a Method in Java
A static filed/variable belongs to the class and it will be loaded into the memory along with the class. You can invoke them without creating an object. (using the class name as reference). There is only one copy of the static field available throughout the class i.e. the value of the static field will be same in all objects. You can define a static field using the static keyword.
Example
public class Sample{ static int num = 50; public void demo(){ System.out.println("Value of num in the demo method "+ Sample.num); } public static void main(String args[]){ System.out.println("Value of num in the main method "+ Sample.num); new Sample().demo(); } }
Output
Value of num in the main method 50 Value of num in the demo method 50
Static variables in methods
The variables with in a method are local variables and their scope lies within the method and they get destroyed after the method execution. i.e. you cannot use a local variable outside the current method which contradicts with the definition of class/static variable. Therefore, declaring a static variable inside a method makes no sense, if you still try to do so, a compile time error will be generated.
Example
In the following Java program, we are trying to declare a static variable inside a method
import java.io.IOException; import java.util.Scanner; public class Sample { static int num; public void sampleMethod(Scanner sc){ static int num = 50; } public static void main(String args[]) throws IOException { static int num = 50; } }
Compile time error
If you try to execute the above program it generates the following error −
Sample.java:6: error: illegal start of expression static int num = 50; ^ Sample.java:9: error: illegal start of expression static int num = 50; ^ 2 errors