Java Programming - Java.lang Class - Discussion

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);

[A]. apa
[B]. app
[C]. apea
[D]. apep

Answer: Option B

Explanation:

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


Sundar said: (Aug 25, 2011)  
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.

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

Shraddha said: (Jan 16, 2012)  
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"

Ahmed said: (Nov 26, 2012)  
How a.charAt(1) returns "p"?

Vinod said: (Jun 11, 2013)  
In obj a now "ape".

a.charAt(0) means "a".

a.charAt(1) means "p".

Amit Agrawalla said: (Jun 18, 2013)  
@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.

Veena said: (Nov 4, 2013)  
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"

Mukesh said: (Oct 4, 2014)  
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.

Aaa said: (Oct 10, 2014)  
7-5 = 2 means length is 2.
a = ap.

a.charAt(1) = p.

Abhi said: (Sep 10, 2015)  
a.substring (5, 7) will return ape.

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

How app anyone please explain?

Sai said: (Sep 15, 2015)  
a.substring (5,7-1).

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

And a.charAt (1).

Result is app//

Arvin said: (Sep 2, 2016)  
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.

Zen said: (Sep 2, 2016)  
substring(beginIndex, endIndex)

beginIndex - inclusive.
endIndex - exclusive.

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

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

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.