Easy Tutorial
❮ Java Filereader Number Tan ❯

Java String Class

Strings are widely used in Java programming. In Java, strings are treated as objects, and Java provides the String class to create and manipulate strings.


Creating Strings

The simplest way to create a string is as follows:

String str = "tutorialpro";

When a string constant is encountered in the code, such as "tutorialpro", the compiler creates a String object with the value.

Like any other object, you can create a String object using the new keyword and a constructor.

Creating a string with a constructor:

String str2 = new String("tutorialpro");

Strings created with String are stored in the common pool, while strings created with new are stored on the heap:

String s1 = "tutorialpro";              // String direct creation
String s2 = "tutorialpro";              // String direct creation
String s3 = s1;                    // Same reference
String s4 = new String("tutorialpro");   // String object creation
String s5 = new String("tutorialpro");   // String object creation

The String class has 11 constructors that allow you to initialize strings with different parameters, such as a character array:

StringDemo.java File Code:

public class StringDemo {
   public static void main(String args[]) {
      char[] helloArray = { 'r', 'u', 'n', 'o', 'o', 'b' };
      String helloString = new String(helloArray);  
      System.out.println(helloString);
   }
}

The above example compiles and runs with the following result:

tutorialpro

Note: The String class is immutable, so once a String object is created, its value cannot be changed (see the notes section for detailed explanation).

If you need to make many modifications to a string, you should use the StringBuffer & StringBuilder classes.


String Length

Methods that provide information about an object are called accessor methods.

One accessor method of the String class is the length() method, which returns the number of characters contained in the string object.

After the following code is executed, the len variable equals 14:

StringDemo.java File Code:

public class StringDemo {
    public static void main(String args[]) {
        String site = "www.tutorialpro.org";
        int len = site.length();
        System.out.println("tutorialpro.org website length: " + len);
    }
}

The above example compiles and runs with the following result:

tutorialpro.org website length: 14

Concatenating Strings

The String class provides a method to concatenate two strings:

string1.concat(string2);

This returns a new string that is string2 appended to string1. You can also use the concat() method with string constants, such as:

"My name is ".concat("tutorialpro");

More commonly, the '+' operator is used to concatenate strings, such as:

"Hello, " + " tutorialpro" + "!"

The result is:

"Hello, tutorialpro!"

Here is an example:

StringDemo.java File Code:

public class StringDemo {
    public static void main(String args[]) {     
        String string1 = "tutorialpro.org website: ";     
        System.out.println("1、" + string1 + "www.tutorialpro.org");  
    }
}

The above example compiles and runs with the following result:

1、tutorialpro.org website: www.tutorialpro.org

Creating Formatted Strings

We know that formatted numbers can be output using the printf() and format() methods.

The String class uses the static format() method to return a String object instead of a PrintStream object.

The static format() method of the String class can be used to create reusable formatted strings, not just for one-time print output.

As shown below:

System.out.printf("The value of the float variable is " +
                  "%f, while the value of the integer variable is " +
                  "%d, and the value of the string variable is " +
                  "%s", floatVar, intVar, stringVar);

You can also write it like this:

String fs;
fs = String.format("The value of the float variable is " +
                   "%f, while the value of the integer variable is " +
                   "%d, and the value of the string variable is " +
                   "%s", floatVar, intVar, stringVar);

String Methods

Below are the methods supported by the String class. For more details, refer to the Java String API documentation:

SN(Serial Number) Method Description
1 char charAt(int index) <br>Returns the char value at the specified index.
2 int compareTo(Object o) <br>Compares this string to another object.
3 int compareTo(String anotherString) <br>Compares two strings lexicographically.
4 int compareToIgnoreCase(String str) <br>Compares two strings lexicographically, ignoring case differences.
5 String concat(String str) <br>Concatenates the specified string to the end of this string.
6 boolean contentEquals(StringBuffer sb) <br>Returns true if and only if this string represents the same sequence of characters as the specified StringBuffer.
7 static String copyValueOf(char[] data) <br>Returns a String that represents the character sequence in the array specified.
8 static String copyValueOf(char[] data, int offset, int count) <br>Returns a String that represents the character sequence in the array specified.
9 boolean endsWith(String suffix) <br>Tests if this string ends with the specified suffix.
10 boolean equals(Object anObject) <br>Compares this string to the specified object.
11 boolean equalsIgnoreCase(String anotherString) <br>Compares this String to another String, ignoring case considerations.
12 byte[] getBytes() <br>Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
13 byte[] getBytes(String charsetName) <br>Encodes this String into a sequence of bytes using the specified charset, storing the result into a new byte array.
14 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) <br>Copies characters from this string into the destination character array.
15 int hashCode() <br>Returns the hash code of this string.
16 int indexOf(int ch) <br>Returns the index within this string of the first occurrence of the specified character.
17 int indexOf(int ch, int fromIndex) <br>Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
18 int indexOf(String str) <br>Returns the index within this string of the first occurrence of the specified substring.
19 int indexOf(String str, int fromIndex) <br>Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
20 String intern() <br>Returns a canonical representation for the string object.
21 int lastIndexOf(int ch) <br>Returns the index within this string of the last occurrence of the specified character.
22 int lastIndexOf(int ch, int fromIndex) <br>Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
23 int lastIndexOf(String str) <br>Returns the index within this string of the last occurrence of the specified substring.
24 int lastIndexOf(String str, int fromIndex) <br>Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
25 int length() <br>Returns the length of this string.
26 boolean matches(String regex) <br>Tells whether or not this string matches the given regular expression.
27 boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) <br>Tests if two string regions are equal.
28 boolean regionMatches(int toffset, String other, int ooffset, int len) <br>Tests if two string regions are equal.
29 String replace(char oldChar, char newChar) <br>Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
30 String replaceAll(String regex, String replacement) <br>Replaces each substring of this string that matches the given regular expression with the given replacement.
31 String replaceFirst(String regex, String replacement) <br>Replaces the first substring of this string that matches the given regular expression with the given replacement.
32 String[] split(String regex) <br>Splits this string around matches of the given regular expression.
33 String[] split(String regex, int limit) <br>Splits this string around matches of the given regular expression.
34 boolean startsWith(String prefix) <br>Tests if this string starts with the specified prefix.
35 boolean startsWith(String prefix, int toffset) <br>Tests if the substring of this string starting at the specified index starts with the specified prefix.
36 CharSequence subSequence(int beginIndex, int endIndex) <br>Returns a new character sequence that is a subsequence of this sequence.
37 String substring(int beginIndex) <br>Returns a new string that is a substring of this string.
38 String substring(int beginIndex, int endIndex) <br>Returns a new string that is a substring of this string.
39 char[] toCharArray() <br>Converts this string to a new character array.
40 String toLowerCase() <br>Converts all of the characters in this String to lower case using the rules of the default locale.
41 String toLowerCase(Locale locale) <br>Converts all of the characters in this String to lower case using the rules of the given Locale.
42 String toString() <br>Returns the object itself (it's already a string!).
43 String toUpperCase() <br>Converts all of the characters in this String to upper case using the rules of the default locale.
44 String toUpperCase(Locale locale) <br>Converts all of the characters in this String to upper case using the rules of the given Locale.
45 String trim() <br>Returns a copy of the string, with leading and trailing whitespace omitted.
46 static String valueOf(primitive data type x) <br>Returns the string representation of the given data type x parameter.
47 contains(CharSequence chars) <br>Checks if it contains the specified character sequence.
48 isEmpty() <br>Checks if the string is empty.
❮ Java Filereader Number Tan ❯