Rakshitha R’s Post

Strings methods in Java 1️⃣ length() Definition: Returns the number of characters in a string (including spaces). 💡 Why it matters: Useful for checking input length (like passwords, usernames) or controlling loops. Example: String name = "Rakshitha"; System.out.println(name.length()); // Output: 9 2️⃣ charAt() Definition: Returns the character at a given index (index starts from 0). 💡 Why it matters: Helps to access or check specific characters, like the first letter of a name. Example: String word = "Java"; System.out.println(word.charAt(2)); // Output: v 3️⃣ toUpperCase() / toLowerCase() Definition: Converts all letters in a string to uppercase or lowercase. 💡 Why it matters: Useful for ignoring case in comparisons or displaying consistent text. Example: String text = "Java"; System.out.println(text.toUpperCase()); // JAVA System.out.println(text.toLowerCase()); // java 4️⃣ equals() / equalsIgnoreCase() Definition: equals() compares two strings exactly, while equalsIgnoreCase() ignores case differences. 💡 Why it matters: Used to compare user inputs like login IDs or names, case-sensitive or not. Example: String a = "Java"; String b = "java"; System.out.println(a.equals(b)); // false System.out.println(a.equalsIgnoreCase(b)); // true 5️⃣ contains() Definition: Checks if a string contains a certain sequence of characters. 💡 Why it matters: Used to search or validate text (like checking if an email contains “@”). Example: String email = "rakshitha@gmail.com"; System.out.println(email.contains("@gmail.com")); // true Awesome 👍 Here are the next 5 common String methods in Java — explained simply with definition, why it matters, and example 👇 6️⃣ substring() Definition: Extracts a part of the string between given start and end indexes. 💡 Why it matters: Used to get a specific portion of text, like extracting username from an email. Example: String word = "JavaDeveloper"; System.out.println(word.substring(0, 4)); // Output: Java 7️⃣ replace() Definition: Replaces all occurrences of a character or substring with another value. 💡 Why it matters: Useful for correcting text, filtering data, or formatting user input. Example: String text = "I love Java"; System.out.println(text.replace("Java", "Python")); // Output: I love Python 8️⃣ split() Definition: Splits a string into multiple parts based on a given delimiter and returns an array. 💡 Why it matters: Used to break text into pieces, such as splitting CSV data or words in a sentence. Example: String data = "apple,banana,grape"; String[] fruits = data.split(","); System.out.println(fruits[1]); // Output: banana 9️⃣ trim() Definition: Removes all leading and trailing spaces from a string. 💡 Why it matters: Essential for cleaning user input before saving or comparing values. Example: String name = " Rakshitha "; System.out.println(name.trim()); // Output: Rakshitha #Java #CoreJava #JavaProgramming #LearnJava #JavaDeveloper

To view or add a comment, sign in

Explore content categories