Careeroza
Useful String Methods
Beyond the Basics
| Method | Example | Result |
|---|---|---|
split | "a,b,c".split(",") | [a, b, c] |
String.join | String.join("-", "a", "b") | a-b |
strip / isBlank | " hi ".strip() | hi |
repeat | "ab".repeat(3) | ababab |
String.format / formatted | "%05d".formatted(42) | 00042 |
chars | "aab".chars().filter(c -> c == 'a').count() | 2 |
compareTo | "apple".compareTo("banana") | negative |
Examples
Example
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String csv = "Asha,Ravi,,Meena";
String[] parts = csv.split(",");
System.out.println(Arrays.toString(parts) + " (" + parts.length + " parts)");
System.out.println(String.join(" | ", parts));
String input = " Hello Java ";
System.out.println("[" + input.strip() + "]");
System.out.println("blank? " + " ".isBlank());
System.out.println("=".repeat(20));
System.out.println(String.format("%-8s|%6.2f|%04d", "Tea", 12.5, 7));
System.out.println("Invoice %s for Rs %,d".formatted("INV-9", 1250000));
String word = "banana";
long aCount = word.chars().filter(c -> c == 'a').count();
System.out.println("a appears " + aCount + " times");
System.out.println("apple vs banana: " + "apple".compareTo("banana"));
System.out.println("contains 'nan': " + word.contains("nan"));
}
}Output
[Asha, Ravi, , Meena] (4 parts) Asha | Ravi | | Meena [Hello Java] blank? true ==================== Tea | 12.50|0007 Invoice INV-9 for Rs 1,250,000 a appears 3 times apple vs banana: -1 contains 'nan': true
Practice
Exercise: Write a method String initials(String fullName) that returns "S.R.T." for "sachin ramesh tendulkar". Use split and StringBuilder.
Show answer
static String initials(String fullName) {
StringBuilder sb = new StringBuilder();
for (String part : fullName.strip().split(" ")) {
if (!part.isEmpty()) {
sb.append(Character.toUpperCase(part.charAt(0))).append('.');
}
}
return sb.toString();
}