In this Java tutorial, you will learn about the java.lang.String class, String constructors, and commonly used String methods with clear examples. The tutorial also explains String immutability, literals, character indexing, comparison, searching, replacing, splitting, formatting, and conversion methods.
Java String class overview
String is a final class in the java.lang package that represents a sequence of characters. In Java, a String object is immutable, which means its value cannot be changed after it is created. Methods such as concat(), replace(), substring(), toLowerCase(), and trim() return a new String instead of modifying the original String.
You can create a String using a string literal or by using a String constructor. In most Java programs, string literals are preferred for normal text values.
String site = "tutorialkart";
String sameText = new String("tutorialkart");
String literals and new String objects in Java
A string literal may be reused from the string pool, while new String("text") explicitly creates a new String object. Use equals() to compare String content. Do not use == when your intention is to compare characters inside the String.
public class StringExample {
public static void main(String[] args) {
String a = "java";
String b = "java";
String c = new String("java");
System.out.println(a == b);
System.out.println(a == c);
System.out.println(a.equals(c));
}
}
true
false
true
Java String constructors list
The String class provides constructors for creating strings from byte arrays, character arrays, Unicode code points, another String, StringBuffer, and StringBuilder. The following list gives quick links to the constructors covered in this tutorial.
| String() | Creates an empty string. |
| String(byte[] bytes) | Decodes bytes using the platform default charset. |
| String(byte[] bytes, Charset charset) | Decodes bytes using the given Charset. |
| String(byte[] bytes, int offset, int length) | Uses part of a byte array. |
| String(byte[] bytes, int offset, int length, Charset charset) | Uses part of a byte array with a Charset. |
| String(byte[] bytes, int offset, int length, String charsetName) | Uses part of a byte array with a charset name. |
| String(byte[] bytes, String charsetName) | Decodes bytes using a charset name. |
| String(char[] value) | Creates a string from a character array. |
| String(char[] value, int offset, int count) | Uses part of a character array. |
| String(int[] codePoints, int offset, int count) | Creates a string from Unicode code points. |
| String(String original) | Creates a new string with the same text. |
| String(StringBuffer buffer) | Creates a string from a StringBuffer. |
| String(StringBuilder builder) | Creates a string from a StringBuilder. |
Java String methods list by purpose
The java.lang.String class contains many methods. Instead of memorising the list, learn them by purpose: access characters, compare text, search inside text, extract substrings, replace text, split text, convert case, format values, and convert other data types to strings.
| Purpose | Important String methods |
|---|---|
| Character access and Unicode | charAt(), codePointAt(), codePointBefore(), codePointCount(), offsetByCodePoints() |
| Comparison | equals(), equalsIgnoreCase(), compareTo(), compareToIgnoreCase(), contentEquals(), regionMatches() |
| Searching | contains(), indexOf(), lastIndexOf(), startsWith(), endsWith() |
| Extracting text | substring(), subSequence(), split(), toCharArray(), getChars() |
| Replacing and regex | replace(), replaceFirst(), replaceAll(), matches() |
| Case, whitespace, and formatting | toLowerCase(), toUpperCase(), trim(), format(), join() |
| Conversion | valueOf(), copyValueOf(), getBytes(), intern(), toString(), hashCode() |
java.lang.String provides these operations through its methods
- Work with individual characters and Unicode code points of a String.
- Compare two strings by value or lexicographic order.
- Search a character or substring in a String.
- Check prefixes, suffixes, and contained text.
- Use regular expressions for matching, replacing, and splitting.
- Convert text to uppercase or lowercase.
- Replace characters, substrings, and regex matches.
- Represent primitive values and objects as Strings.
- Convert between Strings, byte arrays, character arrays, StringBuilder, and StringBuffer.
java.lang.String constructors with examples
String()
The String() constructor creates a new String object initialized to an empty character sequence. In practice, prefer the empty literal "" for an empty string.
Example : An example program to demonstrate String() constructor.
public class StringClassExample {
public static void main(String[] args) {
String str = new String();
System.out.print("Value of str is \""+str+"\"");
}
}
Output to console is :
Value of str is ""
String(byte[] bytes)
The constructor String(byte[] bytes) creates a new string by decoding the given bytes with the platform default charset. For predictable results across systems, prefer constructors or methods that explicitly pass a Charset, such as StandardCharsets.UTF_8.
Example : An example program to demonstrate String(byte[] bytes) constructor.
import java.nio.charset.Charset;
public class StringClassExample {
public static void main(String[] args) {
byte[] bytes = {97,98,99,101,102,105,108,110};
String str = new String(bytes);
System.out.println("Value of str is \""+str+"\"");
System.out.println("Default char set is "+Charset.defaultCharset());
}
}
Output to console is :
Value of str is "abcefiln"
Default char set is UTF-8
String(byte[] bytes, Charset charset)
The constructor String(byte[] bytes, Charset charset) creates a new string by decoding the bytes using the specified charset.
Example : An example program to demonstrate String(byte[] bytes, Charset charset) constructor.
import java.nio.charset.Charset;
public class StringClassExample {
public static void main(String[] args) {
byte[] bytes = {97,98,99,101,102,105,108,110};
String str = new String(bytes, Charset.forName("ISO-8859-1"));
System.out.println("Value of str is \""+str+"\" using ISO-8859-1 charset");
String str1 = new String(bytes, Charset.forName("UTF-8"));
System.out.println("Value of str1 is \""+str1+"\" using UTF-8 charset");
}
}
Output to console is :
Value of str is "abcefiln" using ISO-8859-1 charset
Value of str1 is "abcefiln" using UTF-8 charset
String(byte[] bytes, int offset, int length)
The constructor String(byte[] bytes, int offset, int length) creates a new string from a portion of the byte array. The offset is the starting byte index, and length is the number of bytes to decode.
Example : An example program to demonstrate String(byte[] bytes, int offset, int length) constructor.
public class StringClassExample {
public static void main(String[] args) {
byte[] bytes = {97,98,99,101,102,105,108,110,111,112,113,114}; //"abcefilnopqr"
String str = new String(bytes, 3, 5);
System.out.println("Value of str is \""+str+"\"");
}
}
Output to console is :
Value of str is "efiln"
Here, the bytes represent the text abcefilnopqr. With offset = 3 and length = 5, Java uses five bytes starting from index 3, so the result is efiln.
String(byte[] bytes, int offset, int length, Charset charset)
The constructor String(byte[] bytes, int offset, int length, Charset charset) creates a new string from part of a byte array and decodes that part using the specified Charset.
Example : An example program to demonstrate String(byte[] bytes, int offset, int length, Charset charset) constructor.
import java.nio.charset.Charset;
public class StringClassExample {
public static void main(String[] args) {
byte[] bytes = {97,98,99,101,102,105,108,110,111,112,113,114}; //"abcefilnopqr"
String str = new String(bytes, 3, 5, Charset.forName("ISO-8859-1"));
System.out.println("Value of str is \""+str+"\"");
}
}
Output to console is :
Value of str is "efiln"
String(byte[] bytes, int offset, int length, String charsetName)
The constructor String(byte[] bytes, int offset, int length, String charsetName) creates a new string from part of a byte array using the charset identified by charsetName. If the charset name is invalid or unsupported, an UnsupportedEncodingException can be thrown.
Example : An example program to demonstrate String(byte[] bytes, int offset, int length, String charsetName) constructor.
import java.io.UnsupportedEncodingException;
public class StringClassExample {
public static void main(String[] args) {
byte[] bytes = {97,98,99,101,102,105,108,110,111,112,113,114}; //"abcefilnopqr"
try {
String str = new String(bytes, 3, 5, "ISO-8859-1");
System.out.println("Value of str is \""+str+"\"");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
Output to console is :
Value of str is "efiln"
String(byte[] bytes, String charsetName)
The constructor String(byte[] bytes, String charsetName) creates a new string by decoding all bytes using the named charset.
Example : An example program to demonstrate String(byte[] bytes, String charsetName) constructor.
import java.io.UnsupportedEncodingException;
public class StringClassExample {
public static void main(String[] args) {
byte[] bytes = {97,98,99,101,102,105,108,110};
try {
String str = new String(bytes, "ISO-8859-1");
System.out.println("Value of str is \""+str+"\" using ISO-8859-1 charset");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
Output to console is :
Value of str is "abcefiln" using ISO-8859-1 charset
String(char[] chars)
The constructor String(char[] chars) creates a new string from the characters in the given character array.
Example : An example program to demonstrate String(char[] chars) constructor.
public class StringClassExample {
public static void main(String[] args) {
char[] chars = {'t','u','t','o','r','i','a','l','k','a','r','t'};
String str = new String(chars);
System.out.println("Value of str is \""+str+"\"");
}
}
Output to console is :
Value of str is "tutorialkart"
String(char[] chars, int offset, int count)
The constructor String(char[] chars, int offset, int count) creates a new string from a portion of a character array. The offset is the starting character index, and count is the number of characters to copy.
Example : An example program to demonstrate String(char[] chars) constructor.
public class StringClassExample {
public static void main(String[] args) {
char[] chars = {'t','u','t','o','r','i','a','l','k','a','r','t'};
String str = new String(chars);
System.out.println("Value of str is \""+str+"\"");
}
}
Output to console is :
Value of str is "tutorialkart"
For a partial character array example, new String(chars, 3, 4) would create the string oria from the characters at indexes 3, 4, 5, and 6.
String(int[] codePoints, int offset, int count)
The constructor String(int[] codePoints, int offset, int count) creates a new string from Unicode code points. It is useful when the text is represented as integer code point values instead of Java char values.
Example : An example program to demonstrate String(int[] codePoints, int offset, int count) constructor.
public class StringClassExample {
public static void main(String[] args) {
int[] codePoints = {116,117,116,111,114,105,97,108,107,97,114,116};
String str = new String(codePoints, 3, 5);
System.out.println("Value of str is \""+str+"\"");
}
}
Output to console is :
Value of str is "orial"
String(String original)
The constructor String(String original) creates a new String object with the same character sequence as the original string. For normal use, assigning the original String reference is usually enough because String objects are immutable.
Example : An example program to demonstrate String(String original) constructor.
public class StringClassExample {
public static void main(String[] args) {
String original = "tutorialkart";
String str = new String(original);
System.out.println("Value of str is \""+str+"\"");
}
}
Output to console is :
Value of str is "tutorialkart"
String(StringBuffer buffer)
The constructor String(StringBuffer buffer) creates a new string from the sequence of characters present in the given StringBuffer.
Example : An example program to demonstrate String(StringBuffer buffer) constructor.
public class StringClassExample {
public static void main(String[] args) {
StringBuffer buffer = new StringBuffer("tutorialkart");
String str = new String(buffer);
System.out.println("Value of str is \""+str+"\"");
}
}
Output to console is :
Value of str is "tutorialkart"
String(StringBuilder buffer)
The constructor String(StringBuilder buffer) creates a new string from the sequence of characters present in the given StringBuilder.
Example : An example program to demonstrate String(StringBuilder buffer) constructor.
public class StringClassExample {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("tutorialkart");
String str = new String(builder);
System.out.println("Value of str is \""+str+"\"");
}
}
Output to console is :
Value of str is "tutorialkart"
java.lang.String methods with examples
char charAt(int index)
The method charAt(int index) returns the character value at the specified zero-based index.
public class StringClassExample {
public static void main(String[] args) {
String str = "tutorialkart";
char ch1 = str.charAt(5);
System.out.println("Character at index 5 is "+ch1);
char ch2 = str.charAt(8);
System.out.println("Character at index 8 is "+ch2);
}
}
Output to console is :
Character at index 5 is i
Character at index 8 is k
int codePointAt(int index)
The method codePointAt(int index) returns the Unicode code point at the specified index.
public class StringClassExample {
public static void main(String[] args) {
String str = "tutorialkart";
int codePoint1 = str.codePointAt(5);
System.out.println("codePoint at index 5 is "+codePoint1);
int codePoint2 = str.codePointAt(8);
System.out.println("codePoint at index 8 is "+codePoint2);
}
}
Output to console is :
codePoint at index 5 is 105
codePoint at index 8 is 107
int codePointBefore(int index)
The method codePointBefore(int index) returns the Unicode code point before the specified index.
public class StringClassExample {
public static void main(String[] args) {
String str = "tutorialkart";
int codePoint1 = str.codePointAt(5);
System.out.println("codePoint at index 5 is "+codePoint1);
int codePoint2 = str.codePointBefore(6);
System.out.println("codePoint at index before 6 is "+codePoint2);
}
}
Output to console is :
codePoint at index 5 is 105
codePoint at index before 6 is 105
int codePointCount(int beginIndex, int endIndex)
The method codePointCount(int beginIndex, int endIndex) returns the number of Unicode code points in the given text range. The endIndex is exclusive.
public class StringClassExample {
public static void main(String[] args) {
String str = "tutorialkart";
int count = str.codePointCount(2,5);
System.out.println("number of code points from 2 to 5 is "+count);
}
}
Output to console is :
number of code points from 2 to 5 is 3
int compareTo(String anotherString)
The method compareTo(String anotherString) compares two strings lexicographically. It returns 0 when both strings are equal, a negative value when the current string comes before the argument, and a positive value when it comes after the argument.
public class StringClassExample {
public static void main(String[] args) {
compare("tutorialkart","tutorialkart");
compare("tutorialkart","autorialkart");
compare("autorialkart","tutorialkart");
}
public static void compare(String str, String anotherStr){
int difference = str.compareTo(anotherStr);
if(difference < 0){ System.out.println("The string, \""+str+"\" should occur prior to the string, \""+anotherStr+"\" provided in the arguements."); } else if(difference >0){
System.out.println("The string, \""+str+"\" should occur later to the string, \""+anotherStr+"\" provided in the arguements.");
} else {
System.out.println("The two strings, \""+str+"\" and \""+anotherStr+"\" are equal.");
}
}
}
Output to console is :
The two strings, "tutorialkart" and "tutorialkart" are equal.
The string, "tutorialkart" should occur later to the string, "autorialkart" provided in the arguements.
The string, "autorialkart" should occur prior to the string, "tutorialkart" provided in the arguements.
int compareToIgnoreCase(String anotherString)
The method compareToIgnoreCase(String anotherString) compares strings lexicographically while ignoring case differences.
public class StringClassExample {
public static void main(String[] args) {
compare("Tutorialkart","tutorialkart");
compare("tutorialkart","AutoRialkart");
compare("AutorialkaRt","tutoriAlkart");
}
public static void compare(String str, String anotherStr){
int difference = str.compareToIgnoreCase(anotherStr);
if(difference < 0){ System.out.println("The string, \""+str+"\" should occur prior to the string, \""+anotherStr+"\" provided in the arguements."); } else if(difference >0){
System.out.println("The string, \""+str+"\" should occur later to the string, \""+anotherStr+"\" provided in the arguements.");
} else {
System.out.println("The two strings, \""+str+"\" and \""+anotherStr+"\" are equal.");
}
}
}
Output to console is :
The two strings, "Tutorialkart" and "tutorialkart" are equal.
The string, "tutorialkart" should occur later to the string, "AutoRialkart" provided in the arguements.
The string, "AutorialkaRt" should occur prior to the string, "tutoriAlkart" provided in the arguements.
String concat(String str)
The method concat(String str) appends the specified string to the end of this string and returns the resulting string.
public class StringClassExample {
public static void main(String[] args) {
String thisStr = "tutorialkart";
String str = ".com is the best website to understand java programming language.";
String resultStr = thisStr.concat(str);
System.out.println(resultStr);
}
}
Output to console is :
tutorialkart.com is the best website to understand java programming language.
boolean contains(CharSequence s)
The method contains(CharSequence s) returns true if this string contains the specified sequence of characters.
public class StringClassExample {
public static void main(String[] args) {
CharSequence chSeq = "kart";
String str = "tutorialkart";
boolean isPresent = str.contains(chSeq);
if(isPresent){
System.out.println("CharSequence \""+chSeq+"\" is present in the str, \""+str+"\"");
} else {
System.out.println("CharSequence \""+chSeq+"\" is not present in the str, \""+str+"\"");
}
}
}
Output to console is :
CharSequence "kart" is present in the str, "tutorialkart"
boolean contentEquals(CharSequence cs)
The method contentEquals(CharSequence cs) compares this string with the specified CharSequence and returns true when both contain the same characters.
public class StringClassExample {
public static void main(String[] args) {
CharSequence chSeq = "tutorialkart";
String str = "tutorialkart";
boolean isPresent = str.contentEquals(chSeq);
if(isPresent){
System.out.println("CharSequence \""+chSeq+"\" equals the string str, \""+str+"\"");
} else {
System.out.println("CharSequence \""+chSeq+"\" is not equal to the string str, \""+str+"\"");
}
}
}
Output to console is :
CharSequence "tutorialkart" equals the string str, "tutorialkart"
boolean contentEquals(StringBuffer sb)
The method contentEquals(StringBuffer sb) compares this string with the content of the specified StringBuffer.
public class StringClassExample {
public static void main(String[] args) {
StringBuffer buffer = new StringBuffer("tutorialkart");
String str = "tutorialkart";
boolean isPresent = str.contentEquals(buffer);
if(isPresent){
System.out.println("CharSequence \""+buffer+"\" equals the string str, \""+str+"\"");
} else {
System.out.println("CharSequence \""+buffer+"\" is not equal to the string str, \""+str+"\"");
}
}
}
Output to console is :
CharSequence "tutorialkart" equals the string str, "tutorialkart"
static String copyValueOf(char[] data)
The method copyValueOf(char[] data) creates a String from the given character array. It is equivalent to creating a new String from that character array.
public class StringClassExample {
public static void main(String[] args) {
char[] chArr = {'t','u','t','o','r','i','a','l','k','a','r','t'};
String str = String.copyValueOf(chArr);
System.out.println("Value of str is \""+str+"\"");
}
}
Output to console is :
Value of str is "tutorialkart"
static String copyValueOf(char[] data, int offset, int count)
The method copyValueOf(char[] data, int offset, int count) creates a string from count characters of the array starting at offset.
public class StringClassExample {
public static void main(String[] args) {
char[] chArr = {'t','u','t','o','r','i','a','l','k','a','r','t'};
String str = String.copyValueOf(chArr,6,5);
System.out.println("Value of str is \""+str+"\"");
}
}
Output to console is :
Value of str is "alkar"
boolean endsWith(String suffix)
The method endsWith(String suffix) returns true when this string ends with the specified suffix.
public class StringClassExample {
public static void main(String[] args) {
String str = "tutorialkart";
String suffix = "kart";
boolean isEnding = str.endsWith(suffix);
if(isEnding){
System.out.println("Suffix \""+suffix+"\" is present at the end of string str, \""+str+"\"");
} else {
System.out.println("Suffix \""+suffix+"\" is not present at the end of string str, \""+str+"\"");
}
}
}
Output to console is :
Suffix "kart" is present at the end of string str, "tutorialkart"
boolean equals(Object anObject)
The method equals(Object anObject) compares this string with another object. It returns true only when the other object is also a String with the same character sequence.
public class StringClassExample {
public static void main(String[] args) {
String str = "tutorialkart";
Object otherStr = "kart";
boolean isEqual = str.equals(otherStr);
if(isEqual){
System.out.println("Two string, \""+otherStr+"\" and \""+str+"\" are equal.");
} else {
System.out.println("Two string, \""+otherStr+"\" and \""+str+"\" are not equal.");
}
}
}
Output to console is :
Two string, "kart" and "tutorialkart" are not equal.
boolean equalsIgnoreCase(String anotherString)
The method equalsIgnoreCase(String anotherString) compares two strings while ignoring uppercase and lowercase differences.
public class StringClassExample {
public static void main(String[] args) {
String str = "tutorialkart";
String otherStr = "TUTORIALKART";
boolean isEqual = str.equalsIgnoreCase(otherStr);
if(isEqual){
System.out.println("Two strings, \""+otherStr+"\" and \""+str+"\" are equal.");
} else {
System.out.println("Two strings, \""+otherStr+"\" and \""+str+"\" are not equal.");
}
}
}
Output to console is :
Two string, "TUTORIALKART" and "tutorialkart" are equal.
static String format(Locale l, String format, Object… args)
The method String.format(Locale l, String format, Object... args) returns a formatted string using the specified locale, format string, and arguments.
import java.util.Locale;
public class StringClassExample {
public static void main(String[] args) {
String str = String.format(Locale.ENGLISH,"%s %d days %s", "There are",365,"in an year.");
System.out.println(str);
}
}
Output to console is :
There are 365 days in an year.
static String format(String format, Object… args)
The method String.format(String format, Object... args) returns a formatted string using the default locale.
public class StringClassExample {
public static void main(String[] args) {
String str = String.format("%s %d days %s", "There are",365,"in an year.");
System.out.println(str);
}
}
Output to console is :
There are 365 days in an year.
byte[] getBytes()
The method getBytes() encodes this String into bytes using the platform default charset.
public class StringClassExample {
public static void main(String[] args) {
String str = "tutorialkart";
byte[] bytes = str.getBytes();
System.out.print("The bytes are : ");
for(byte b:bytes) System.out.print(b+",");
}
}
Output to console is :
The bytes are : 116,117,116,111,114,105,97,108,107,97,114,116,
byte[] getBytes(Charset charset)
The method getBytes(Charset charset) encodes this String into bytes using the specified charset.
import java.nio.charset.Charset;
public class StringClassExample {
public static void main(String[] args) {
String str = "tutorialkart";
byte[] bytes = str.getBytes(Charset.forName("UTF-8"));
System.out.print("The bytes are : ");
for(byte b:bytes) System.out.print(b+",");
}
}
Output to console is :
The bytes are : 116,117,116,111,114,105,97,108,107,97,114,116,
byte[] getBytes(String charsetName)
The method getBytes(String charsetName) encodes this String into bytes using the named charset.
import java.io.UnsupportedEncodingException;
public class StringClassExample {
public static void main(String[] args) {
String str = "tutorialkart";
byte[] bytes = null;
try {
bytes = str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("The bytes are : ");
for(byte b:bytes) System.out.print(b+",");
}
}
Output to console is :
The bytes are : 116,117,116,111,114,105,97,108,107,97,114,116,
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
The method getChars() copies characters from this string into a destination character array. The source end index is exclusive.
public class StringExample {
public static void main(String[] args) {
String text = "tutorialkart";
char[] result = new char[5];
text.getChars(0, 5, result, 0);
System.out.println(result);
}
}
tutor
int hashCode()
The method hashCode() returns the hash code of the String. Equal strings always return the same hash code.
String a = "java";
String b = "java";
System.out.println(a.hashCode() == b.hashCode());
true
int indexOf(int ch)
The method indexOf(int ch) returns the index of the first occurrence of the specified character. It returns -1 when the character is not found.
String text = "banana";
System.out.println(text.indexOf('a'));
1
int indexOf(int ch, int fromIndex)
The method indexOf(int ch, int fromIndex) searches for the character starting from the specified index.
String text = "banana";
System.out.println(text.indexOf('a', 2));
3
int indexOf(String str)
The method indexOf(String str) returns the index of the first occurrence of the specified substring.
String text = "java programming";
System.out.println(text.indexOf("program"));
5
int indexOf(String str, int fromIndex)
The method indexOf(String str, int fromIndex) searches for the substring starting from the given index.
String text = "one two one";
System.out.println(text.indexOf("one", 1));
8
String intern()
The method intern() returns a canonical representation of the string from the string pool. It is mainly useful when you specifically need pooled String references.
String a = new String("java");
String b = "java";
System.out.println(a.intern() == b);
true
boolean isEmpty()
The method isEmpty() returns true when the length of the string is zero.
System.out.println("".isEmpty());
System.out.println(" ".isEmpty());
true
false
static String join(CharSequence delimiter, CharSequence… elements)
The method String.join() joins multiple character sequences using the specified delimiter.
String result = String.join("-", "java", "string", "methods");
System.out.println(result);
java-string-methods
static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
This overload of String.join() joins an iterable collection of character sequences.
import java.util.Arrays;
String result = String.join(", ", Arrays.asList("red", "green", "blue"));
System.out.println(result);
red, green, blue
int lastIndexOf(int ch)
The method lastIndexOf(int ch) returns the index of the last occurrence of the specified character.
String text = "banana";
System.out.println(text.lastIndexOf('a'));
5
int lastIndexOf(int ch, int fromIndex)
The method lastIndexOf(int ch, int fromIndex) searches backward from the given index.
String text = "banana";
System.out.println(text.lastIndexOf('a', 4));
3
int lastIndexOf(String str)
The method lastIndexOf(String str) returns the index of the last occurrence of the specified substring.
String text = "one two one";
System.out.println(text.lastIndexOf("one"));
8
int lastIndexOf(String str, int fromIndex)
The method lastIndexOf(String str, int fromIndex) searches backward for the specified substring starting at the given index.
String text = "one two one";
System.out.println(text.lastIndexOf("one", 5));
0
int length()
The method length() returns the number of char values in the string.
String text = "tutorialkart";
System.out.println(text.length());
12
boolean matches(String regex)
The method matches(String regex) checks whether the whole string matches the given regular expression.
String email = "user@example.com";
System.out.println(email.matches(".+@.+\\..+"));
true
int offsetByCodePoints(int index, int codePointOffset)
The method offsetByCodePoints() returns an index offset by the specified number of Unicode code points.
String text = "tutorial";
int index = text.offsetByCodePoints(0, 3);
System.out.println(index);
3
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
The method regionMatches() compares a region of this string with a region of another string. This overload can ignore case.
String a = "JavaString";
String b = "string";
System.out.println(a.regionMatches(true, 4, b, 0, 6));
true
boolean regionMatches(int toffset, String other, int ooffset, int len)
This overload of regionMatches() compares regions with case sensitivity.
String a = "JavaString";
String b = "String";
System.out.println(a.regionMatches(4, b, 0, 6));
true
String replace(char oldChar, char newChar)
The method replace(char oldChar, char newChar) replaces all occurrences of one character with another character.
String text = "banana";
System.out.println(text.replace('a', 'o'));
bonono
String replace(CharSequence target, CharSequence replacement)
The method replace(CharSequence target, CharSequence replacement) replaces each literal target sequence with the replacement sequence.
String text = "Java is simple. Java is popular.";
System.out.println(text.replace("Java", "Python"));
Python is simple. Python is popular.
String replaceAll(String regex, String replacement)
The method replaceAll(String regex, String replacement) replaces every substring that matches the given regular expression.
String text = "A1 B22 C333";
System.out.println(text.replaceAll("\\d+", "#"));
A# B# C#
String replaceFirst(String regex, String replacement)
The method replaceFirst(String regex, String replacement) replaces only the first substring that matches the given regular expression.
String text = "A1 B22 C333";
System.out.println(text.replaceFirst("\\d+", "#"));
A# B22 C333
String[] split(String regex)
The method split(String regex) splits this string around matches of the given regular expression.
String csv = "red,green,blue";
String[] colors = csv.split(",");
for (String color : colors) {
System.out.println(color);
}
red
green
blue
String[] split(String regex, int limit)
The method split(String regex, int limit) controls the maximum number of resulting parts based on the limit argument.
String text = "a,b,c";
String[] parts = text.split(",", 2);
for (String part : parts) {
System.out.println(part);
}
a
b,c
boolean startsWith(String prefix)
The method startsWith(String prefix) returns true when this string begins with the specified prefix.
String text = "tutorialkart";
System.out.println(text.startsWith("tutorial"));
true
boolean startsWith(String prefix, int toffset)
The method startsWith(String prefix, int toffset) checks whether the string starts with the prefix at the specified offset.
String text = "tutorialkart";
System.out.println(text.startsWith("kart", 8));
true
CharSequence subSequence(int beginIndex, int endIndex)
The method subSequence() returns a character sequence from beginIndex to endIndex - 1.
String text = "tutorialkart";
CharSequence sequence = text.subSequence(0, 8);
System.out.println(sequence);
tutorial
String substring(int beginIndex)
The method substring(int beginIndex) returns the part of the string from the specified index to the end.
String text = "tutorialkart";
System.out.println(text.substring(8));
kart
String substring(int beginIndex, int endIndex)
The method substring(int beginIndex, int endIndex) returns the part of the string from beginIndex to endIndex - 1.
String text = "tutorialkart";
System.out.println(text.substring(0, 8));
tutorial
char[] toCharArray()
The method toCharArray() converts the string into a new character array.
String text = "java";
char[] chars = text.toCharArray();
System.out.println(chars[0]);
j
String toLowerCase()
The method toLowerCase() converts the string to lowercase using the default locale.
System.out.println("JAVA".toLowerCase());
java
String toLowerCase(Locale locale)
The method toLowerCase(Locale locale) converts the string to lowercase using the rules of the specified locale.
import java.util.Locale;
System.out.println("JAVA".toLowerCase(Locale.ENGLISH));
java
String toString()
For a String object, toString() returns the same String object.
String text = "java";
System.out.println(text.toString());
java
String toUpperCase()
The method toUpperCase() converts the string to uppercase using the default locale.
System.out.println("java".toUpperCase());
JAVA
String toUpperCase(Locale locale)
The method toUpperCase(Locale locale) converts the string to uppercase using the specified locale.
import java.util.Locale;
System.out.println("java".toUpperCase(Locale.ENGLISH));
JAVA
String trim()
The method trim() removes leading and trailing characters whose code is less than or equal to the space character. It does not remove every kind of Unicode whitespace.
String text = " java ";
System.out.println("[" + text.trim() + "]");
[java]
static String valueOf(boolean b)
The method String.valueOf(boolean b) converts a boolean value into a string.
System.out.println(String.valueOf(true));
true
static String valueOf(char c)
The method String.valueOf(char c) converts a character into a string.
System.out.println(String.valueOf('J'));
J
static String valueOf(char[] data)
The method String.valueOf(char[] data) converts a character array into a string.
char[] chars = {'j', 'a', 'v', 'a'};
System.out.println(String.valueOf(chars));
java
static String valueOf(char[] data, int offset, int count)
The method String.valueOf(char[] data, int offset, int count) converts part of a character array into a string.
char[] chars = {'j', 'a', 'v', 'a'};
System.out.println(String.valueOf(chars, 1, 2));
av
static String valueOf(double d)
The method String.valueOf(double d) converts a double value into a string.
System.out.println(String.valueOf(12.5d));
12.5
static String valueOf(float f)
The method String.valueOf(float f) converts a float value into a string.
System.out.println(String.valueOf(12.5f));
12.5
static String valueOf(int i)
The method String.valueOf(int i) converts an integer value into a string.
System.out.println(String.valueOf(100));
100
static String valueOf(long l)
The method String.valueOf(long l) converts a long value into a string.
System.out.println(String.valueOf(10000000000L));
10000000000
static String valueOf(Object obj)
The method String.valueOf(Object obj) returns obj.toString() when the object is not null. If the object is null, it returns the string "null".
Object value = null;
System.out.println(String.valueOf(value));
null
StringBuilder, StringBuffer, and String in Java
Use String when text is not changed repeatedly. Use StringBuilder when you need to build or modify text many times in a single thread. Use StringBuffer when you need similar mutable text operations with synchronized methods.
StringBuilder builder = new StringBuilder();
builder.append("Java");
builder.append(" String");
builder.append(" class");
String result = builder.toString();
System.out.println(result);
Java String class
Common mistakes with Java String methods
- Using
==to compare String content instead ofequals(). - Expecting methods such as
replace()ortrim()to modify the original String. - Forgetting that String indexes start from
0. - Passing the wrong end index to
substring(); the end index is exclusive. - Using
getBytes()without a charset when output must be consistent across environments. - Using
replaceAll()for literal text replacement whenreplace()is enough.replaceAll()treats the first argument as a regular expression.
Java String constructors and methods FAQ
What is the String class in Java?
The String class in Java is java.lang.String. It represents a sequence of characters and is immutable, so String methods return new String values instead of changing the existing object.
Which String constructor is commonly used in Java?
In everyday code, developers usually use string literals such as String name = "Java";. Constructors are mainly used when creating strings from byte arrays, character arrays, code points, StringBuilder, or StringBuffer.
What is the difference between equals() and == for strings?
equals() compares the text inside two strings. == compares object references. For String content comparison, use equals() or equalsIgnoreCase().
Why does a String method not change my original string?
String objects are immutable. Methods such as replace(), concat(), substring(), and toUpperCase() return a new String. Assign the result to a variable if you want to use the changed value.
When should I use StringBuilder instead of String?
Use StringBuilder when you need to append, insert, or modify text repeatedly, especially inside loops. Convert it back to a String using toString() when the final text is ready.
Editorial QA checklist for this Java String tutorial
- Confirm every constructor name and method signature uses
java.lang.String, notjava.util.String. - Check that examples using byte arrays mention charset behavior clearly.
- Verify output blocks are marked as output and not as Java syntax.
- Check that String comparison examples explain
equals()and==separately. - Confirm regex methods such as
matches(),replaceAll(),replaceFirst(), andsplit()are described as regex-based methods.
Conclusion
The java.lang.String class is used throughout Java programs for storing and processing text. Learn the constructors when you need to create strings from arrays, buffers, builders, bytes, or Unicode code points. For day-to-day programming, focus first on the most used String methods: length(), charAt(), equals(), contains(), indexOf(), substring(), replace(), split(), trim(), toLowerCase(), toUpperCase(), and valueOf().
TutorialKart.com