String
In Java, a String is an object — not a primitive type. Strings are stored as an internal array of characters and are immutable (they cannot be changed after creation). Every operation on a String produces a new String, which can impact performance if done repeatedly in a loop. For dynamic String construction, use StringBuilder or StringBuffer.
StringBuilder (non-thread-safe, faster) is suitable for String manipulation within a single thread. StringBuffer (thread-safe) is suitable for multithreaded environments. Both provide the methods append(), insert(), delete(), reverse(), and toString().
Java provides many utility methods on String: length(), charAt(), substring(), indexOf(), contains(), replace(), split(), trim(), toLowerCase(), toUpperCase(), equals(), compareTo(), and many more. Text Blocks (Java 15+) make it easy to create multi-line Strings with the triple quote """.
Important String Methods:
| Method | Use | Example |
|---|---|---|
length() |
String length | "Hello".length() → 5 |
charAt(i) |
The i-th character | "Hello".charAt(1) → 'e' |
substring(a,b) |
A slice of the string | "Hello".substring(1,3) → "el" |
contains(s) |
Check for a substring | "Hello".contains("ell") → true |
split(s) |
Split the string | "a,b".split(",") → ["a","b"] |
equals(s) |
Compare | "Hi".equals("Hi") → true |
Code Example
public class StringJava {
public static void main(String[] args) {
// Basic string
String name = "Skillversitas";
System.out.println("Length: " + name.length()); // 13
System.out.println("Character at index 2: " + name.charAt(2)); // i
System.out.println("Substring: " + name.substring(0, 5)); // Skill
// String methods
String text = " Hello, World! ";
System.out.println("Trim: [" + text.trim() + "]");
System.out.println("Upper: " + text.trim().toUpperCase());
// StringBuilder (efficient for manipulation)
StringBuilder sb = new StringBuilder("Hello");
sb.append(" ");
sb.append("World");
sb.insert(6, ", ");
System.out.println("Result: " + sb.toString()); // Hello, World
// Text Block (Java 15+)
String json = """
{
"name": "John",
"age": 25
}
""";
System.out.println(json);
}
}
Code Explanation
length()returns the number of characters.charAt(i)gets the character at a specific index (starting at 0).substring(start, end)takes the part of the string from indexstartup toend(exclusive).trim()removes leading and trailing spaces.toUpperCase()converts all letters to uppercase.StringBuilderbuilds a String incrementally without creating a new String object on each step — much more efficient for join operations inside loops.- Text blocks
"""..."""make it easy to write multi-line strings such as JSON or SQL without escape characters.
Everyday Example
A simple program to validate and format user data:
public class UserValidation {
public static void main(String[] args) {
String email = " [email protected] ";
String fullName = "john smith";
// Clean and format
String emailBersih = email.trim().toLowerCase();
String nameFormat = formatTitleCase(fullName);
// Validate
boolean emailValid = emailBersih.contains("@") && emailBersih.endsWith(".com");
boolean nameValid = nameFormat.length() >= 3;
System.out.println("Email: " + emailBersih);
System.out.println("Name: " + nameFormat);
System.out.println("Email valid: " + emailValid);
System.out.println("Name valid: " + nameValid);
}
static String formatTitleCase(String name) {
String[] word = name.split(" ");
StringBuilder result = new StringBuilder();
for (String k : word) {
if (!result.isEmpty()) result.append(" ");
result.append(Character.toUpperCase(k.charAt(0)))
.append(k.substring(1).toLowerCase());
}
return result.toString();
}
}
Summary
Strings in Java are powerful immutable objects. StringBuilder is the solution for high-performance String manipulation. Text Blocks make working with multi-line strings easy. Master the String methods, because almost every Java program uses them.