public class StringMethodsExample { public static void main(String[] args) { String str = "Hello, World!"; // Length of the string int length = str.length(); System.out.println("Length of the string: " + length); // Concatenation String newStr = str.concat(" How are you?"); System.out.println("Concatenated string: " + newStr); // Substring String substring = str.substring(7); System.out.println("Substring from index 7: " + substring); // Character at a specific index char charAtIndex = str.charAt(0); System.out.println("Character at index 0: " + charAtIndex); // Index of a specific character int indexOfComma = str.indexOf(","); System.out.println("Index of comma: " + indexOfComma); // Conversion to lowercase and uppercase String lowercase = str.toLowerCase(); String uppercase = str.toUpperCase(); System.out.println("Lowercase: " + lowercase); System.out.println("Uppercase: " + uppercase); // Checking for presence of a substring boolean containsHello = str.contains("Hello"); System.out.println("Contains 'Hello': " + containsHello); // Removing leading and trailing whitespaces String stringWithSpaces = " Trim me "; String trimmedString = stringWithSpaces.trim(); System.out.println("Trimmed string: " + trimmedString); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter