Introduction
Strings in Java cannot be changed once created. This helps keep data safe and programs reliable.
Strings in Java cannot be changed once created. This helps keep data safe and programs reliable.
String text = "Hello"; // text cannot be changed after this
Strings are objects but behave like fixed text.
Any change creates a new String object instead of modifying the original.
String greeting = "Hi"; greeting = greeting + " there!"; System.out.println(greeting);
String name = "Alice"; String copy = name; // Both name and copy point to the same string object "Alice"
This program shows that the original string stays the same after trying to replace a character. A new string is created instead.
public class Main { public static void main(String[] args) { String original = "Cat"; String changed = original.replace('C', 'B'); System.out.println("Original: " + original); System.out.println("Changed: " + changed); } }
Because strings are immutable, methods like replace() return new strings.
Use StringBuilder if you need to change text many times for better performance.
Strings cannot be changed after creation.
Changing a string creates a new string object.
Immutability helps keep programs safe and predictable.
String in Java is immutable?str?str.charAt(0) = 'A' is invalid.String s = "hello"; s.toUpperCase(); System.out.println(s);
toUpperCase() returns a new string but does not change the original string s.s was not reassigned, printing s outputs the original string "hello".String s = "test"; s.charAt(0) = 'T'; System.out.println(s);
charAt() returns a character but cannot be assigned a new value.input. Which code correctly does this considering string immutability?replace() method returns a new string with replacements but does not change the original.input, assign the result of replace() back to it before printing.Pass the test and this pattern moves unknown