String
. - String is immutable.
- It seems mutable in certain cases, but it is a misconception.
String hi = "Hi"
hi += "Hello"
//it seems that we just changed the object itself from "Hi" to "HiHello"
//but what really happened is that we created a new String value "HiHello" and
//changed the reference of the object hi from "Hi" to "HiHello"
StringBuffer
- StringBuffer is a data type that is used when we need a 'mutable String.'
- StringBuffer is heavier than String, so it is better to use String when there is not much change of String.
- append(string value): adds the string to a StringBuffer object in chronological order.
StringBuffer sb = new StringBuffer();
sb.append("Hi");
sb.append(" ");
sb.append("Hello");
//sb = "Hi Hello"
String st = sb.toString();
//can be changed to String data type by toString() method.
- insert(index number, string value): inserts the string at a given position in a StringBuffer.
StringBuffer sb = new StringBuffer();
sb.append("Hi Hello");
sb.insert(0, "Hey ");
//sb = "Hey Hi Hello"
- substring(startingpoint, endpoint): same as the substring method of String class.
StringBuffer sb = new StringBuffer();
sb.append("Hi Hello");
System.out.println(sb.substring(0, 4));
//result: Hi H
(StringBuilder has the same methods as StringBuffer)
'Notes for Java' 카테고리의 다른 글
Methods of String (0) | 2022.07.01 |
---|