0

a string created with String class can not be modified. but when we use the += operator does it mean that the original string change? exp:

 String ch="hello"; ch+= "world";

another question: why we don't use these instructions to display the string ?

for (int i=0;i<ch.length();i++) {System.out.println(ch[i]); }

i tried this

for (int i=0;i<ch.length();i++) {System.out.println(ch.charAt(i)); }

why it is not similar to

for (int i=0;i<ch.length();i++) {System.out.println(ch[i]); }
toubi
  • 1
  • 1
    `ch[i]` is used when `ch` is an array. If you want to get an array out of `ch`, you can use `ch.toCharArray()` and assign the result to a variable, say `char arr[]`. Then, you can use `arr[i]`. When you do `ch+= "world"`, a new `String` with the value `helloworld` is created. – Arvind Kumar Avinash Nov 19 '22 at 17:41
  • so in java the only way to display a string is using the methods od String class and it is not like String in langage c ? the concatenation means that the reference ch changes from hello to helloworld? Taking this in consideration the string in ch has changed from hello to helloworld so it is not constant and immutable? – toubi Nov 19 '22 at 17:59
  • A `String` in Java is different from that in C. Every `String` object in Java is immutable. As I have already mentioned in my previous comment, a new `String` is created and then `ch` starts pointing to this new `String`. I suggest you go through the [documentation](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html) to learn more about it. – Arvind Kumar Avinash Nov 19 '22 at 18:04

0 Answers0