A static filed/variable belongs to the class and it will be loaded into the memory at class load time. We can invoke them without creating an object. (using the class name as reference). There is only one copy of the static field available entire the class i.e. the value of the static field will be the same in all objects. We can define a static field using the static keyword Output The variables within a method are local variables and their scope lies within the method and they get destroyed after the method execution. i.e. we cannot use a local variable outside the current method which contradicts the definition of class/static variable. Therefore, declaring a static variable inside a method makes no sense, if we still try to do so, a compile-time error will be generated If we run above code it will throw compile time error
public class Test{
static int num = 22;
public void demo(){
System.out.println("Value of num in the demo method "+ Test.num);
}
public static void main(String args[]){
System.out.println("Value of num in the main method "+ Test.num);
new Test().demo();
}
}
Value of num in the main method 22
Value of num in the demo method 22
Static variables in methods
import java.io.IOException;
import java.util.Scanner;
public class Test{
static int num;
public void sampleMethod(Scanner sc){
static int num = 22;
}
public static void main(String args[]) throws IOException {
static int num = 22;
}
}
Compile time error
Test.java:6: error: illegal start of expression
static int num = 22;
^
Test.java:9: error: illegal start of expression
static int num = 22;
^
2 errors
What is Method Overloading in Java ?
Can we overload the main method in Java?
How to create a table in Java with JDBC Connection?
Can we declare the main method as private in Java?
What is the Difference between Path and ClassPath in java?
How to check Java version?
Can we define a static constructor in Java?
Convert given time in String format to seconds
Can we declare the main () method as final in Java?
What is the difference between JDK and JRE?
How to Create Objects in Java?
Memory Allocation in Java
Can we declare a static variable within a method in java?
What are the important features of Java 8?
What is a Class/Static Variables?
What is Instance variable?