演算子
・文字列と数値の違い
public static void main(String[] args) { System.out.println(1+2+3); // 6 System.out.println("A"+1+2+3); // A123 System.out.println("B"+1+2*3); // B16 }
・インクリメント、デクリメントのタイミング
public static void main(String[] args) { int i = 0, j = 0; System.out.println(i++); // 0 (処理後に足される) System.out.println(i); // 1 System.out.println(++j); // 1 (処理前に足される) System.out.println(j); // 1 }
・論理演算子
&&:両方trueならtrue
||:片方trueならtrue
public static void main(String[] args) { System.out.println((1 == 1) && (1 == 2)); // false System.out.println((1 == 1) || (1 == 2)); // true }
・比較
コンストラクタを使用すると参照先が異なるため不一致になる
internメソッドは同じ文字列であれば同じオブジェクトを取得する
public static void main(String[] args) { String str1 = "A"; String str2 = "A"; String str3 = new String("A"); // コンストラクタを使用 System.out.println(str1 == str2); // true System.out.println(str1 == str3); // false System.out.println(str1.equals(str3)); // true System.out.println(str1.intern() == str3.intern()); // true }
Stringクラスのメソッド
・substring
substring(開始文字,終了文字)
先頭は0
public static void main(String[] args) { String str = "ABCD"; System.out.println(str.substring(0,2)); // AB }
・replace
replace(対象,変換後)
public static void main(String[] args) { String str = "ABCD"; System.out.println(str.replace("B","b")); // AbCD }
・charAt
charAt(取り出す文字番号)
先頭は0
public static void main(String[] args) { String str = "ABCD"; System.out.println(str.charAt(0)); // A }
・StringBuilder
public static void main(String[] args) { StringBuilder str = new StringBuilder("ABCD"); System.out.println(str.replace(0,1,"a")); // aBCD System.out.println(str.delete(0,1)); // BCD }
IF文
true,falseの判定はboolean型でないとエラー
public static void main(String[] args) { String str = "true"; if (str) { // boolean型でないためコンパイルエラー System.out.println("a"); } if (str=="true") { // これならOK System.out.println("a"); } }
Switch
breakがないと条件を無視して次のcaseを通る
public static void main(String[] args) { String str = "A"; switch(str) { case "A": System.out.println("A"); // A case "B": System.out.println("B"); // B ※breakがないから通る break; default: System.out.println("C"); } }
caseの条件は定数でないとコンパイルエラー
finalをつけた変数だと問題なし
public static void main(String[] args) { String str = "A"; final String str2 = "A"; switch(str) { case str2: System.out.println("hello"); // hello break; } }