Junior
What is the feature of the String class and is it immutable?
sobes.tech AI
Answer from AI
String in Kotlin/Java is an immutable class. This means that after creating a String object, its contents cannot be changed. Any operation that seemingly modifies the string (for example, concatenation) actually creates a new String object.
Features:
- Immutability: Ensures safety in concurrent access and simplifies reasoning about code behavior.
- String Pool: To save memory and improve performance, identical string literals refer to the same object in a special area of JVM memory.
- Security: Using immutable strings prevents unexpected changes in other parts of the program that reference the same string.
// Creating a string literal. It is placed in the String Pool.
val str1 = "hello"
// Refers to the same object in the String Pool as str1.
val str2 = "hello"
// str1 == str2 will be true, as the references point to the same object.
// The result of concatenation is a new string object.
val str3 = str1 + " world"
// str1 remains unchanged.
println(str1) // Outputs: hello
println(str3) // Outputs: hello world