No announcement
 

Substrings

We can extract a part of the string using substring method of the String class.

Example:

String message = “Hello World”;
String part = message.substring(0, 3);
System.out.print(part);

Output will be Hel.

You can see that the substring method takes two arguments,]. First argument is the starting index and second argument is the ending index.

The string will be extracted from starting index to ending index – 1.

In other terms, you can assume that the text cursor will start at 0 position (“↕Hello World”) and end at 3rd position (“Hel↕lo World”), so the string between the text cursor starting position and ending position (“↕Hel↕lo World”) will be our substring.

Example:

SubstringDemo.java

package com.codingnous.tutorial;

public class SubstringDemo {

	public static void main(String[] args) {

		// Declare and initialize a string.
		String message = "Hello World!";

		// Create substring from message.
		String part = message.substring(0, 3);

		// Print the substring.
		System.out.print(part);

	}

}

Output
Hel