Variables have a visible range called "** scope **". The scope is that the variable can be used in a certain range, but the variable cannot be used outside the range.
Basically, a variable has a lifetime between the declared line and {}, and if it goes outside, it becomes unusable. I often use the word lifespan. Scope life
* </ font> I will be aware of the scope after studying control statements, but since it is a basic thing, I will describe it first.
I think that understanding will deepen if you can see this "scope" again after completing all the control statements. You can skip it and have it come back to this page later.
Still, if you want to read it for the time being, please continue reading. Also, this time it's a distorted program for explanation, so I don't think I'll write it in a similar way.
As I mentioned earlier, the scope has a lifespan between {}.
You probably didn't care about the program so far.
Main.java
public class Main {
public static void main(String[] args) {
int test = 100;
System.out.println(test);
}
}
It's just outputting 100!
So what about the next program?
Main.java
public class Main {
public static void main(String[] args) {
int outter = 100;
{
int inner = 200;
} //Inner life
//Output the addition of outer and inner
System.out.println(outter + inner);
} //outer life
}
Should be an error! ~~ Bukitcho sauce ~~
This is because the inner is used for standard output after the inner has reached the end of its life. You're trying to use something you don't have.
Where the comment says "// inner life", the variable inner has expired and cannot be used outside of it.
As a test, the following sources can work without problems.
Main.java
public class Main {
public static void main(String[] args) {
int outter = 100;
{
int inner = 200;
//Output the addition of outer and inner
System.out.println(outter + inner);
} //Inner life
//output of outter
System.out.println(outter);
} //outer life
}
It outputs inner and outter on the way.
As a capture, the outer can also be used during the {} where the inner is declared.
Usually, in the study after the "control statement" that will be used in the future, you will become aware of the scope.
I don't usually write the source like this time. sorry. It is written in a neat way in the explanation.
For the time being,
** Variables have a lifetime in the range of {} **
I hope you can remember it! !!
that's all!
Next time, I will write about "if statements"! Control statement! It was a long time, but from here it will become more like a program! Let's do our best happily!
Next time → "Study Java-Part 10-if statement"
Recommended Posts