substring() String Example

substring() String Example


Many methods exist in java.lang.String class used for different string manipulations like checking the availability of a character, to extract a part of a string or to convert a data type to string etc. The present method is substring() String.

substring(int) and substring(int, int) extracts part of a string.

substring() method is overloaded 2 times in String class. Both will return a substring from a string. Following are method signatures.

  • public String substring(int beginIndex): Returns a new string containing characteres from beginIndex to the end of the original string.
  • public String substring(int beginIndex, int endIndex): Returns a new string containing characteres from beginIndex to endIndex-1 of the original string. Length of the substring returned will be endIndex-beginIndex.

Following example on substring() String illustrates the usage of the above 2 overloaded methods.


substring() String
Output screenshot on substring() String Example

One practical application on substring() String. To extract Web server names.


substring() String
Output screenshot on substring() String Example

firstDot+1 is used to eliminate first dot from the substring. Last dot will not come in substring as it becomes lastDot-1.

Leave a Reply

Your email address will not be published. Required fields are marked *