Junior — Middle
Can you name data types that cannot be changed after creation?
sobes.tech AI
Answer from AI
Java has several data types and classes whose objects are immutable after creation. These include:
- String — once created, its content cannot be changed. Operations that seem to modify a string actually create a new object.
- Primitive wrapper classes (e.g.,
Integer,Double,Boolean) — objects of these classes are immutable. - BigInteger and BigDecimal — classes for large numbers and precise arithmetic, whose objects are also immutable.
Example:
String s = "hello";
String s2 = s.toUpperCase(); // s remains unchanged, s2 is a new object
If you need to create your own immutable class, you typically make fields final and do not provide setters.