The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

Question about substrings

Hello, this is my first post on this forum. Hopefully, it won't get anyone mad or upset.

My question is a logic question. Say, for example, I have this code here:

String str = "Bill Gates"
String a = str.substring(0,str.length())

The output would of course be: "Bill Gate"

My assignment is (Taken from Codingbat. Personal Hoppy, not an actual assignment!):
Given a string, return a new string made of 3 copies of the last 2 chars of the original string. The string length will be at least 2.
Ex: extraEnd("Hello") → "lololo"
extraEnd("ab") → "ababab"
extraEnd("Hi") → "HiHiHi"

But, it is wrong. I know the answer is "String new2 = str.substring (str.length()-2, str.length());" But I do not understand why. Shouldn't it be str.length()+1? based on the logic from the Bill Gates code? When using a substring, wouldn't it be the last number and subtract that number by 1? To make more sense of what I am trying to say: When I use str.length() wouldn't that be the second to last letter and not the last letter? Thanks for the help!

Re: Question about substrings

Eclipse gives a nice little explanation of what the substring method actually does:

Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

Next, it would not output "Bill Gate" it would output the entire string "Bill Gates". The index values for string length are zero based which means that the first character is at index 0 as opposed to 1. Knowing that along with the length of "Bill Gates", being 10, would mean the str.substring(0,str.length()) would return the characters at indices 0-9 (note the bold text in the quote); in other words the entire string. Your logic was not wrong if indeed the Bill Gates code was correct, just a little hiccup is all. Hopefully that helped.