In this Java tutorial, you will learn about String class in Java. We will go through the constructors, and methods of String class, with examples for each of them.
String Constructors and Methods
String is a sequence of characters. java.lang.String class provides many constructors and methods to do string operations in Java. In this Java Tutorial, we shall see the usage of all the constructors and methods of java.lang.String with example programs.
String Constructors
java.lang.String Methods
java.util.String provides following functionalities through its methods :
- Work with individual characters of a String
- Compare two strings
- Pattern Maching
- Search a character or sub-string in a String
- Uppercase and Lowercase conversions
- Sub-String replacements
- Representation of primitive data types as Strings
java.lang.String Constructors :
String()
String() constructor creates a new String object which is initialized to an empty character sequence.
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)
Java has a computing platform to run and develop java applications. There are many character sets available to choose from based on the application you are interested in. The constructor String(byte[] bytes) creates a new string and initializes it to a sequence of characters based on the interpretation of bytes with the default character set of Java.
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 and initializes the string with the bytes decoded using the charset speicified.
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 and initialize the string with sequence of characters starting from a position in bytes array specified by “offset”, and considering the “length” number of bytes from the offset.
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"
The bytes when decoded using UTF-8 Charset which is default to the Java Virtual Machine,
bytes = abcefilnopqr
and the offset is given by the integers in bold : 0-a-1-b-2-c-3-e-4-f-5-i-6-l-7-n-8-o-9-p-10-q-11-r-12
Offset = 3 and Lenght = 5 : 3-e-4-f-5-i-6-l-7-n-8 : five bytes starting from offset three 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 and initialize the string with sequence of characters starting from a position in bytes array specified by “offset”, and considering the “length” number of bytes from the offset. The bytes are decoded 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"
The bytes when decoded using ISO-8859-1 Charset which is specified in the constructor,
bytes = abcefilnopqr
and the offset is given by the integers in bold : 0-a-1-b-2-c-3-e-4-f-5-i-6-l-7-n-8-o-9-p-10-q-11-r-12
Offset = 3 and Lenght = 5 : 3-e-4-f-5-i-6-l-7-n-8 : five bytes starting from offset three 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 and initializes the string with sequence of characters starting from a position in bytes array specified by “offset”, and considering the “length” number of bytes from the offset. The bytes are decoded using the specified charsetName.
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"
The bytes when decoded using ISO-8859-1 Charset which is specified in the constructor,
bytes = abcefilnopqr
and the offset is given by the integers in bold : 0-a-1-b-2-c-3-e-4-f-5-i-6-l-7-n-8-o-9-p-10-q-11-r-12
Offset = 3 and Lenght = 5 : 3-e-4-f-5-i-6-l-7-n-8 : five bytes starting from offset three is “efiln“
String(byte[] bytes, String charsetName)
The constructor String(byte[] bytes, String charsetName) creates a new string and initializes the string with the bytes decoded using the charsetName speicified.
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 and initializes the string with the characters from chars 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 and initializes the string with sequence of characters starting from a position in chars array specified by “offset”, and considering the “length” number of characters from the offset.
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"
chars = tutorialkart
and the offset is given by the integers in bold : 0-t-1-u-2-t-3-o-4-r-5-i-6-a-7-l-8-k-9-a-10-r-11-t-12
Offset = 3 and Length = 4 : 3-o-4-r-5-i-6-a-7 : four characters of chars array starting from offset three is “oria“
String(int[] codePoints, int offset, int count)
The constructor String(int[] codePoints, int offset, int count) creates a new string and initializes the string with sequence of Unicode code points starting from a position in codePoints integer array specified by “offset”, and considering the “length” number of Unicode code points from the offset.
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"
Unicode code points of integer array codePoints = tutorialkart
and the offset is given by the integers in bold : 0-t-1-u-2-t-3-o-4-r-5-i-6-a-7-l-8-k-9-a-10-r-11-t-12
Offset = 3 and Length = 5 : 3-o-4-r-5-i-6-a-7-l-8 : five code points of codePoints integer array starting from offset three is “orial“
String(String original)
The constructor String(String original) creates a new string and initializes the string with the value of original string received in the arguments.
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 and initializes the string with the sequence of characters present in buffer.
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 and initializes the string with the sequence of characters present in buffer.
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 :
char charAt(int index)
The method java.lang.String.charAt(int index) returns the character value at the index specified in the arguments.
Example : An example program to demonstrate charAt(int index) method.
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 java.lang.String.codePointAt(int index) returns the Unicode code point at the index specified in the arguements.
Example : An example program to demonstrate codePointAt(int index) method.
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 java.lang.String.codePointBefore(int index) returns the Unicode code point character just before the index specified in the arguements.
Example : An example program to demonstrate codePointBefore(int index) method.
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 java.lang.String.codePointCount(int beginIndex, int endIndex) returns the number of Unicode code points in the specified text range of this String.
Example : An example program to demonstrate codePointCount(int beginIndex, int endIndex) method.
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 java.lang.String.compareTo(String anotherString) compares two strings lexicographically (the order in which words are arranged in a dictionary).
Returns a positive value if the string should occur later to the string provided in the arguements.
Returns a negative value if the string should occur prior to the string provided in the arguements.
Example : An example program to demonstrate compareTo(String anotherString) method.
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 java.lang.String.compareToIgnoreCase(String anotherString) compares two strings lexicographically (the order in which words are arranged in a dictionary) without considering if characters’ case.
Returns a negative value if the string should occur later to the string provided in the arguements
Returns a negative value if the string should occur prior to the string provided in the arguements
Example : An example program to demonstrate compareToIgnoreCase(String anotherString) method.
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 java.lang.String.concat(String str) concatenates the string specified in the arguements to the end of this string.
Example : An example program to demonstrate concat(String str) method.
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 java.lang.String.contains(CharSequence s) returns true if and only if this string contains the sequence of char values specified in the arguements.
Example : An example program to demonstrate contains(CharSequence s) method.
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 java.lang.String.contentEquals(CharSequence cs) compares this string to the specified CharSequence and returns true if both the String and CharSequence are equal, else it returns false.
Example : An example program to demonstrate contentEquals(CharSequence cs) method.
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 java.lang.String.contentEquals(StringBuffer sb) compares this string to the specified StringBuffer, and returns true if both the String and StringBuffer are equal, else it returns false.
Example : An example program to demonstrate contentEquals(StringBuffer sb) method.
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)
This method java.lang.String.copyValueOf(char[] data) creates a new String object with the sequence of characters speicified by char[] data.
Example : An example program to demonstrate copyValueOf(char[] data) method.
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)
This method java.lang.String.copyValueOf(char[] data, int offset, int count) creates a new string object with the sequence of “count” number of characters of char[] data starting from offset position.
Example : An example program to demonstrate copyValueOf(char[] data, int offset, int count) method.
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 java.lang.String.endsWith(String suffix) tests if this string ends with the specified suffix.
Example : An example program to demonstrate endsWith(String suffix) method.
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 java.lang.String.equals(Object anObject) compares this string to the specified object.
Example : An example program to demonstrate equals(Object anObject) method.
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 java.lang.String.equalsIgnoreCase(String anotherString) compares this String to another String, ignoring if the characters in the Strings are uppercase or lowercase.
Example : An example program to demonstrate equalsIgnoreCase(String anotherString) method.
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 java.lang.String.format(Locale l, String format, Object… args) returns a formatted string using the specified locale, format string, and arguments.
Example : An example program to demonstrate format(Locale l, String format, Object… args) method.
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.
In the above program :
“Locale” is Locale.ENGLISH
“format” is : “%s %d days %s”
And there are three args (%s,%d,%s in format string) respectively are : “There are”, 365, “in an year.”
static String format(String format, Object… args)
The method java.lang.String.format(String format, Object… args) returns a formatted string using the specified format string and arguments.
Example : An example program to demonstrate format(String format, Object… args) method.
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.
In the above program “format” is : “%s %d days %s”
And there are three args : “There are”, 365, “in an year.”
byte[] getBytes()
The method java.lang.String.getBytes() encodes this String into a sequence of bytes using the platform’s default charset, storing the result into a new byte array.
Example : An example program to demonstrate getBytes() method.
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 java.lang.String.getBytes(Charset charset) encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.
Example : An example program to demonstrate getBytes(Charset charset) method.
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 java.lang.String.getBytes(String charsetName) encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
Example : An example to demonstrate getBytes(String charsetName) method.
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,