Strings in Java
Work with text using String methods, compare strings the right way, and build text efficiently with StringBuilder.
Learning objectives
- βUse common String methods such as length, charAt, substring and indexOf
- βExplain what immutability means and why it matters
- βCompare strings correctly with equals, equalsIgnoreCase and compareTo
- βBuild and change text efficiently with StringBuilder
π‘ Key points
- A String is an object of the String class, not a primitive. Characters are indexed from 0, like arrays.
- Strings are immutable: methods like toUpperCase() return a NEW String and leave the original unchanged.
- == checks whether two references point to the same object. equals() checks whether the characters match.
- String literals with the same text share one object in the String pool; new String(...) always makes a fresh object.
- compareTo() returns 0 if equal, a negative number if the first string comes earlier in dictionary order, and a positive number if it comes later.
- substring(begin, end) includes the begin index but stops before the end index.
- Use StringBuilder when you change text many times, for example inside a loop.
π» Code examples(6)
public class StringBasics {
public static void main(String[] args) {
String name = "Priya Sharma";
System.out.println(name.length());
System.out.println(name.charAt(0));
System.out.println(name.toUpperCase());
System.out.println(name.indexOf("Sharma"));
System.out.println(name.substring(0, 5));
System.out.println(name.contains("Sharma"));
System.out.println(name.replace('a', '@'));
}
}
12 P PRIYA SHARMA 6 Priya true Priy@ Sh@rm@
public class Immutable {
public static void main(String[] args) {
String city = "pune";
city.toUpperCase(); // result thrown away
System.out.println(city);
city = city.toUpperCase(); // keep the new String
System.out.println(city);
String s = " Amit ";
System.out.println("[" + s.trim() + "]");
System.out.println("[" + s + "]");
}
}
pune PUNE [Amit] [ Amit ]
public class CompareDemo {
public static void main(String[] args) {
String a = "Amit";
String b = "Amit";
String c = new String("Amit");
System.out.println(a == b);
System.out.println(a == c);
System.out.println(a.equals(c));
System.out.println("AMIT".equalsIgnoreCase(a));
}
}
true false true true
public class Order {
public static void main(String[] args) {
System.out.println("Amit".compareTo("Amit"));
System.out.println("Amit".compareTo("Priya"));
System.out.println("Priya".compareTo("Amit"));
System.out.println("apple".compareTo("Apple"));
String x = "Ravi", y = "Rohan";
if (x.compareTo(y) < 0) {
System.out.println(x + " comes first");
}
}
}
0 -15 15 32 Ravi comes first
public class Builder {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java");
sb.append(" is fun");
sb.insert(0, "Learning ");
System.out.println(sb);
sb.reverse();
System.out.println(sb);
StringBuilder nums = new StringBuilder();
for (int i = 1; i <= 5; i++) {
nums.append(i).append(" ");
}
System.out.println(nums.toString().trim());
}
}
Learning Java is fun nuf si avaJ gninraeL 1 2 3 4 5
public class WordCheck {
static int countVowels(String s) {
int count = 0;
for (char ch : s.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(ch) != -1) {
count++;
}
}
return count;
}
static boolean isPalindrome(String s) {
String rev = new StringBuilder(s)
.reverse().toString();
return s.equalsIgnoreCase(rev);
}
public static void main(String[] args) {
String[] words = {"Madam", "Mumbai", "Level"};
for (String w : words) {
System.out.println(w + ": vowels="
+ countVowels(w) + ", palindrome="
+ isPalindrome(w));
}
}
}
Madam: vowels=2, palindrome=true Mumbai: vowels=3, palindrome=false Level: vowels=2, palindrome=true
π― Practice
Q1. What does this print? String s = "hello"; s.toUpperCase(); System.out.println(s);+
hello. toUpperCase() returns a new String, but the result is not stored, so s is unchanged. Write s = s.toUpperCase(); to keep it.
Q2. What is "Board Formulas".substring(6)?+
"Formulas". With one argument, substring(begin) returns everything from index 6 to the end.
Q3. Two Strings both contain "Amit", but a == b is false. How is that possible?+
== compares references, not text. If one of them was made with new String("Amit") or built while the program runs, it is a different object. Use a.equals(b) to compare the text.
Q4. Reverse the String "Kerala" using StringBuilder.+
String rev = new StringBuilder("Kerala").reverse().toString(); System.out.println(rev); // alareK
Q5. Is "Zebra".compareTo("apple") positive or negative? Why?+
Negative (-7). Uppercase 'Z' is 90 and lowercase 'a' is 97, so "Zebra" counts as earlier. Use compareToIgnoreCase() when you want true alphabetical order.
π Notes
Why immutability matters
A String object never changes after it is created. That lets Java safely share a single "Amit" literal between many variables (the String pool), and it means a String you pass to a method cannot be changed behind your back.
The cost: every + on a String creates a brand-new String. In a loop this builds a lot of throwaway objects:
String s = "";
for (int i = 0; i < 1000; i++) {
s = s + i; // a new String every time
}
Use a StringBuilder and call append(i) instead. It changes one object in place.
More useful methods
split(",")breaks text into an array:"Amit,Priya,Ravi".split(",")gives 3 names.startsWith("Mr"),endsWith(".pdf")andlastIndexOf('a')help when searching.isEmpty()is true only for""(length 0).String.valueOf(25)turns a number into a String, andInteger.parseInt("25")goes the other way.
String line = "Amit,Priya,Ravi";
String[] names = line.split(",");
System.out.println(names.length); // 3
System.out.println(names[1]); // Priya
Common mistakes
- Using
==to compare text. It may work for literals because of the pool, then fail for text typed by the user. Useequals(). - Forgetting to store the result.
name.trim();on its own does nothing useful. - Going past the last index.
name.charAt(name.length())throwsStringIndexOutOfBoundsException. The last index islength() - 1. - Calling a method on
null. Ifanswermight benull, write"yes".equals(answer)rather thananswer.equals("yes"). The first version never throwsNullPointerException.
Next: Day 12, Constructors. You will see default and parameterised constructors, overloading and constructor chaining.