0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Java 学習メモ(まとめ④) イミュータブル

0
Last updated at Posted at 2026-06-01

String はイミュータブル(不変)

Java の String は イミュータブル(Immutable:不変) なオブジェクトです。
これは、一度作成された文字列の内容は変更できないことを意味します。

String name = "太郎";
name = "花子";

一見すると "太郎" が "花子" に変更されたように見えますが、実際には "花子" という新しい文字列オブジェクトが作成され、変数 name の参照先が切り替わっています。

name
 ↓
"太郎"

↓

name
 ↓
"花子"

そのため、元の "太郎" という文字列は変更されていません。

ポイント

  • String の内容は変更できない
  • 文字列を変更する操作は新しい文字列を生成する
  • 変数には新しい文字列を再代入する必要がある
String text = "hello";

text = text.toUpperCase();  //再代入

System.out.println(text); // HELLO

文字列メソッドは元の文字列を変更するのではなく、新しい文字列を返す点に注意しましょう。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?