How to Get Substring from String in Java


In this example, we will learn how to get substring of the given java string object with substring method of java String class.

Source Code

package com.beginner.examples;

public class SubstringExample {

	public static void main(String[] args) {
		
		String string  = "Hello World !";
		
		/*
		 * To get substring of Java String use the method substring(int startIndex). 
		 * This method returns new String object containing the substring of the 
		 * given string from specified startIndex (inclusive).
		 */
		System.out.println(string.substring(6));
		
		/*
		 * To get substring of Java String use the method substring(int startIndex,int endIndex).
		 * This method returns new String object containing the substring of the 
		 * given string from specified startIndex to endIndex. Here, startIndex is 
		 * inclusive while endIndex is exclusive.
		 */
		System.out.println(string.substring(0,5));

	}

}

Output:

World !
Hello
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments