問題一覧に戻る
初級基本構文
問題43: ローカル変数とスコープ
ローカル変数は宣言されたブロック(メソッド、if文、ループ)内でのみ存在します。内側のブロックの変数は外側の変数にアクセスできますが、逆はできません。
public class ScopeExample {
public static void test() {
// メソッド内のローカル変数
x = 10;
if (x > 5) {
// ブロック内の変数
int y = 20;
System.out.println("x = " + x);
System.out.println("y = " + );
}
// yはスコープ外
// System.out.println("y = " + y); // Error!
}
public static void main(String[] args) {
test();
}
}