Explain any four string modification methods of String class
Here are four commonly used string modification methods from the Java String
class, each explained with examples:
1. replace()
Purpose: Replaces each occurrence of a character or substring with another.
Syntax:
String newString = original.replace(oldChar, newChar); String newString = original.replace(oldSubstring, newSubstring);
Example:
String str = "Hello World"; String result = str.replace("World", "Java"); // result = "Hello Java"
2. substring()
Purpose: Extracts a part of the string (a substring).
Syntax:
String sub = original.substring(startIndex); String sub = original.substring(startIndex, endIndex);
Example:
String str = "Programming"; String result = str.substring(0, 6); // result = "Progra"
3. toUpperCase()
/ toLowerCase()
Purpose: Converts all characters in the string to upper or lower case.
Syntax:
String upper = original.toUpperCase(); String lower = original.toLowerCase();
Example:
String str = "Hello"; String upper = str.toUpperCase(); // "HELLO" String lower = str.toLowerCase(); // "hello"
4. trim()
Purpose: Removes leading and trailing white spaces from the string.
Syntax:
String trimmed = original.trim();
Example:
String str = " Hello Java "; String result = str.trim(); // "Hello Java"
Summary Table:
Method | Purpose | Example Output |
---|---|---|
replace() | Replace characters/substrings | "Java" |
substring() | Extract part of string | "Progra" |
toUpperCase() | Convert to uppercase | "HELLO" |
trim() | Remove extra spaces | "Hello Java" |