String Manipulation in Java
With Simple Program Examples
Program 1: Find Length of String
public class StringLengthExample { public static void main(String[] args) { String str = "Java
Programming"; [Link]("Length: " + [Link]()); } }
Program 2: String Concatenation
public class ConcatExample { public static void main(String[] args) { String a = "Hello"; String b =
"World"; [Link](a + " " + b); } }
Program 3: Change Case
public class CaseExample { public static void main(String[] args) { String str = "Java";
[Link]([Link]()); [Link]([Link]()); } }
Program 4: Compare Strings
public class CompareExample { public static void main(String[] args) { String s1 = "Java"; String s2
= "java"; [Link]([Link](s2)); } }
Program 5: Substring Example
The substring() method is used to extract a part of a string. It is part of the String class. Since
Strings are immutable, it returns a new string. public class SubstringExample { public static void
main(String[] args) { String str = "Programming"; [Link]([Link](0,6)); } }
Program 6: Replace Characters
public class ReplaceExample { public static void main(String[] args) { String str = "Java";
[Link]([Link]('a','o')); } }
Program 7: Split String
public class SplitExample { public static void main(String[] args) { String str = "Java,Python,C++";
String[] arr = [Link](","); for(String s : arr) { [Link](s); } } }
Program 8: StringBuilder Example
StringBuilder is used to create mutable (changeable) strings. Unlike String, which is immutable,
StringBuilder allows you to modify the same object without creating a new one. public class
StringBuilderExample { public static void main(String[] args) { StringBuilder sb = new
StringBuilder("Hello"); [Link](" World"); [Link](sb); } }
Program 9: String with User Input
import [Link]; public class UserInputExample { public static void main(String[] args) {
Scanner sc = new Scanner([Link]); [Link]("Enter your name: "); String name =
[Link](); [Link]("Hello " + name); } }
Program 10: trim
In Java, the trim() method is used to remove leading (starting) and trailing (ending) white spaces**
from a string. ■ It does not remove spaces in between words. ■ It belongs to the String class. ■
Since Strings are immutable, it returns a new string.
public class TrimExample { public static void main(String[] args) {
String str = " Hello Java "; [Link]("Before trim: '" + str
+ "'"); String trimmedStr = [Link](); [Link]("After
trim: '" + trimmedStr + "'"); } }
Conclusion
• Strings are immutable in Java • Many built-in methods available • StringBuilder is mutable • Used
widely in real-world applications