✏️ Explanatory Question

[String]

Question:

Find the output of the following snippet:

String S1 = "AB", S2 = "BC";

for(int i = 0, j = 0; i < S1.length(); i++, j++)
{
    System.out.println(S1.charAt(i) + S2.charAt(j));
}

👁 10 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

Answer:

131
133

Explanation:

The loop runs for:

S1.length() = 2

So there will be 2 iterations.

Character ASCII Values:

'A' = 65
'B' = 66
'C' = 67

First Iteration:

S1.charAt(0) = 'A'
S2.charAt(0) = 'B'

ASCII addition:

65 + 66 = 131

Output:

131

Second Iteration:

S1.charAt(1) = 'B'
S2.charAt(1) = 'C'

ASCII addition:

66 + 67 = 133

Output:

133

Important Concept:

  • charAt() returns characters
  • When characters are added using +, Java adds their ASCII values
  • Therefore, numeric output is produced instead of string concatenation

Final Output:

131
133