Using the substring method in Java

Published in Java
May 18, 2023
1 min read

The substring method in the String class functions to return a part of the string in the range of the string designation index.

public String substring(int startIndex)
public String substring(int startIndex, int endIndex)
startIndex : Required. Starting index number (int type), starting from 0
endIndex : Optional. End index number (int type), if omitted, return to the end of the string.


public class Test {
public static void main(String[] args) {
String str = "code-journey.com";
System.out.println(hz.substring(0,4)); // result: code
System.out.println(hz.substring(5)); // result: : journey.com
System.out.println(hz.substring(0)); // result: : code-journey.com
System.out.println(hz.substring(5,20)); // result : (fail) StringIndexOutOfBoundsException

If the StringIndexOutOfBoundsException error occurs.

  1. If startIndex is negative number.
  2. If the endindex is greater than the string length.
  3. If startIndex is greater than endIndex.




Previous Article
What is HashSet in Java



Related Posts

How to use BigInteger in Java - 2
May 31, 2023
1 min