Careeroza
Common String Methods
Method Reference Table
| Method | Returns | Example | Result |
|---|---|---|---|
length() | number of characters | "Java".length() | 4 |
toUpperCase() / toLowerCase() | changed case | "Java".toUpperCase() | JAVA |
trim() / strip() | removes outer spaces | " hi ".trim() | hi |
substring(b, e) | part from b to e-1 | "Careeroza".substring(0, 6) | Career |
contains(s) | boolean | "Java".contains("av") | true |
startsWith / endsWith | boolean | "a.pdf".endsWith(".pdf") | true |
replace(a, b) | new string | "a-b-c".replace("-", "/") | a/b/c |
split(regex) | String[] | "a,b,c".split(",") | [a, b, c] |
isEmpty() / isBlank() | boolean | " ".isBlank() | true |
repeat(n) | repeated | "ab".repeat(3) | ababab |
Methods in Action
Example
public class Main {
public static void main(String[] args) {
String email = " [email protected] ";
String clean = email.trim().toLowerCase();
System.out.println("[" + clean + "]");
int at = clean.indexOf('@');
String user = clean.substring(0, at);
String domain = clean.substring(at + 1);
System.out.println("User: " + user + ", Domain: " + domain);
System.out.println(clean.contains("@") && clean.endsWith(".com"));
System.out.println(user.replace(".", " "));
String[] parts = "Java,Spring,React".split(",");
System.out.println(parts.length + " skills, first = " + parts[0]);
System.out.println("=".repeat(20));
System.out.println(" ".isBlank() + " " + "".isEmpty());
}
}Output
[[email protected]] User: ravi.kumar, Domain: gmail.com true ravi kumar 3 skills, first = Java ==================== true true
Practice
Exercise: Given String fullName = "sachin tendulkar"; print the initials in capitals: ST.
Show answer
String[] parts = fullName.split(" ");
String initials = "" + parts[0].charAt(0) + parts[1].charAt(0);
System.out.println(initials.toUpperCase()); // ST