Multiple choice technology web technology

What is the output (Assuming written inside main) String s1 = new String("amit"); String s2 = s1.replace('m','i'); s1.concat("Poddar"); System.out.println(s1); System.out.println((s1+s2).charAt(5));

  1. Compile error

  2. amitPoddar O

  3. amitPoddar I

  4. amit I

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

String objects in Java are immutable - methods like concat() return a new String without modifying the original. After s1.concat('Poddar'), s1 remains 'amit'. s2 becomes 'aiit' after replacing 'm' with 'i'. Concatenating s1+s2 gives 'amitaiit', and charAt(5) returns 'i' (0-indexed: a-m-i-t-a-i, position 5 is 'i').

AI explanation

To answer this question, let's go through each line of code:

  1. String s1 = new String("amit"); - This line creates a new String object s1 with the value "amit".

  2. String s2 = s1.replace('m','i'); - This line creates a new String object s2 by replacing the character 'm' with 'i' in s1. So, the value of s2 will be "aiit".

  3. s1.concat("Poddar"); - This line concatenates the string "Poddar" to s1, but the result is not assigned to any variable. Therefore, the value of s1 remains unchanged, which is still "amit".

  4. System.out.println(s1); - This line prints the value of s1, which is "amit".

  5. System.out.println((s1+s2).charAt(5)); - This line concatenates s1 and s2 using the + operator, resulting in "amitaiit". It then retrieves the character at index 5, which is 'a', and prints it.

The correct answer is D) "amit I".