File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes substring() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "substring()" Watch "substring()" New topic


jose chiramal
Ranch Hand

Joined: Feb 12, 2010
Posts: 266
Any reason why the ending argument is not zero based in substring() ? It just adds to confusion !!!

String x="0123456789";

s.o.pln(x.substring(5)); output is 56789
s.o.pln(x.substring(5,8)); output is 567
Pushkar Choudhary

Joined: May 21, 2006
Posts: 425

Am I missing something here? What you've shown seems perfectly fine to me.
Have you read this?
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46367
You can work out the length of the substring easily by subtracting the two numbers.

It is probably like that because older functions in C/C++ used that numbering convention, and Gosling kept what he thought was familiar to programmers in 1995.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15084

The ending number is zero-based, but you have to specify the index one past the last character that you want to be included. So the starting index is inclusive, and the ending index is exclusive. As Campbell says, it's probably that way because of conventions in other programming languages.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Henry Wong

Joined: Sep 28, 2004
Posts: 20526

Agreed. The concept of inclusive start and exclusive end, is used in practically every other system that has substring -- and is intuitive to anyone that has ever used substring in any programming language.

On the other hand, I guess it can get confusing to someone who is just learning his/her first language.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
I agree. Here's the link:
subject: substring()
It's not a secret anymore!