×

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

Even Odd Program in Java

Even Odd Program in Java The number that are completely divisible by 2 are even and the number that leaves remainder are odd numbers. For example, the numbers 2, 0, 4,...

5 minutes read.

Implementing Queue Using Array in Java

We can implement queue by using array in Java. The queue is a linear data structure, and the array is one of the simplest data structures. Before implementing a queue...

4 minutes read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes read.

Why to use Enum in Java?

In this article, you will be acknowledged about the Enum in java, its uses and mainly its purpose. Enum has various functionalities. Each of them will be discussed. Enum In a computer...

3 minutes read.

Java Xml Parser

In this article, we acknowledge you about what is a XML parser in Java, how is it going to work and what is the purpose of it. Also, the article discusses...

6 minutes read.

Powerful Number in Java

We will define a powerful number in this article and write Java programs to determine whether a given number is a powerful number or not. Java coding interviews and academic...

6 minutes read.

String Declaration in Java

A string is a group of characters. In Java, the string can be treated as both class and datatype. In Java programming, the String class have many advantages. Everything in...

3 minutes read.

Snake and Ladder Problem in Java

Find the smallest number of dice throws necessary to reach the destination or last cell from the source or first cell on a snake and ladder board. Essentially, the player...

6 minutes read.

Trim Method in String Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

3 minutes read.

How to compare two dates in different format in Java?

We need to compare two dates frequently when coding. Real-world examples include sorting a list of persons by age or keeping track of students' attendance. To compare two dates, we...

7 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

Java Enum vs Class

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four integrators named Club, Diamond,...

7 minutes read.

Java Null Keyword

Null is a term that is only used for literal values in Java. Although it appears to be a term, it is a literal opposite of true and false. Java's...

3 minutes read.

Java URL Class with Example

Java URL Uniform Resource Locator To find any resource on the internet, you need to have an address of it. The URL and IP addresses are the pointers used for this purpose....

12 minutes read.

Matrix Multiplication Program in Java

Matrix Multiplication Program in Java The matrix multiplication program in Java is the continuation of the matrix program in Java that we have already discussed earlier. In this section, we will...

3 minutes read.

Java Math toDegrees() Method

The toDegrees() method of Java Math class converts a radian angle to an approximately equivalent angle measured in degrees. Syntax: public static double toDegrees(double angrad) Parameters: The parameter ‘angrad ‘represents an angle measured in...

2 minutes read.

Example of Static import in Java

Static keyword Java's static keyword is mainly used to control memory. Variables, methods, blocks, and nested classes are compatible with the static keyword. Instead of an instance, the static keyword is...

3 minutes read.

Java Read File to String

There are different ways to deal with forming and examining a text record. This is normal while dealing with various applications. There are different ways to deal with looking at a...

6 minutes read.

How to Convert String to Date in Java

How to Convert String to Date in java You can convert String to Date in Java by using the parse() method. There are two classes which have parse() method namely, DateFormat and SimpleDateFormat classes....

2 minutes read.

Three Partition Problems in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

8 minutes read.