Predict the output · Java
Strings and immutability
String operations, joining with numbers, and comparisons.
Learn: Predicting what Java string code prints7 minute read
A "predict the output" question shows you a short program and asks what it prints. String questions are very common in Java interviews for testers, because test code handles text all day: page titles, API responses, CSV data. The interviewer wants to see that you know a few exact rules, and that you can trace code one line at a time without running it. This page covers those rules, from the basics up.
Rule 1: a String never changes
A String is immutable: once it is created, its characters never change. Methods that seem to change it, such as toUpperCase, concat, replace or trim, return a new string. If nothing stores the result, it is lost. So whenever a string method call sits on its own line, ask: was the result assigned?
Rule 2: + works from left to right
Java works through a chain of + from left to right, one pair at a time. While both sides are numbers, it adds. As soon as one side is a String, it joins text, and the result is a String, so every later + joins too. Brackets are evaluated first.
public class Main {
public static void main(String[] args) {
String s = "qa";
s.toUpperCase();
System.out.println(s);
s = s.toUpperCase();
System.out.println(s);
System.out.println(1 + 2 + "x" + 1 + 2);
}
}
qa QA 3x12
In the last line, 1 + 2 is 3, then 3 + "x" is "3x", and from there the 1 and the 2 are joined as text.
Rule 3: == compares objects, equals compares text
A String variable holds a reference to a string object (think of it as the object's address). == asks "do both sides point at the same object?". equals asks "do they hold the same characters?".
Java keeps one shared copy of each string literal (text written in quotes) in the string pool. So two literals with the same text are the same object, and == happens to be true. new String(...) always builds a separate object. A join of two literals, such as "te" + "st", is done by the compiler (the tool that turns your code into a runnable program, before it runs) and also comes from the pool. A join that involves an ordinary variable happens while the program runs and makes a new object. intern() returns the pooled copy.
Rule 4: a char is a number in arithmetic
A char holds a character code: 'a' is 97. In arithmetic it becomes an int, so 'a' + 'b' is 195. That sum is a number. It shows as a letter again only when a string joins in first, as in "" + 'a' + 'b', or when you cast the number back to char. A cast, such as (char) 98, converts a value to another type.
public class Main {
public static void main(String[] args) {
String a = "test";
String b = "te" + "st";
String c = new String("test");
System.out.println(a == b);
System.out.println(a == c);
System.out.println(a.equals(c));
System.out.println('t' + 1);
}
}
true false true 117
Rule 5: indexes start at 0 and the end is excluded
In "automation", a is index 0 and n is index 9. substring(2, 5) takes indexes 2, 3 and 4, so the end index is not included. indexOf returns the first match and lastIndexOf the last, and both return -1 when nothing is found. Write the indexes under the word before you answer.
Rule 6: StringBuilder changes in place
StringBuilder is the mutable partner of String. append and reverse change the builder itself and return that same object. It does not write its own equals, so it uses the basic one from Object, which only checks whether both sides are the same object. Two builders with the same text are therefore not equal. Compare toString() results instead.
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("ab");
StringBuilder same = sb.append("c");
System.out.println(sb + " " + (same == sb));
System.out.println(new StringBuilder("x").equals(new StringBuilder("x")));
System.out.println("automation".substring(2, 5) + " " + "automation".indexOf('o'));
}
}
abc true false tom 3
Rule 7: some methods read a regular expression
split, replaceAll and matches treat their argument as a regular expression, a small pattern language. In a pattern, a dot means "any character", so splitting on "." does not split on dots. Escape it with a backslash: "\\.". Inside a Java string the backslash must be written twice, so the pattern Java sees is \., which means a real dot. replace treats its argument as plain text. split also drops empty strings at the end of the result but keeps empty strings in the middle.
Rule 8: null joins as the text "null"
Joining a null reference with + does not throw. It adds the four letters null. Calling a method on a null reference, such as s.length(), throws a NullPointerException, which is a runtime error: the program stops.
public class Main {
public static void main(String[] args) {
System.out.println("1.2.3".split("\\.").length);
System.out.println("x,,y,,".split(",").length);
String missing = null;
System.out.println("id=" + missing);
}
}
3 3 id=null
How to answer in an interview
Say the output first, then the rule that produces it, in one or two sentences. For example: "It prints false, because == compares references and new String makes a new object. I would use equals in real code." If a line is tricky, trace it out loud, one operator at a time. Interviewers care about the reasoning as much as the answer.
Common mistakes
- Thinking
s.toUpperCase();changess. - Adding numbers that come after a string in a
+chain. - Using
==to compare text in test assertions (the checks in your test code). - Counting from 1, or including the end index of
substring. - Forgetting that
splitreads a pattern.
Recap
Strings are immutable. + goes left to right and switches to joining at the first string. == compares objects while equals compares text. Chars are numbers in arithmetic, and split takes a pattern. In real test code, compare strings with equals and keep == for numbers and null checks.
10 questions0/10 solved
| Status | Question | Difficulty | Asked in |
|---|---|---|---|
| Not started | A string method whose result is not kept | Easy | |
| Not started | Numbers and strings joined with + | Easy | Asked in: Infosys, PhonePe, Wipro |
| Pro+ | String literals, new String and == | Easy-Medium | Asked in: Accenture, Capgemini, Cognizant +3 |
| Pro+ | Adding two chars | Easy-Medium | Asked in: Mastercard, TCS |
| Pro+ | substring, indexOf and lastIndexOf | Easy-Medium | |
| Pro+ | String joins done by the compiler and at run time | Medium | Asked in: Cognizant, Oracle |
| Pro+ | Comparing two StringBuilders | Medium | |
| Pro+ | split and the empty strings at the end | Medium | |
| Pro+ | Joining text to a null String | Medium | |
| Pro+ | replace, replaceAll and split with a dot | Medium-Hard |
The first 2 questions of each topic are free. Pro+ opens every question.