Java Programming - Java.lang Class - Discussion

Discussion Forum : Java.lang Class - Finding the output (Q.No. 19)
19.
What will be the output of the program?
String a = "newspaper";
a = a.substring(5,7);
char b = a.charAt(1);
a = a + b;
System.out.println(a);
apa
app
apea
apep
Answer: Option
Explanation:

Both substring() and charAt() methods are indexed with a zero-base, and substring() returns a String of length arg2 - arg1.

Discussion:
15 comments Page 1 of 2.

Dakota Hobson said:   2 years ago
The output of this code would be "ape", because:

The variable `a` is initialized with the string "newspaper".
The `substring()` method is used to extract a new string from `a` starting at index 5 (inclusive) and ending at index 7 (exclusive). This results in the string "ap".

The 'charAt()' method is used to retrieve the character at index 1 of the string "ap", which is the character 'p'.
The variable 'b' is assigned the value of 'p'.
The string concatenation operator `+` is used to concatenate the string "ap" and the character 'p', resulting in the string "ape".
Finally, the 'println()' method is used to print the value of the variable `a`, which is now "ape".

Srinu said:   8 years ago
Length start from 0 now (sunstring(5,7) return ape)
charAt(1) retuns=p then,
Final the output.

Zen said:   9 years ago
substring(beginIndex, endIndex)

beginIndex - inclusive.
endIndex - exclusive.

That's why a.substring(5,7) = ap.

Arvin said:   9 years ago
How is a.substring(5,7) same as a.substring(5,6)?

Execute it and see, following is the right answer, everything else is wrong.

a = a.substring(5,7) = n(0)e(1)w(2)s(3)p(4)a(5)p(6)e(7)r(8) = ape

It will take from 5th, 6th, and 7th position.

Then next,

a.charAt(1) = e

Final result = apep

That's it.

Sai said:   10 years ago
a.substring (5,7-1).

a.substring (5,6) will return ap.

And a.charAt (1).

Result is app//

Abhi said:   10 years ago
a.substring (5, 7) will return ape.

And charAt (1) will be p. So answer will be apep.

How app anyone please explain?

Aaa said:   1 decade ago
7-5 = 2 means length is 2.
a = ap.

a.charAt(1) = p.

Mukesh said:   1 decade ago
a.substring(5,7) will return ape.

So the final output should be apep...

Please explain why the first line is returning ap only and not ape.

Veena said:   1 decade ago
In string the position is starts from 0.

So count letters in "newspapers" as of a.substring(5,7); will count from 0 and its start taking letters after 5 till (7-1).

i.e till 6th letter.

So a.substring(5,7); will contains "ap"

Amit Agrawalla said:   1 decade ago
@Ahmed : as a.substring(5,7); // Returns: "ap"

So now a has "ap" that is a is in zero place and p in the 1 place.

So charAt(1) implies 1 place of a. that is p.


Post your comments here:

Your comments will be displayed after verification.