ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

How to Use Substring() in Java Programming

Updated on February 26, 2013

What is a substring() in Java Programming

Substring() is a pre-defined method under the pre-defined class String. There are 2 kinds of substring(), first is with only 1 parameter and second is with 2 parameters.

Substring() #1: substring(int firstIndex)

Substring() #2: substring(int firstIndex, int lastIndex)

How to Use Substring() in Java Programming?

You can use substring() if you want to return a certain string minus the specified index or indexes of a certain string, print it on the screen or simply use it as a condition.

For example: If we will use the substring() #1 to return a certain string. Here how it goes.

Declared_String: Learn Java Programming

Java Code: Declared_String.substring(1);

The Java Code above will return ‘earn Java Programming’, without the first index ‘L’ since ‘L’ is the first index of ‘Learn Java Programming’. Similarly, if we have declared strings like as follows:

‘Decode’ with substring(2), it will return the string ‘code’ without the 2 indexes ‘d and e’, while if we have:

'Debugging' with substring(2, 5), it will return the string ‘bug’ without 2 first indexes ‘d and e’ and last 4 indexes ‘g, i, n and g, ’.

Note: that for substring(int firstIndex, int lastIndex), the last index meant in there is the number you declare minus 1. Like that on substring(2, 5), the 5 there was subtracted to 1, so it only subtracted 4 indexes instead of 5. To see the running code for this, check the code below:

package substringinjava;

import java.util.Scanner;

public class Main {

    public static void main(String[] args)
        String word1 = "Learn Java Programming";
        System.out.println("Result for 'Learn Java Programming' with substring(1)");

        String word2 = "decode";
        System.out.println("Result for Return 'decode' with substring(2)");

        String word3 = "debugging";
        System.out.println("Return for 'debugging' with substring(2, 5)");
        System.out.println(word3.substring(2, 5));



Sample Output:

If you find this hub useful to you, please rate and share it. Happy Programming!


    0 of 8192 characters used
    Post Comment

    No comments yet.