×

Java String substring() method

Java String substring() method returns a part of the String.

Syntax:

public String substring(int startIndex)
public String substring(int startIndex, int endIndex)

Parameters:

startIndex : starting index

endIndex : ending index

Returns:

It returns a specified String.

Throws:

StringIndexOutOfBoundsException if start index is negative value or end index is lower than starting index.

Java String substring() method example 1

 public class JavaStringSubstringEx1 
    { 
       public static void main(String args[])
       { 
    String s1="tutorialand example"; 
    System.out.println(s1.substring(0,8));
    System.out.println(s1.substring(8));
       }
    }

Output:

tutorial and example

Java String substring() Method Example 2

      public class JavaStringSubstringEx2
       { 
           public static void main(String[] args)
           { 
            String s1="tutorialandexample";   
            String substr = s1.substring(0); // Starts with 0 and goes to end 
            System.out.println(substr); 
            String substr2 = s1.substring(5,10); // Starts from 5 and goes to 10 
            System.out.println(substr2);   
            String substr3 = s1.substring(5,15); // Returns Exception 
        } 
    }

Output:

tutorialandexample
ialan

Java String substring() Method Example 3

import java.lang.*;
public class JavaStringSubstringEx3 {
   public static void main(String[] args) {
      String str = "Welcome to tutorial and example";
      String substr = "";
     // prints the substring after index 0 till index 7
      substr = str.substring(0, 7);
      System.out.println("substring after index 0 to 7  ==> " + substr); 
      // prints the substring after index 7 till index 31
      substr = str.substring(7, 31);
      System.out.println("substring after index 7 to 31 ==> " + substr);    
   }
}

Output:

 substring after index 0 to 7  ==> Welcome
 substring after index 7 to 31 ==>  to tutorial and example

Java String substring() Method Example 4

public class JavaStringCentersubStringEx4 {
   public static void main(String[] args) {
      System.out.println("A       --> " + centerString("A"));
      System.out.println("AB      --> " + centerString("AB"));
      System.out.println("ABC     --> " + centerString("ABC"));
      System.out.println("ABCD    --> " + centerString("ABCD"));
      System.out.println("ABCDE   --> " + centerString("ABCDE"));
      System.out.println("ABCDEF  --> " + centerString("ABCDEF"));
      System.out.println("ABCDEFG --> " + centerString("ABCDEFG"));
   }
   private static String centerString(String str) {
      if (str.length() <= 2) {
         return str;
      }
      int beginIndex = (str.length() - 1) / 2;
      int endIndex = beginIndex + 2 - (str.length() % 2);
      return str.substring(beginIndex, endIndex);
   }
}

Output:

A       --> A
AB      --> AB
ABC     --> B
ABCD    --> BC
ABCDE   --> C
ABCDEF  --> CD
ABCDEFG --> D

Related Topics

Java Single Linkedlist

Like arrays, linked lists are a type of linear data structure. Unlike arrays, which store each element in the same location, linked lists employ pointers to connect the elements together. In...

25 minutes read.

How to remove last character from String in Java

In java, there are predominantly three classes connected with the string. The classes are String, StringBuilder, and StringBuffer class that gives techniques connected with string control. Eliminating the first and...

5 minutes read.

How to Convert long to String in Java

How to Convert long to String in java It is used if we have to display a long number in the text field because everything is displayed as a String. A...

3 minutes read.

Java vs Go

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

Heart Pattern in Java

Heart Pattern is yet another intricate pattern program, however, due to its complexity, interviewers hardly ever inquire about it. Method for Printing the Heart Number Pattern Put the value of the total row...

2 minutes read.

Ordinal Number in Java

What is the Ordinal Number in Java? An object's or person's position or rank can be expressed mathematically using an ordinal number. Depending on the criteria used to establish the positions,...

3 minutes read.

Missing Number in an Arithmetic Progression in Java

Given an array that shows the elements of an orderly arithmetic progression. Find the missing number to complete the succession of elements. Example:  Input: a [ ] = {2 , 4 , 6...

3 minutes read.

Java vs Scala

Java : Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say...

4 minutes read.

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.

Class vs Object in Java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Arithmetic Operations on String in Java

Introduction Arithmetic, Relational, Bitwise, and Logical operators are all available in Java. Simple mathematical calculations are performed using Java arithmetic operators. Basic Arithmetic operators are considered in Java to be Addition,...

4 minutes read.

Java String concat() method:

Java String concat() method is used to add the given String to the end of the current String. Syntax: public String concat(String str) Parameter: Str: String to be concatenated at the end of current...

1 minute read.

BigDecimal toString() in Java

BigDecimal is a Java class that is a part of the java.math package and the java.base module. It implements the ComparableBigDecimal> interface and extends the Number class. The BigDecimal class...

3 minutes read.

Minimum XOR value pair in Java

In this section, you will discuss about minimum XOR value pair in Java. The objective is to enforce a value that indicates the least XOR values of the two numbers from...

4 minutes read.

How to sort an array in Java

Sorting is the process of arranging the elements of a list or array in a specific order, either ascending or descending. The sorting criterion numerical and alphabetical is commonly used...

6 minutes read.

Types of Bitwise Operators in Java

In this tutorial, we will learn about the various types or kinds of bitwise operators in java. Before proceeding to bitwise operators, let us know what is meant by the...

6 minutes read.

IdentityHashMap in Java

The IdentityHashMap class is comparable to the HashMap class and is an AbstractMap implementation. However, when comparing the key, it uses reference equality rather than object equality (or values). Identity HashMap...

6 minutes read.

For Loop Program in Java

For Loop Program in Java The for-loop program in Java is written when we want a particular set of statements to be executed repeatedly until the given criteria/ condition is met....

8 minutes read.

Java Integer valueOf() method

The valueOf() method of Java Integer class returns an Integer object holding the specified int value. The second method returns an Integer object holding the specified String value. The third syntax returns...

2 minutes read.

Java vs Node.js

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.