void doStuff() {
for (int i = 0; i < 4; i++) {
boolean flag = false;
if (i == 3) { flag = true; }
}
System.out.println(flag);
}
I’m sure the compiler will do this :
Compiler will say that I have no memory of such a variable called flag. It will give an error with a message “flag cannot be resolved to a variable”
Examine the class below :
public class Test { // class
static int a = 29; // static variable
int b; // instance variable
{ // initialization block
b = 7;
int d = 5;
}
Test() { // constructor
b += 8;
int e = 6;
}
void doSomething() { // method
int c = 0; // local variable
for (int i = 0; i < 4; i++) { // for code block
c += i + b;
}
}
}
a is static variable
b is an instance variable
c is a local variable
i is a block variable
d is an init block variable, a flavor of local variable
e is a constructor variable, a flavor of local variable
There are 4 basic scopes:
- Static variable has the longest scope. They are created when the class is loaded and they survive as long as the class stays loaded in the JVM.
- Instance variables are the next most long-lived. They are created when a new instance(object) is created in the heap, and they live until the instance is removed.
- Local variables are the next one. They live as long as their method remains on the stack.
- Block variables live only as long as the code block is executing.
—Saju Pappachen
About the author: Saju Pappachen is the Chief Consultant of jThread IT Training & Consultancy. He has more than 20 years of experience in Java technology.
He can be reached at saju@jthread.com
Very informative.
Hey nice post sir not only for beginners but also for experienced people for basics.
Thank you.
Good one sir😃👍
The compiler’s reaction reminded me of Mary Thamburatti 😄 very well explained, sir.
ha ha 🙂 Thank you.
Well explained sir 😊 . Helpful to understand the basics.
Brainstorming nuggets .
Veryyyy helpfull post sir!!!
Revision of topics can be done so easily with this🙂
Very usefull one ..!
One blog with all details about scope of variables.Great!👍
Well explained sir
It is very useul
👍
Thanks sir.
It is more usefull to refer it.and getting a very clear idea about variables by this blog Sir.How i expect that to get clarification about the variables it is there.
Thank You
Very helpful and informative…. Thank you Sir…
Got a clear idea about the scope of the variables, Sir.
Well explained sir
Well explained… Thank you sir
Informative Blog..Thank you so much sir
Well explained sir❤️
Well understood and get a clear idea of scope of variables.
Static>Instance>Local… got an idea about the scope of variables Sir.. Thank you..
Detailed and simple explaination.Thank you sir.
clearly understood sir…simple explanation
Well explained sir