What is a String?
A String is a sequence of characters, such as a name, a PIN or a sentence. In Java, String is a class in java.lang, so every string is an object with useful methods.
String city = "Ranchi";
String empty = "";
String greeting = "Hello, " + city; // "Hello, Ranchi"
Strings are immutable
Once created, a String object never changes. Methods that seem to change it return a new string:
String s = "java";
s.toUpperCase(); // creates "JAVA" but it is thrown away
System.out.println(s); // java
s = s.toUpperCase(); // keep the new string
System.out.println(s); // JAVA
equals versus ==
==checks whether two variables point to the same object.equals()checks whether two strings have the same characters.
String a = "hello";
String b = "hello";
String c = new String("hello");
System.out.println(a == b); // true: both come from the string pool
System.out.println(a == c); // false: c is a separate object
System.out.println(a.equals(c)); // true: same characters
System.out.println("Hello".equalsIgnoreCase(a)); // true
Rule: always compare string contents with equals() or equalsIgnoreCase(), never ==.
The string pool
String literals such as "hello" are stored once in a shared area called the string pool. Two identical literals share one object, which is why a == b was true above. new String(...) always makes a new object outside the pool.
Common String methods
String s = " BrainBit Infotech ";
String t = s.trim(); // "BrainBit Infotech"
| Method | Result for t = "BrainBit Infotech" |
|---|---|
t.length() | 17 |
t.charAt(0) | 'B' |
t.indexOf("Info") | 9 (-1 if not found) |
t.substring(9) | "Infotech" |
t.substring(0, 8) | "BrainBit" (end index not included) |
t.toLowerCase() | "brainbit infotech" |
t.contains("Bit") | true |
t.startsWith("Brain") | true |
t.endsWith("tech") | true |
t.replace('i', 'I') | "BraInBIt Infotech" |
t.split(" ") | ["BrainBit", "Infotech"] |
t.isEmpty() | false |
" ".isBlank() | true (Java 11+) |
"ab".repeat(3) | "ababab" (Java 11+) |
String.valueOf(42) | "42" |
String.join("-", "a", "b") | "a-b" |
compareTo for alphabetical order
a.compareTo(b) returns a negative number if a comes first, 0 if equal, positive if a comes after:
"apple".compareTo("mango"); // negative
"mango".compareTo("apple"); // positive
Looping over characters
String word = "programming";
int vowels = 0;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if ("aeiou".indexOf(ch) != -1) vowels++;
}
System.out.println(vowels); // 3
toCharArray() gives a char[] you can use in a for-each loop: for (char ch : word.toCharArray()).
Converting between strings and numbers
int n = Integer.parseInt("125");
double d = Double.parseDouble("72.5");
String s1 = String.valueOf(n);
String s2 = "" + d;
Integer.parseInt("12a") throws NumberFormatException.
StringBuilder: a changeable string
Joining strings with + in a loop creates a new object every time. StringBuilder changes one buffer instead, which is much faster for repeated changes:
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append(i).append(", ");
}
sb.setLength(sb.length() - 2); // remove the last ", "
System.out.println(sb); // 1, 2, 3, 4, 5
| Method | Does |
|---|---|
append(x) | adds to the end |
insert(i, x) | inserts at index i |
delete(start, end) | removes characters |
deleteCharAt(i) | removes one character |
reverse() | reverses in place |
setCharAt(i, c) | replaces one character |
toString() | gives a normal String |
Palindrome check
String w = "madam";
boolean pal = new StringBuilder(w).reverse().toString().equals(w);
StringBuffer has the same methods but is synchronised for threads; use StringBuilder unless several threads share it.
Text blocks (Java 15+)
Three double quotes start a multi-line string:
String receipt = """
BrainBit Infotech
Item: Notebook
Total: Rs 180
""";
Example: initials from a full name
public class Initials {
public static void main(String[] args) {
String full = "Asha Kumari Singh";
StringBuilder initials = new StringBuilder();
for (String part : full.split(" ")) {
initials.append(Character.toUpperCase(part.charAt(0))).append('.');
}
System.out.println(initials); // A.K.S.
}
}
Common mistakes
- Comparing strings with
==. - Calling
s.toUpperCase();without storing the result. - Using
s.length(no brackets) for a string; it iss.length(). substring(2, 5)gives characters 2, 3 and 4: the end index is not included.- Calling a method on a
nullstring:NullPointerException.
Key points
Stringobjects are immutable; their methods return new strings.- Compare contents with
equals;==compares references. - Key methods:
length,charAt,indexOf,substring,split,trim,replace,contains. - Use
StringBuilderwhen building a string in many steps. Integer.parseIntandString.valueOfconvert between text and numbers.
Practice questions
1. What is printed? String s = "Java"; s.concat(" 21"); System.out.println(s);
Java. concat returns a new string, which was not stored.
2. What does "education".substring(2, 5) return?
"uca": indexes 2, 3 and 4.
3. Count the words in a sentence.
String line = "Java is fun to learn";
int words = line.trim().split("\\s+").length; // 5
\\s+ splits on one or more spaces.
4. Reverse each word but keep the word order: "hello world" to "olleh dlrow".
StringBuilder out = new StringBuilder();
for (String w : "hello world".split(" ")) {
out.append(new StringBuilder(w).reverse()).append(' ');
}
System.out.println(out.toString().trim());5. Why is StringBuilder better than + inside a loop that runs 10,000 times?
Each + creates a new String object and copies all the text so far. StringBuilder appends to one growing buffer, so it does far less copying and creates far fewer objects.