Task 1 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

3.4 Methods — local variables and scope

Lesson

Where a variable lives

A variable declared inside a method is local to that method: it exists only while the method runs, and it can't be seen from anywhere else. This is called its scope. Because of scope, two methods can each have a variable with the same name without interfering.


Worked example

void showX() {
    int x = 99;            // this x belongs to showX
    System.out.println(x);
}

int x = 5;                 // a different x, belongs to main
showX();                   // prints 99
System.out.println(x);     // prints 5 — main's x is untouched

▶ Try it: showX() has its own x = 99. Run this — the x in main stays 5, because the method's x is separate. Change the values and re-run.



Where can a variable declared inside a method be used?


showX() declares its own int x = 99 and prints it. Type exactly what this prints:

int x = 5;
showX();
System.out.println(x);

True or false?