×

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 Integer toBinaryString() method

The toBinaryString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 2. Syntax public static String toBinaryString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Pernicious Number in Java

If the number of 1s in a number appearing in the binary representation is the prime number, such a number is known as a pernicious number. A pernicious number always corresponds to...

4 minutes read.

MVC in Java

A well-known design pattern is Model-View-Controller. The discipline of web development. We can organize our code in this manner. The document stipulates that a program or application must include a...

4 minutes read.

How to convert float to String in Java

How to convert float to String in java There are following methods to convert float to String: Convert using Float.toString(float) Convert using String.valueOf(float) Convert using Float.toString(float) The Float class has a static method that returns...

2 minutes read.

Java Int Keyword

Among the primitive data types is the Java int keyword. To declare variables, use this. It can also be used with methods that return values of the integer type. It...

3 minutes read.

Java 13 New Features

The Java SE Platform's JDK 13 version is an open-source reference implementation defined by the Java Community's JSR 388 Process. The necessary modifications made in Java 13 are listed below....

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

Iccanobif Numbers in Java

In this article, you will be very well equipped with the knowledge of iccanobif numbers in Java. You will also know how they are formed and basic example programs on...

3 minutes read.

Functional Interface in Java 8

A brief introduction to Interface in Java: Interfaces in Java are basically the blue print of classes. Before the appearance of Java 8, it was only possible to declare one or...

11 minutes read.

How to check the Java version in cmd

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated...

5 minutes read.

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.

How to calculate time complexity of any program in Java

Java : Java's syntax and principles are derived from the C and C++ languages. We know that java is one of the programming language. The main feature of java which is...

3 minutes read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

Why are generics used in Java

Java has a feature called generics that allows you to make a class, interface, and function accepting any (reference) type as a parameter. In other words, it is the idea...

4 minutes read.

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

Java StringWriter Class

The StringWriter class is a character stream in which it is used to store the output consisting of characters into the string buffer. Upon collecting output into a string buffer,...

3 minutes read.

Java Buffered Writer

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

India Map Pattern in Java

India Map Pattern is the pattern we'll code now using Java, as demonstrated. We will use a star in Java to print our India map.The specialty is that we will only...

4 minutes read.

Java instance variable

An instance in object-oriented programming (OOP) is a particular implementation of any object. Each realized version of an item, which might vary in several ways, is an instance. Instantiation is...

3 minutes read.

Java Session

Session indicates interval of time. A session is a simple  time interval in which servers and client interacts. To maintain the state of the client or user we use technologies...

5 minutes read.