
//Sample15_03.java class Sample15_03 { public static void main(String[] args){ int x; x = 3; //代入 System.out.println("x = "+x); //参照 } }
>javac Sample15_03.java >java Sample15_03 x = 3
int x = 3; //変数の宣言と同時に代入
一見代入できそうでも、変数とリテラルが一致していないとNGです。
int i = 28.0; //エラー: 不適合な型 char ch = "A"; //エラー: 不適合な型 char ch = ''; //エラー: 空の文字リテラルです
//Sample15_04.java class Sample15_04 { public static void main(String[] args){ int x; //宣言 x = 100; //代入 System.out.println("x= "+x); x = 200; //代入(上書き) System.out.println("x= "+x); x = 300; //代入(上書き) System.out.println("x= "+x); } }
>javac Sample15_04.java >java Sample15_04 x= 100 x= 200 x= 300
//Sample15_05.java class Sample15_05 { public static void main(String[] args){ int x = 1; System.out.println("x= "+x); x = x+1; System.out.println("x= "+x); x = x+1; System.out.println("x= "+x); } }
>javac Sample15_05.java >java Sample15_05 x= 1 x= 2 x= 3