Stringの不変性(Immutable)と、主要なメソッドの使用例です。
public class StringExample {
public static void main(String[] args) {
String str = "Hello";
str.concat(" World"); // 結合結果の新しいStringが作られるが、strは変更されない!
System.out.println(str); // 出力: Hello
str = str.concat(" World"); // 再代入することで新しい参照を保持
System.out.println(str); // 出力: Hello World
// 主要メソッド
System.out.println(str.length()); // 11 (文字数)
System.out.println(str.charAt(1)); // 'e' (1番目の文字)
System.out.println(str.substring(0, 5)); // Hello (切り出し)
System.out.println(str.indexOf("World"));// 6 (検索位置)
}
}