Multiple choice technology programming languages

Given: class Polish { public static void main(String[] args) { int x = 4 ; StringBuffer sb = new StringBuffer("..fedcba"); sb.delete(3,6); sb.insert(3, "az"); if(sb.length() > 6) x = sb.indexOf("b"); sb.delete((x-3), (x-2)); System.out.println(sb); } } What is the result?

  1. .faza

  2. .fzba

  3. ..azba

  4. .fazba

  5. ..fezba

  6. Compilation fails

Reveal answer Fill a bubble to check yourself
C Correct answer
Explanation

The StringBuffer starts as '..fedcba'. delete(3,6) removes indices 3-5 ('fed'), leaving '..cba'. insert(3,'az') inserts at position 3, giving '..azcba'. Since length is 6 (not >6), x stays 4. delete(1,2) removes the '.' at index 1, yielding '.azba'. Option C is correct.

AI explanation

To determine the result of the given code, let's go through the code step by step:

  1. The code initializes an integer variable x with the value 4.
  2. It creates a StringBuffer object sb with the initial value "..fedcba".
  3. The code deletes the characters at positions 3, 4, and 5 from sb.
    • After deletion, sb becomes "..fba".
  4. The code inserts the string "az" at position 3 in sb.
    • After insertion, sb becomes "..azfba".
  5. The code checks if the length of sb is greater than 6. Since it is, the code executes the following:
  6. It assigns x the value of the index of the first occurrence of the character "b" in sb.
    • The first occurrence of "b" is at index 6.
    • Therefore, x is set to 6.
  7. The code deletes the characters at positions (x-3) and (x-2) from sb.
    • This translates to deleting characters at positions 3 and 4 from sb.
    • After deletion, sb becomes "..azba".
  8. Finally, the code prints the value of sb, which is "..azba".

Therefore, the result is "..azba".

The correct answer is option C.