×

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

How to add 6 Months to the Current Date in Java?

In this tutorial, we will learn how to add 6 months to the local or current date in Java language. We will begin our topic with basic concepts and would...

3 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.

Java Class Syntax

A class is a fundamental building piece in object-oriented programming. It can be characterised as a template that outlines the information and actions connected to the creation of a class....

3 minutes read.

Java Float Keyword

Float: In general, there are two categories of data types: primitive data types and non-primitive data types. So, float is the data type which is a primitive data type. Declarating the variables and...

3 minutes read.

Addition Program in Java

Addition Program in Java We can perform the addition (sum) of two or more numbers by using the arithmetic operator (+). To write an addition program in Java, one must understand...

3 minutes read.

Java Developer

Who is a Java Developer? A Java developer is a skilled programmer who works on commercial applications, software, and webpages.  Java developers can work in two different areas: Operating system development:...

3 minutes read.

Nested Enum in Java

A class that can be defined within another class is called a nested class in Java. You can logically group classes that are used onlyin one place. This makes encapsulation...

3 minutes read.

Order of Execution of Constructors in Java Inheritance

Constructor in Java There are several distinctions between a method and a function object() in Java. The name of the function object()  is identical to the class name. There is no...

4 minutes read.

Bucket Sort in Java

Bucket Sort in JavaBucket sort is also called bin sort. Bucket sort first puts the elements of the array or list into different buckets. The first bucket contains elements of the smallest value. The...

11 minutes read.

The Maximum Rectangular Area in a Histogram in Java

Continuous bars should be used to form the largest possible rectangle. We'll assume in the interest of convenience that each bar's width is 1. Naive Approach In this method, each bar will be...

6 minutes read.

Difference Between BufferedReader and FileReader

BufferedReader: To read data from a specified character stream, two classes are used: buffered readers and file readers. Both of them have advantages and disadvantages. Although how they operate is the...

6 minutes read.

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic....

4 minutes read.

Java Math acos() Method

The acos() method of Math class computes the trigonometric Arc Cosine (inverse of cosine ) of an angle. The value returned is between 0.0 to pi. Syntax: public static double acos(double a) Parameters: The...

1 minute read.

How to Set Java_home in Linux

To set the Java_home in Linux, we must follow several steps to make us understand it easily.  Java follows the principle called WORA (write once run anywhere). We know that java...

3 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

Java Type Casting

Type casting is a technique or process used in Java to convert one data type into another, either manually or automatically. The compiler performs the automatic conversion, and the programmer...

3 minutes read.

Java Framework List

The framework is the programs which are written in Java. Frameworks in Java are used to create web applications. The code which can reuse can act as a reference for...

6 minutes read.

Best Practices to use String Class in Java

Use String Builder or String Buffer for String concatenation in place of + operator.Compare two strings by equals( ) method instead == operator.Call .equals( ) method on a known String...

3 minutes read.

How to compare characters in Java

In this tutorial, we will learn about how to compare characters in Java. To compare characters in Java, we will learn about what is a character in Java Char The character is...

4 minutes read.

Why String in Immutable in Java?

Why String in Immutable in Java Immutable means unchangeable or unmodifiable.  Strings in Java are immutable, it means once a string is created, it cannot be modified or changed. Any change...

2 minutes read.