<< Back to JAVA
Java Substring Examples, subSequence
Use the substring and subSequence methods. One or two indexes can be specified.Substring. 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.
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);
System.out.println(cat);
// Take substring of three letters.
// ... Indexes based on value length.
String dog = value.substring(value.length() - 4,
value.length() - 1);
System.out.println(dog);
}
}
Output
cat
dog
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);
System.out.println(sub);
value = "newspaper";
// Take substring starting at index 4.
sub = value.substring(4);
System.out.println(sub);
}
}
Output
site
paper
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);
System.out.println(data);
}
}
Output
gram
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);
System.out.println(letter2);
// Get one char String object.
String letter2String = letters.substring(1, 2);
System.out.println(letter2String);
}
}
Output
b
b
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);
System.out.println(builder);
}
}
Output
abc
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, AfterRight. This method can be implemented also with substring. When we call right(), we get the rightmost several characters from a string.
RightCharAt. 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.
charAtFirst words. Sometimes we want to shorten text to a few words. With a loop (and substring) we can extract the first words of a string into a new string.
First WordsA review. A substring is another String. In Java we acquire substrings with a begin index and an end index. The length is not specified.
In calling this method, 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:
- Java Continue Keyword
- Java Convert Char Array to String
- Java Combine Arrays
- Java Console Examples
- Java Web Services Tutorial
- Java Odd and Even Numbers: Modulo Division
- Java IO
- Java 9 Features
- Java 8 Features
- Java String
- Java Regex | Regular Expression
- Java Filename With Date Example (Format String)
- Java Applet Tutorial
- Java Files.Copy: Copy File
- Java filter Example: findFirst, IntStream
- Java Final and final static Constants
- Java Super: Parent Class
- Java Date and Time
- Java do while loop
- Java Break
- Java Continue
- Java Comments
- Java Splitter Examples: split, splitToList
- Java Math.sqrt Method: java.lang.Math.sqrt
- Java Reflection
- Java Convert String to int
- JDBC Tutorial | What is Java Database Connectivity(JDBC)
- Java main() method
- Java HashMap Examples
- Java HashSet Examples
- Java Arrays.binarySearch
- Java Integer.bitCount and toBinaryString
- Java Overload Method Example
- Java First Words in String
- Java Convert ArrayList to String
- Java Convert boolean to int (Ternary Method)
- Java regionMatches Example and Performance
- Java ArrayDeque Examples
- Java ArrayList add and addAll (Insert Elements)
- Java ArrayList Clear
- Java ArrayList int, Integer Example
- Java ArrayList Examples
- Java Boolean Examples
- Java break Statement
- Java Newline Examples: System.lineSeparator
- Java Stream: Arrays.stream and ArrayList stream
- Java charAt Examples (String For Loop)
- Java Programs | Java Programming Examples
- Java OOPs Concepts
- Java Naming Conventions
- Java Constructor
- Java Class Example
- Java indexOf Examples
- Java Collections.addAll: Add Array to ArrayList
- Java Compound Interest
- Java Int Array
- Java Interface Examples
- Java 2D Array Examples
- Java Remove HTML Tags
- Java Stack Examples: java.util.Stack
- Java Enum Examples
- Java EnumMap Examples
- Java StackOverflowError
- Java startsWith and endsWith Methods
- Java Initialize ArrayList
- Java Object Array Examples: For, Cast and getClass
- Java Objects, Objects.requireNonNull Example
- Java Optional Examples
- Java Static Initializer
- Java static Keyword
- Java Package: Import Keyword Example
- Java Do While Loop Examples
- Java Double Numbers: Double.BYTES and Double.SIZE
- Java Truncate Number: Cast Double to Int
- Java Padding: Pad Left and Right of Strings
- Java Anagram Example: HashMap and ArrayList
- Java Math.abs: Absolute Value
- Java Extends: Class Inheritance
- Java String Class
- Java String Switch Example: Switch Versus HashMap
- Java StringBuffer: append, Performance
- Java Array Examples
- Java Remove Duplicates From ArrayList
- Java if, else if, else Statements
- Java Math.ceil Method
- Java This Keyword
- Java PriorityQueue Example (add, peek and poll)
- Java Process.start EXE: ProcessBuilder Examples
- Java Palindrome Method
- Java parseInt: Convert String to Int
- Java toCharArray: Convert String to Array
- Java Caesar Cipher
- Java Array Length: Get Size of Array
- Java String Array Examples
- Java String compareTo, compareToIgnoreCase
- Java String Concat: Append and Combine Strings
- Java Cast and Convert Types
- Java Math.floor Method, floorDiv and floorMod
- Java Math Class: java.lang.Math
- Java While Loop Examples
- Java Reverse String
- Java Download Web Pages: URL and openStream
- Java Math.pow Method
- Java Math.round Method
- Java Right String Part
- Java MongoDB Example
- Java Substring Examples, subSequence
- Java Prime Number Method
- Java Sum Methods: IntStream and reduce
- Java switch Examples
- Java Convert HashMap to ArrayList
- Java Remove Duplicate Chars
- Java Constructor: Overloaded, Default, This Constructors
- Java String isEmpty Method (Null, Empty Strings)
- Java Regex Examples (Pattern.matches)
- Java ROT13 Method
- Java Random Number Examples
- Java Recursion Example: Count Change
- Java reflect: getDeclaredMethod, invoke
- Java Count Letter Frequencies
- Java ImmutableList Examples
- Java String equals, equalsIgnoreCase and contentEquals
- Java valueOf and copyValueOf String Examples
- Java Vector Examples
- Java Word Count Methods: Split and For Loop
- Java Tutorial | Learn Java Programming
- Java toLowerCase, toUpperCase Examples
- Java Ternary Operator
- Java Tree: HashMap and Strings Example
- Java TreeMap Examples
- Java while loop
- Java Convert String to Byte Array
- Java Join Strings: String.join Method
- Java Modulo Operator Examples
- Java Integer.MAX VALUE, MIN and SIZE
- Java Lambda Expressions
- Java lastIndexOf Examples
- Java Multiple Return Values
- Java String.format Examples: Numbers and Strings
- Java Joiner Examples: join
- Java Keywords
- Java Replace Strings: replaceFirst and replaceAll
- Java return Examples
- Java Multithreading Interview Questions (2021)
- Java Collections Interview Questions (2021)
- Java Shuffle Arrays (Fisher Yates)
- Top 30 Java Design Patterns Interview Questions (2021)
- Java ListMultimap Examples
- Java String Occurrence Method: While Loop Method
- Java StringBuilder capacity
- Java Math.max and Math.min
- Java Factory Design Pattern
- Java StringBuilder Examples
- Java Mail Tutorial
- Java Swing Tutorial
- Java AWT Tutorial
- Java Fibonacci Sequence Examples
- Java StringTokenizer Example
- Java Method Examples: Instance and Static
- Java String Between, Before, After
- Java BitSet Examples
- Java System.gc, Runtime.getRuntime and freeMemory
- Java Character Examples
- Java Char Lookup Table
- Java BufferedWriter Examples: Write Strings to Text File
- Java Abstract Class
- Java Hashtable
- Java Math class with Methods
- Java Whitespace Methods
- Java Data Types
- Java Trim String Examples (Trim Start, End)
- Java Exceptions: try, catch and finally
- Java vs C#
- Java Float Numbers
- Java Truncate String
- Java Variables
- Java For Loop Examples
- Java Uppercase First Letter
- Java Inner Class
- Java Networking
- Java Keywords
- Java If else
- Java Switch
- Loops in Java | Java For Loop
- Java File: BufferedReader and FileReader
- Java Random Lowercase Letter
- Java Calendar Examples: Date and DateFormat
- Java Case Keyword
- Java Char Array
- Java ASCII Table
- Java IntStream.Range Example (Get Range of Numbers)
- Java length Example: Get Character Count
- Java Line Count for File
- Java Sort Examples: Arrays.sort, Comparable
- Java LinkedHashMap Example
- Java Split Examples
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