StringBuilder & Immutability Questions with Answers

22 practice questions on StringBuilder & Immutability (Core Java) with answers and step-by-step solutions. Try 10 samples below, then practise all 22 free in the AptiNest app.

Sample questions

Question 1Easy

What is the main difference between StringBuilder and StringBuffer?

  1. StringBuilder is immutable; StringBuffer is mutable
  2. StringBuffer's methods are synchronized; StringBuilder's are not
  3. StringBuffer cannot be converted to a String
  4. StringBuilder stores characters in the string pool

Answer: B. StringBuffer's methods are synchronized; StringBuilder's are not

Explanation

Both are mutable character sequences with the same API. StringBuffer synchronizes its methods for thread safety, so StringBuilder is faster in single-threaded code.

Step-by-step solution

  1. StringBuilder methods are not synchronized; StringBuffer methods are synchronized.
  2. Synchronization makes StringBuffer thread-safe but slower than StringBuilder.
  3. Both classes allow dynamic modification of character sequences.
  4. StringBuffer is suitable for multi-threaded environments; StringBuilder is faster in single-threaded code.
  5. The main difference lies in method synchronization for thread safety.
  6. Correct answer: StringBuffer's methods are synchronized; StringBuilder's are not.

Why the other options are wrong

  • A. Both StringBuilder and StringBuffer are mutable; neither one is immutable.
  • C. StringBuffer can be converted to a String with toString(), so this claim is false.
  • D. StringBuilder keeps its characters in its own buffer, not in the string pool.

Tip: Use StringBuffer in multi-threaded apps; choose StringBuilder for speed in single threads.

Question 2Easy

Which of these classes is immutable?

  1. java.lang.Integer
  2. java.lang.StringBuilder
  3. java.util.ArrayList
  4. java.lang.StringBuffer

Answer: A. java.lang.Integer

Explanation

Wrapper classes such as Integer, like String, cannot change their value after construction. The others are mutable containers.

Step-by-step solution

  1. java.lang.Integer is a wrapper class for int and cannot be changed after creation.
  2. StringBuilder allows modification of its content, so it is mutable.
  3. ArrayList stores elements in a dynamic array and can change size, making it mutable.
  4. StringBuffer lets characters be added or removed, so it is also mutable.
  5. Only java.lang.Integer remains unchanged once created, making it immutable.
  6. Final answer: java.lang.Integer.

Why the other options are wrong

  • B. StringBuilder has methods that change its content, so it is mutable and not immutable.
  • C. ArrayList can add and remove elements, so it is mutable and not immutable.
  • D. StringBuffer lets characters be changed, so it is mutable and not immutable.

Tip: Remember: Wrapper classes like Integer and String are immutable, while builders and arrays are mutable.

Question 3Easy

What is the output?

public class Main {
    public static void main(String[] args) {
        String s = "abc";
        s = s + "d";
        System.out.println(s);
    }
}
  1. dabc
  2. Compilation error
  3. abcd
  4. abc

Answer: C. abcd

Explanation

The original "abc" object is not modified; s is simply reassigned to a new String "abcd".

Step-by-step solution

  1. S starts as 'abc' and then becomes 'abcd' by adding 'd'.
  2. s + "d" creates a new string 'abcd' and assigns it to s.
  3. System.out.println(s) prints the value of s, which is 'abcd'.

Why the other options are wrong

  • A. The d is added at the end with +, so the result is abcd, not dabc.
  • B. The code compiles, since reassigning s to s + d is valid for a String variable.
  • D. s is reassigned to abcd, so the output is abcd and not abc.

Tip: String concatenation creates a new string, not modifying the original.

Question 4Easy

What is the output?

public class Main {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("cat");
        sb.append("s").insert(0, "big ");
        System.out.println(sb + " " + sb.length());
    }
}
  1. big cats 8
  2. big cats 7
  3. big cat 7
  4. catsbig 8

Answer: A. big cats 8

Explanation

append gives "cats", insert(0, "big ") puts the text at the front, giving "big cats", which has 8 characters.

Step-by-step solution

  1. Start 'cat'; append 's' -> 'cats'.
  2. insert(0,'big ') -> 'big cats'.
  3. Length is 8.

Why the other options are wrong

  • B. 'big cats' has 8 characters including both spaces.
  • C. The s was appended.
  • D. insert at 0 puts text in front.

Tip: Count spaces too.

Question 5Medium

What is the output?

public class Main {
    public static void main(String[] args) {
        String s1 = "Java";
        String s2 = s1;
        s1 += "17";
        System.out.println(s2 + " " + (s1 == s2));
    }
}
  1. Java17 false
  2. Java true
  3. Java17 true
  4. Java false

Answer: D. Java false

Explanation

s1 += "17" makes s1 point to a new String. s2 still points to the original "Java", so the references differ.

Step-by-step solution

  1. s2 points to the original 'Java'.
  2. s1 += '17' creates a new String Java17.
  3. s2 stays Java.
  4. They are different objects: false.

Why the other options are wrong

  • A. s2 is not changed by s1.
  • B. s1 no longer points to the same object.
  • C. s2 remains Java.

Tip: Immutable: change = new object.

Question 6Medium

What is the output?

public class Main {
    public static void main(String[] args) {
        StringBuilder a = new StringBuilder("hi");
        StringBuilder b = new StringBuilder("hi");
        System.out.println(a.equals(b) + " " + a.toString().equals(b.toString()));
    }
}
  1. false false
  2. true true
  3. true false
  4. false true

