Java – Introduction and usage of Substring()

MartinYeung
·
·
IPFS
·

Reading time: 5 minutes

public String substring(int beginIndex, int endIndex)

A substring will be returned, and the first index of this substring will be beginIndex, and the last index will be endIndex.

The length of this substring will be endIndex-beginIndex.

This explanation will be a bit abstract, so I will illustrate it with an example.

public String substring(int beginIndex)

A substring will be returned starting from beginIndex and ending at the last letter of the String. The end position cannot be customized.

This explanation will be a bit abstract, so I will illustrate it with an example.

example:

 public class SubStringTest {
    public static void main(String args[]) {
        String Str = new String("uppengarden.com");
 
        System.out.print("Return value:" );
        System.out.println(Str.substring(4) );
//return value: engarden.com
 
        System.out.print("Return value:" );
        System.out.println(Str.substring(4, 10) );
//return value: engard

		System.out.print("Return value:" );
        System.out.println("uppengarden.com".substring(4, 10) );
//return value: engard

    }
}

explain:

substring(int beginIndex, int endIndex)

There are two main parameters as follows:

beginIndex – the starting position, including the current index.

endIndex – the position of the end, excluding the current index.

There will be a chance of the following Error Exception:

IndexOutOfBoundsException

  • starting index is negative
  • The index at the end is greater than the length of the String
  • The starting index is greater than the ending index


CC BY-NC-ND 2.0

Like my work? Don't forget to support and clap, let me know that you are with me on the road of creation. Keep this enthusiasm together!

MartinYeungLove life Love IT IT blog: https://ithelp.ithome.com.tw/users/20119569
  • Author
  • More

Java - Volatile keyword的介紹

Java - Atomic VS Volatile

Java - Thread-Safety是什麼 - Part 3