Junior — Middle
Can you tell about any unique properties of string data types?
sobes.tech AI
Answer from AI
In Java, string data types (String) have several unique properties:
-
Immutability: After creating a String object, it cannot be changed. Any operations that seem to modify the string actually create a new object.
-
String Pool: Java stores string literals in a special pool, which helps save memory and speeds up string comparison using the
==operator for literals. -
String class methods: Provide many convenient functions for working with text — searching, replacing, splitting, transforming, etc.
Example:
String s1 = "hello";
String s2 = "hello";
System.out.println(s1 == s2); // true, because both refer to the same object in the pool
String s3 = new String("hello");
System.out.println(s1 == s3); // false, different objects
String s4 = s1.toUpperCase();
System.out.println(s1); // "hello"
System.out.println(s4); // "HELLO" - the original string did not change