Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Java Substring Examples, subSequence

These Java examples use the substring and subSequence methods. With substring, one or two indexes can be specified.

Substrings. Strings are immutable.

We cannot delete characters from them to get a substring. Instead we must copy a range of characters (from a begin index to an end).

With substring, we pass one or two indexes. We must specify a begin index, which is where the substring copying starts. The end index, optional, is where the substring ends.

An example. We begin. The first substring call takes the first three letters (from index 0 to index 3). The character at index 3, "s," is not included.

Then: We assign a new String reference (cat) to the result of substring. This is a separate String.

Finally: We take a second substring. We use indexes that are based on the String length. We reduce it by an offset.

Based on:

Java 7

Java program that uses substring

public class Program {
    public static void main(String[] args) {

	String value = "cats and dogs";

	// Take substring of first three letters.
	String cat = value.substring(0, 3);

	// Take substring of three letters.
	// ... Indexes based on value length.
	String dog = value.substring(value.length() - 4,
		value.length() - 1);



Begin index. When we use just one argument, this is the begin index. The end index is automatically equal to the last index. This allows for simpler syntax.

Java program that uses substring, begin index

public class Program {
    public static void main(String[] args) {

	String value = "website";

	// Take substring starting at index 3.
	String sub = value.substring(3);

	value = "newspaper";

	// Take substring starting at index 4.
	sub = value.substring(4);



SubSequence. This method does the same thing as substring, but returns instead a reference to a CharSequence. Unless you need a CharSequence, this method is probably not needed.

Java program that uses subSequence

public class Program {
    public static void main(String[] args) {

	String value = "programmer";

	// Get sequence excluding first and last three chars.
	CharSequence data = value.subSequence(3, value.length() - 3);



SubSequence, use. The Java documentation tells us why subSequence exists on the String class. It is required for String to implement the CharSequence interface. It has no other purpose.

Java documentation:

This method is defined so that the String class
can implement the CharSequence interface.

One char, charAt. Often we need to get a single character from a String. Substring can do this, but charAt is a clearer option. It returns a char, not a String object, so is likely faster.

Note: It may be better to use substring for a one-char string if other parts of a program require a String.

Java program that uses charAt, substring

public class Program {
    public static void main(String[] args) {

	String letters = "abc";

	// Get one char from the String.
	char letter2 = letters.charAt(1);

	// Get one char String object.
	String letter2String = letters.substring(1, 2);



StringBuilder, append substring. We often need to append substrings to a StringBuilder. But the substring call is not needed here. We can append a CharSequence directly from the string.

So: Usually we can avoid substring() before calling append() on the StringBuilder.

Java program that uses StringBuilder, CharSequence

import java.lang.StringBuilder;

public class Program {
    public static void main(String[] args) {

	StringBuilder builder = new StringBuilder();
	String value = "abcdef";

	// Append first 3 chars from String to StringBuilder.
	// ... No substring is needed.
	// ... String is a CharSequence.
	builder.append(value, 0, 3);



StringBuilder. This class also has a substring method, one provided by the AbstractStringBuilder class. It uses the same arguments as the String substring method.

StringBuilder: substring

RegionMatches. For performance, substring() often should be avoided. Consider using regionMatches before taking substrings—we can check equivalence of parts this way.

String: regionMatches

Between substrings. We can combine the indexOf method with substring() to locate relative substrings. We find ones between, before and after other parts.

Between, Before, After

CharAt. This is worth considering for one-char strings. We can think of Strings as collections of characters, like arrays. Testing elements, rather than copying arrays, is faster.

A review. A substring is another String. In Java we acquire substrings with a begin index and an end index. The length is not specified.

With substring, we create a new string. Often a separate string is needed in programs. But in other cases, we can just use the original string and store indexes to access a range.

Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf