Concatenation: The + operator is used for string concatenation, which means combining two or more strings together.
String firstName = "John"; String lastName = "Doe"; String fullName = firstName + " " + lastName;
You can find the length of a string using the length() method.
String text = "Hello, World!"; int length = text.length(); // length is 13
You can access individual characters in a string using the charAt() method.
String text = "Hello, World!"; char firstChar = text.charAt(0); // firstChar is 'H'
To compare two strings for equality, use the equals() method.
String str1 = "Java"; String str2 = "java"; boolean isEqual = str1.equals(str2); // isEqual is false
You can extract a portion of a string using the substring() method.
String text = "Hello, World!"; String subText = text.substring(0, 5); // subText is "Hello"
To find the position of a substring within a string, use the indexOf() method.
String text = "Hello, World!"; int index = text.indexOf("World"); // index is 7
To concatenate a string to an existing one, you can use the concat() method or the += operator.
String greeting = "Hello"; greeting = greeting.concat(", World!"); // greeting is "Hello, World!"
To replace characters within a string, use the replace() method.
String message = "I like Java"; String newMessage = message.replace("Java", "Python"); // newMessage is "I like Python"
To remove leading and trailing whitespace, use the trim() method.
String input = " Java Programming "; String trimmed = input.trim(); // trimmed is "Java Programming"
You can change the case of a string using methods like toUpperCase() and toLowerCase().
String text = "Hello, World!"; String uppercaseText = text.toUpperCase(); // uppercaseText is "HELLO, WORLD!"
String sentence = "Java is a powerful language"; String[] words = sentence.split(" "); // words is ["Java", "is", "a", "powerful", "language"]
Mastering these essential string methods in Java is crucial for effective text manipulation and data processing in your Java applications. Whether you're extracting substrings, modifying content, searching for specific characters, or handling escape sequences, a good understanding of these methods will greatly enhance your programming capabilities.