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);
For the following code snippet choose the correct output:
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
Your Answer
Choose the Best Option
Click any option to instantly check if you're correct.
Correct Answer: Option D
Explanation
[Strings]
For the following code snippet choose the correct output:
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);
String str = String.valueOf(x);
System.out.println(str.length());
System.out.println(x + x);
System.out.println(str + str);
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
468
234234
Conclusion:
Therefore, the correct answer is: (d)
| Statement | Result |
|---|---|
| str.length() | 3 |
| x + x | 468 |
| str + str | 234234 |
Continue Practice
Share
Share This Question
Challenge a friend or share with your study group.
More from This Topic