Answer: D. false true

Explanation

StringBuilder does not override equals(), so it compares references. Converting to String compares content.

Step-by-step solution

  1. a.equals(b) checks reference equality, returns false.
  2. a.toString() converts to String, which overrides equals(), so comparison is by content.
  3. String content of a and b is same, so a.toString().equals(b.toString()) returns true.
  4. Final output is false true.
  5. Answer: false true.

Why the other options are wrong

  • A. The second comparison is true, since toString() gives two String objects with the same content.
  • B. StringBuilder does not override equals, so a.equals(b) compares references and is false.
  • C. a.equals(b) compares references, not content, so the first value is false.

Tip: Remember: StringBuilder uses reference equality unless converted to String.

Question 7Medium

What is the output?

public class Main {
    public static void main(String[] args) {
        final StringBuilder sb = new StringBuilder("a");
        sb.append("b");
        System.out.println(sb);
    }
}
  1. Compilation error
  2. ab
  3. ba
  4. a

Answer: B. ab

Explanation

final makes the variable unreassignable, not the object immutable. Calling append on the referenced StringBuilder is allowed.

Step-by-step solution

  1. Sb starts as 'a' with final keyword.
  2. append('b') adds 'b' to sb making it 'ab'.
  3. System.out.println(sb) prints the result of sb which is 'ab'.
  4. No compilation error because final only prevents reassignment, not modification of object content.
  5. Final variable can still have its contents changed via methods like append().
  6. Final answer: B (ab).

Why the other options are wrong

  • A. The code compiles, since final only stops reassigning sb, and append changes its content.
  • C. append adds b to the end, so the result is ab, not ba.
  • D. append was called, so b is added and the output is ab, not a.

Tip: Final only prevents reassignment, not modification of object contents.

Question 8Medium

What is the output?

public class Main {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 5; i++) {
            sb.append(i).append(i % 2 == 0 ? "-" : "");
        }
        System.out.println(sb);
    }
}
  1. 01234
  2. 0-1-2-3-4-
  3. 0-12-34-
  4. 0-12-34

Answer: C. 0-12-34-

Explanation

A dash is appended only after even numbers: "0-" "1" "2-" "3" "4-", giving "0-12-34-".

Step-by-step solution

  1. The loop runs i from 0 to 4.
  2. Each time, i is appended. A dash is appended only when i is even.
  3. i=0 gives 0-, i=1 gives 1, i=2 gives 2-, i=3 gives 3, and i=4 gives 4-.
  4. Joined together this is 0-12-34-, option C.

Why the other options are wrong

  • A. The dashes are missing, but a dash follows each even number.
  • B. Odd numbers get no dash, so 1 and 3 are not followed by a dash.
  • D. The last even number, 4, also gets a dash, so the output ends with a dash.

Tip: Check the condition of the ternary for each loop index. When it is false, an empty string is appended.

Question 9Hard

What is the output?

public class Main {
    static void change(String s) { s = s + "y"; }
    static void change(StringBuilder sb) { sb.append("y"); }

    public static void main(String[] args) {
        String s = "x";
        change(s);
        StringBuilder sb = new StringBuilder("x");
        change(sb);
        System.out.println(s + " " + sb);
    }
}
  1. x x
  2. xy xy
  3. xy x
  4. x xy

Answer: D. x xy

Explanation

Java passes references by value. Reassigning the String parameter does not affect the caller, but append() mutates the shared StringBuilder object.

Step-by-step solution

  1. String is immutable, so changing s inside change() creates a new string, not affecting original s.
  2. StringBuilder is mutable, so appending 'y' to sb inside change() modifies the shared object.
  3. S remains 'x' after first call to change().
  4. Sb becomes 'xy' after second call to change().
  5. Final output is x xy.

Why the other options are wrong

  • A. The StringBuilder changes in change(sb), so sb is xy and the first output cannot be x x.
  • B. String s is immutable, so change(s) cannot alter s, and s stays x.
  • C. The output order is wrong: s is printed first and stays x, and sb is printed second as xy.

Tip: Remember: Strings don't change, StringBuilder does.

Question 10Hard

What is the output?

public class Main {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("abc");
        sb.setLength(2);
        sb.append(sb.length());
        sb.setLength(5);
        System.out.println(sb.toString().replace('\0', '.'));
    }
}
  1. abc2.
  2. ab3..
  3. ab2
  4. ab2..

Answer: D. ab2..

Explanation

setLength(2) truncates to "ab", append adds "2", and setLength(5) pads with null characters, which are shown here as dots.

Step-by-step solution

  1. Sb is "abc". setLength(2) cuts it to "ab".
  2. sb.length() is 2, so append adds "2", giving "ab2".
  3. setLength(5) pads the string with two null characters, giving "ab2" followed by two \0 characters.
  4. replace('\0', '.') turns each null into a dot, giving ab2.., option D.

Why the other options are wrong

  • A. setLength(2) removed the c, so the text does not contain abc.
  • B. The appended number is 2, because the length was 2 when append ran, not 3.
  • C. setLength(5) pads to length 5, so two dots follow the 2.

Tip: SetLength cuts the text when it shrinks, and pads with null characters when it grows.

Practise all 22 questions free

The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.

Open this topic in the app →

Related topics

See all Core Java topics · All topics