Strings look simple, yet they cause some of the most common Java bugs and some of the most frequent interview questions. Three ideas cover most of it.
1. equals vs ==
== checks whether two variables point to the same object in memory. equals() checks whether two strings contain the same characters.
String a = "java";
String b = new String("java");
a == b // false: different objects
a.equals(b) // true: same text
Sometimes == appears to work because Java reuses identical string literals from a shared pool. That makes the bug hard to spot: code passes a quick test and fails later with input from a user or a database. Always compare text with equals(), or equalsIgnoreCase() when case should not matter. To avoid a NullPointerException, write "admin".equals(role) rather than role.equals("admin").
2. Strings are immutable
Once a String object is created, it never changes. Methods like toUpperCase() or replace() return a new string. So this does nothing useful:
name.trim(); // result thrown away
You must keep the result: name = name.trim();. Immutability makes strings safe to share between threads and safe to use as keys in a HashMap, which is why Java designed them this way.
3. StringBuilder for building text in loops
Because strings are immutable, joining them with + inside a long loop creates many temporary objects. For that job, use StringBuilder:
StringBuilder sb = new StringBuilder();
for (String item : items) {
sb.append(item).append(", ");
}
String result = sb.toString();
For a few joins outside a loop, plain + is fine and easier to read. String.join(", ", items) is often the simplest option of all.
Interview-style questions to practise
- Why is String immutable in Java?
- What is the string pool?
- What is the difference between StringBuilder and StringBuffer? (StringBuffer is synchronized and slower; StringBuilder is the usual choice.)
- Reverse a string and check whether it is a palindrome.
Continue with core Java for freshers and Java collections.
Core Java is the foundation of our Java Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
Want structured practice with a mentor? See our Java Full Stack training in Bangalore.
