Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String .. substring

 
Roopa Bagur
Ranch Hand
Posts: 267
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This question is a very basic one.. but the answer given int the Sun Guoqiao's mock exam got me confused
What is the output of trying to compile and run the following code?
(Select one correct answer)
-----------------------------------------------------------------------
public class Test023
{
public static void main(String args[])
{
String str = new String("Hello");
System.out.print(str.substring(0,3));
System.out.print(" ");
System.out.println(str.replace('r', 'h'));
}
}
-----------------------------------------------------------------------
A: Hell Hello
B: Hel Hel
C: Hel Hello
D: Hell Hell

My answer was A but the correct answer is C..
The API doc has the following example which made me believe that the string index starts from 0 & not 1.

"smiles".substring(1, 5) returns "mile"

Can anybody clear my confusion
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roopa
The correct answer is C.
String str = new String("Hello");
This line assigns the String 'Hello' to the variable str
System.out.print(str.substring(0,3));
This line prints the substring from the index 0 to the index 3-1. The substring method returns a new string from the first index to 1 less then the second index. The string is 'Hel'.

System.out.print(" ");
This line prints the space.
System.out.println(str.replace('r', 'h'));
This returns a string that has had all of the occurances of 'r' replaced with an 'h'. Since there wheren't any r's it returns the original string which is 'Hello'.
So the final output is 'Hel Hello'.
Hope that helps


------------------
Dave
Sun Certified Programmer for the Java� 2 Platform
 
Roopa Bagur
Ranch Hand
Posts: 267
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Thankyou Dave..
Originally posted by Dave Vick:
Roopa
The correct answer is C.
String str = new String("Hello");
This line assigns the String 'Hello' to the variable str
System.out.print(str.substring(0,3));
This line prints the substring from the index 0 to the index 3-1. The substring method returns a new string from the first index to 1 less then the second index. The string is 'Hel'.

System.out.print(" ");
This line prints the space.
System.out.println(str.replace('r', 'h'));
This returns a string that has had all of the occurances of 'r' replaced with an 'h'. Since there wheren't any r's it returns the original string which is 'Hello'.
So the final output is 'Hel Hello'.
Hope that helps


 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic