MCQ Single Best Answer Moderate

Q
[Strings]

For the following code snippet choose the correct output:
int x = 234;
String str = String.valueOf(x);
System.out.println(str.length());
System.out.println(x + x);
System.out.println(str + str);

ID: #24942 Competency focused Practice Questions ISC Class XII Computer Science 5 views
Question Info
#24942Q ID
ModerateDifficulty
Competency focused Practice Questions ISC Class XII Computer ScienceTopic

Choose the Best Option

Click any option to instantly check if you're correct.

  • A
    2
    234234
    234234
  • B Error
  • C
    3
    234234
    468
  • D
    3
    468
    234234
Correct Answer: Option D

Explanation

[Strings]

For the following code snippet choose the correct output:
int x = 234;
String str = String.valueOf(x);
System.out.println(str.length());
System.out.println(x + x);
System.out.println(str + str);
(a)
2
234234
234234
(b) Error
(c)
3
234234
468
(d)
3
468
234234
Correct Answer: (d)

Step-by-Step Explanation:

Step 1: Integer Declaration

int x = 234;

Here, the integer variable x stores the value:

234

Step 2: Converting Integer to String

String str = String.valueOf(x);

The String.valueOf() method converts the integer into a String.

So:

str = "234"

Step 3: Finding String Length

System.out.println(str.length());

The string "234" contains:

  • 2
  • 3
  • 4

Total characters = 3

Output: 3

Step 4: Integer Addition

System.out.println(x + x);

Since x is an integer:

234 + 234 = 468

Therefore output is:

Output: 468

Step 5: String Concatenation

System.out.println(str + str);

Here, both operands are Strings. So Java performs String Concatenation.

"234" + "234" = "234234"

Therefore output is:

Output: 234234

Final Output:

3
468
234234

Conclusion:

Therefore, the correct answer is: (d)

Statement Result
str.length() 3
x + x 468
str + str 234234

Share This Question

Challenge a friend or share with your study group.