Java - String and Substring

Introduction

substring() method returns a sub-part of a string.

substring() method is overloaded.

  • One version takes the start index as the parameter and returns a substring beginning at the start index to the end of string.
  • Another version takes the start index and the end index as parameters. It returns the substring beginning at the start index and one less than the end index. For example,

Demo

public class Main {
  public static void main(String[] args) {
    String s1 = "Hello".substring(1);    // s1 has "ello"
    String s2 = "Hello".substring(1, 4); // s2 has "ell"
    System.out.println(s1);/*from  w w  w  .j  a va2 s.c  o  m*/
    System.out.println(s2);
  }
}

Result

Related Topics

Exercise