Syntax
String variableName = "text";Examples
Creating and Combining Strings
Basic string creation and concatenation.
String firstName = "John";
String lastName = "A";
String fullName = firstName + " " + lastName;
System.out.println(fullName); // John A
String greeting = String.format("Hello, %s!", firstName);
System.out.println(greeting);Common String Methods
Length, case conversion, and trimming whitespace.
String text = " Hello World ";
System.out.println(text.length()); // 15 (includes whitespace)
System.out.println(text.trim()); // "Hello World"
System.out.println(text.toUpperCase()); // " HELLO WORLD "
System.out.println(text.toLowerCase()); // " hello world "Searching and Extracting Substrings
Finding content within a string and pulling out parts of it.
String sentence = "The quick brown fox";
System.out.println(sentence.contains("quick")); // true
System.out.println(sentence.indexOf("brown")); // 10
System.out.println(sentence.substring(4, 9)); // "quick"
System.out.println(sentence.replace("fox", "dog")); // The quick brown dogSplitting and Joining
Converting between a string and an array of strings.
String csv = "John,Zain,Jamal";
String[] names = csv.split(",");
for (String name : names) {
System.out.println(name);
}
String joined = String.join(" & ", names);
System.out.println(joined); // John & Zain & JamalBest practices
- Remember String is immutable - every method like .trim() or .toUpperCase() returns a new String rather than modifying the original
- Use a StringBuilder instead of repeated + concatenation when building a string inside a loop, for much better performance
- Use .equals() (or .equalsIgnoreCase()) for content comparison, never == for comparing String values
- Use String.format() or printf-style formatting for building strings with embedded numbers or aligned output, rather than manual concatenation
Runtime & versions
Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Java Language Specification