変数の宣言
変数の宣言は以下のように宣言します。

public class Test{
    public static void main(String[] args) {
        int a;
        int b,c;
        int d=2;
        System.out.println(a);
    }
}
サンプルソース
public class Test{
    public static void main(String[] args) {
        int a=3;
        int b,c;
        int d=2;
        System.out.println(a);
    }
}
実行結果は以下の通りです。

3
static変数
static変数は、クラスに付随する変数です。その為、インスタンスを生成してもstatic変数は一つです。

private static boolean flg = true;

if(flg){
    //~何か実行~
    flg = false;
}

例えば、上記のようにboolean型のstatic変数flgが宣言されているとします。
マルチスレッド環境において、最初にクラスを実行したスレッドでstatic変数flgをfalseにした場合、以降のスレッドではif文の中は二度と通りません。
gcでも初期化されることはなく、アプリケーションサーバを再起動するまでずっと値を保持し続けます。

Back to top

Information