×

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

flour pack problem in Java

Create a method called canPack and give it three int parameters: bigCount, smallCount, and objective. The bigCount option indicates the number of large flour bags (5 kilos each). The smallCount argument indicates...

3 minutes read.

Accessors and Mutator in Java

Introduction Accessors and mutators are used in Java to get and set the value of private fields, respectively. Accessors and mutators are both referred to as getters and setters, respectively. The...

6 minutes read.

Java time local date

Java: Java is one of the programming language which is object oriented. It consists of many features such as robust, simple, architecture neutral, dynamic, distributed, multi threaded, portable etc. The main feature...

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

Java Network Programming (Socket Programming in Java)

JAVA NETWORK Network programming is used to execute programs across multiple machines that are connected by a network. The java.net package contains a collection of classes and interfaces that provide this...

3 minutes read.

Bounded buffer problem in Java

The Bounded buffer Problem can also be called a Producer consumer problem. The problem covers two processes—the producer and the consumer—that share a single, fixed-size buffer that serves as a...

4 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 Char Keyword

The java char keyword is a data type which is defined as character data type.Char keyword belongs to a primitive data type where the data types are classified into primitive...

4 minutes read.

Rehashing in Java

The most crucial idea mostly in the data structure is hashing, which is utilized to change a particular key into some other value. The hash function can be used to...

7 minutes read.

Difference between String Tokenizer and split Method in Java

Introduction Today, let us understand the difference between String Tokenizer and Split Method. First, let us learn about the String Tokenizer and Split method individually and then know about their differences String...

7 minutes read.

Figurate Number in Java

There have been several uses for figurate or figural numerals throughout history. A number that may be expressed by regular, distinct geometric shapes with spaced evenly points is referred to...

4 minutes read.

Count of Range Sum Problem in Java

In this article, we will discuss the basic approach or native approach used to count range sum problem in java. To solve this problem, we will check for numbers if they...

6 minutes read.

Level order Traversal of a Binary Tree in Java

In Java, a level order traversal of a tree structure is also referred to as the breadth-first traversal of the binary tree. Regarding the subsequent binary tree: Level order traversal is as...

5 minutes read.

Comparetoignorecase in Java

In Java, the function compareToIgnoreCase ( ) is part of the String class, which is part of the java.lang package. It is used to compare any two strings while disregarding...

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

Java Custom Exception

Java Custom Exception Java language facilitates us to create our own exceptions. The class intended to throw the Custom Exception has to be derived from the Java Exceptionor RuntimeExceptionclass. The Java...

4 minutes read.

Java Math toRadians() Method

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

2 minutes read.

Maximum length of string in java

In java, String can act as a data type and a class. The string can be defined as the collection of characters that are enclosed with double quotes(“ “). The...

3 minutes read.

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java Introduction: HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K,...

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