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 2 of 2.

Vinod said:   1 decade ago
In obj a now "ape".

a.charAt(0) means "a".

a.charAt(1) means "p".

Ahmed said:   1 decade ago
How a.charAt(1) returns "p"?

Shraddha said:   1 decade ago
Second argument of the Substring() method is the LENGTH from first argument.
a.Substring(5,7);//Returns:"aper"
a.charAt(1); // Returns: "p"
a = a + b; // a + b = ("aper" + "p") = "aperp"

Muthuramu said:   1 decade ago
a.Substring(5,8);//Returns:"ape"(means 5,6,7)???
a.Substring(5,9);//Returns:"Aper"??? only 0 to 8 is available in string??

Sundar said:   1 decade ago
a.substring(5,7); // Returns: "ap"

a.charAt(1); // Returns: "p"

a = a + b; // a + b = ("ap" + "p") = "app" stored in a.

Therefore the string "app" is the correct answer.


Post your comments here:

Your comments will be displayed after verification.