Java Strings — Java Technical Interview Questions & Answers

Java Strings

Java Strings

  • String is text in Java — a sequence of characters. Create: String s = "Java";. That looks simple, and then interviews fail people on it. Two rules from day one: String cannot change in place (immutable), and you compare letters with equals, not ==.
  • Immutable means this: String a = "Java"; a.toUpperCase(); print a; still prints Java. toUpperCase returns a new String. The old one stays. If you want the upper text, write a = a.toUpperCase(); or store it in another variable. Freshers think the method edits a. It does not.
  • Let’s take comparison on the board. String a = new String("Hi"); String b = new String("Hi"); print a == b; print a.equals(b);. == is false — two different objects in memory. equals is true — same letters. User input from Scanner is like new String. Never compare it with ==. Literals "Hi" == "Hi" can be true because of the String Pool. That pool trick does not save you in real input.
  • Everyday APIs you should write from memory: length(), charAt(0), substring(0, 2), contains("va"), equalsIgnoreCase. Index starts at 0. substring end index is exclusive: "Java".substring(0, 2) is "Ja", not "Jav". Say that before you code.
  • Interview line: immutable + equals for content + pool for literals. If they ask only one trap, give == vs equals. If they ask why immutable, say pool + HashMap keys + security, then point to StringBuilder when you need to change text many times.
  s = "Java"
       │ toUpperCase()
       ▼
  new "JAVA"     (old s stays "Java")

Technical Interview Tip: == vs equals is the #1 String interview trap.

Code Examples for Java Strings

Example

public class Main {
  public static void main(String[] args) {
    String a = "Java";
    String b = "Java";
    System.out.println(a.equals(b));
    System.out.println(a.length());
  }
}

Java Strings — output: true then 4. "Java".equals("Java") is content; length() is 4.

How to Explain Java Strings to an Interviewer

Is String mutable?

No Immutable

How do you compare two strings?

equals Not ==

What does == compare?

References Same object, not same letters