Beginner · Arrays and strings · topic 13 of 60 · 30 min
Strings in depth
Explanation
Strings are objects, and immutable
String is a class in java.lang. A String object never changes after it is created; it is immutable. Every "change" (toUpperCase, replace, concat, trim) creates a new String and leaves the old one as it was. Immutability makes Strings safe to share between threads and to use as map keys.
String name = "asha";
name.toUpperCase(); // result thrown away
System.out.println(name); // asha
name = name.toUpperCase(); // keep the new String
System.out.println(name); // ASHA== versus equals: the most famous Java trap
== on objects checks whether two references point to the SAME object. equals checks whether the TEXT is the same. Java keeps string literals in a string pool: identical literals in your code share one object, so "a" == "a" is true. But strings created at run time (new String, user input, concatenation of variables, substring) are new objects.
String a = "Pune";
String b = "Pune"; // same pooled literal
String c = new String("Pune"); // a new object
String d = "Pu" + "ne"; // compile-time constant: pooled
String part = "Pu";
String e = part + "ne"; // built at run time: new object
System.out.println(a == b); // true (same pool object)
System.out.println(a == c); // false (different objects)
System.out.println(a.equals(c)); // true (same text)
System.out.println(a == d); // true
System.out.println(a == e); // false
System.out.println(a.equals(e)); // trueEveryday methods
| Method | Example | Result |
|---|---|---|
| length() | "Kolkata".length() | 7 |
| charAt(i) | "Kolkata".charAt(0) | 'K' |
| substring(a, b) | "Kolkata".substring(0, 4) | "Kolk" (b not included) |
| indexOf(s) | "banana".indexOf("na") | 2 (or -1) |
| contains(s) | "order-55".contains("55") | true |
| startsWith / endsWith | "bill.pdf".endsWith(".pdf") | true |
| toUpperCase / toLowerCase | "upi".toUpperCase() | "UPI" |
| strip() / trim() | " hi ".strip() | "hi" |
| replace(a, b) | "9-8-7".replace("-", "") | "987" (all occurrences) |
| split(regex) | "a,b,c".split(",") | ["a", "b", "c"] |
| isEmpty / isBlank | " ".isBlank() | true (Java 11+) |
| String.join | String.join("-", "a", "b") | "a-b" |
| compareTo | "apple".compareTo("banana") | negative (comes first) |
Note: replace replaces ALL occurrences of the text (it is not regex-based); replaceAll and split take regular expressions, so a literal dot is written "\\." in Java source (the regex \. inside a Java string).
Walking through characters
String pan = "ABCDE1234F";
int digits = 0;
for (int i = 0; i < pan.length(); i++) {
if (Character.isDigit(pan.charAt(i))) digits++;
}
System.out.println(digits); // 4Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Strings in depth · 1/6
In this lesson you will work with Java Strings and avoid their famous traps.
Prefer a video by a teacher? Find free videos on “java string methods equals vs == string pool immutable” on YouTube ↗
In real life: Validating a PAN number
A tax-filing website checks that a PAN has the right shape before calling the government verification API: 10 characters, five letters, four digits, one letter. This uses length, charAt and Character methods (a regex can do the same in one line).
static boolean looksLikePan(String pan) {
if (pan == null || pan.length() != 10) return false;
for (int i = 0; i < 10; i++) {
char ch = pan.charAt(i);
boolean ok = (i < 5 || i == 9) ? Character.isUpperCase(ch) : Character.isDigit(ch);
if (!ok) return false;
}
return true;
}
// looksLikePan("ABCDE1234F") → true, looksLikePan("ABCD12345F") → falsePractice (0/3 done)
What does this print? String s = "hello"; s.toUpperCase(); s.concat(" world"); System.out.println(s);
What does this print? String x = "ab"; String y = "a"; String z = y + "b"; System.out.println((x == z) + " " + x.equals(z));
Write static String initials(String fullName) that returns the upper-case initials of every word, ignoring extra spaces: initials(" ravi kumar singh ") returns "RKS". Also write static boolean isPalindrome(String s) that ignores case and spaces ("Nitin" → true).
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- StringBuilder and formattingArrays and strings · same module
- Strings and template literalsJavaScript Programming (language in depth) · Strings, decisions and loops
- Strings in depthFrontend Web Development · JavaScript in depth
- Strings: methods, interpolation, verbatim and raw stringsC# and .NET · Arrays, strings and null
- Strings are char arraysC Programming (from zero to systems) · Strings in C
- f-strings and string methodsPython Programming · Text and decisions
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
How should you compare two Strings for equal text?
Answer: a.equals(b)
equals compares content.
"Bengaluru".substring(3, 6) is…
Answer: "gal"
Indexes 3, 4, 5: g, a, l.
Why write "yes".equals(input) instead of input.equals("yes")?
Answer: It avoids a NullPointerException when input is null
Calling equals on a null reference throws; the literal is never null.
"a.b.c".split(".") returns an array of length…
Answer: 0
split takes a regex; "." matches every character, and trailing empty strings are removed, leaving an empty array. Use split("\\.").
let s = 'hi'; s.toUpperCase(); console.log(s); What is printed?Related
Answer: 'hi'
Strings are immutable; the result of toUpperCase was thrown away.
Which gives the last character of the string text?Related
Answer: text.at(-1)
at(-1) counts from the end. text[-1] is undefined, there is no last() method, and slice(0, 1) gives the first character.
From Strings in depth
What does immutable mean for strings?Related
Answer: Once made, a string's characters cannot change; methods return new strings
Every "change" creates a new string.
From Strings: methods, interpolation, verbatim and raw strings
How many bytes does "UPI" occupy as a string literal?Related
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 2 more topics in “Arrays and strings” before its exam: StringBuilder and formatting, Wrapper classes and autoboxing.
- Module 3 exam: Arrays and strings · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Classes and objects. 60 topics left in the course before the final exam.