Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Java String class


May 10, 2021 Java


Table of contents


Java String class

Strings are widely used in Java programming, where strings belong to objects, and Java provides String classes to create and manipulate strings.


Create a string

The easiest way to create a string is as follows:

String greeting = "Hello world!";

When you encounter a string constant in your code, the value here is "Hello world!" and the compiler uses that value to create a String object.

Like other objects, you can use keywords and construction methods to create String objects.

The String class has 11 construction methods that provide different parameters to initialize strings, such as an array of characters:

public class StringDemo{

   public static void main(String args[]){
      char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
      String helloString = new String(helloArray);  
      System.out.println( helloString );
   }
}

The above examples compile and run as follows:

hello.

Note: T he String class is imm changed, so once you create a String object, its value cannot be changed. If you need to make a lot of changes to the string, you should choose to use the StringBuffer and StringBuilder classes.


The length of the string

The method used to get information about an object is called the accessor method.

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

After the following code is executed, the len variable is equal to 17:

public class StringDemo {

   public static void main(String args[]) {
      String palindrome = "Dot saw I was Tod";
      int len = palindrome.length();
      System.out.println( "String Length is : " + len );
   }
}

The above examples compile and run as follows:

String Length is : 17

The connection string

The String class provides a way to connect two strings:

string1.concat(string2);

Returns a new string for string2 connection string1. You can also use the concat() method for string constants, such as:

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

It is more common to use the 'plus' operator to connect strings, such as:

"Hello," + " world" + "!"

The results are as follows:

"Hello, world!"

Here's an example:

public class StringDemo {
   public static void main(String args[]) {     
   String string1 = "saw I was ";     
   System.out.println("Dot " + string1 + "Tod");  
}
}

The above examples compile and run as follows:

Dot saw I was Tod

Create a formatted string

We know that output formatted numbers can use the printf() and format() methods. The String class uses the static method format() to return a String object instead of a PrintStream object.

The static method format() of the String class can be used to create reusable formatted strings, not just for one printout. Here's what it looks like:

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

You can write like that, too

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

String method

Here's how the String class supports it, see the Java API documentation for more detail:

SN (Serial No.) Method description
1 char charAt(int index)
Returns the char value at the specified index.
2 int compareTo(Object o)
Compare this string with another object.
3 int compareTo(String anotherString)
Compare the two strings in dictionary order.
4 int compareToIgnoreCase(String str)
Compare two strings in dictionary order, without considering case.
5 String concat(String str)
Connect the specified string to the end of the string.
6 boolean contentEquals(StringBuffer sb)
True when and only if the string has characters in the same order as the specified StringButter.
7 static String copyValueOf(char[] data)
Returns String, which represents the sequence of characters in the specified array.
8 static String copyValueOf(char[] data, int offset, int count)
Returns String, which represents the sequence of characters in the specified array.
9 boolean endsWith(String suffix)
Test whether this string ends with the specified suffix.
10 boolean equals(Object anObject)
Compare this string to the specified object.
11 boolean equalsIgnoreCase(String anotherString)
Compare this String with another String, without considering case.
12 byte[] getBytes()
Use the platform's default character set to encode this String as a byte sequence and store the results in a new byte array.
13 byte[] getBytes(String charsetName)
Use the specified character set to encode this String as a byte sequence and store the results in a new byte array.
14 void getChars (int srcBegin, int srcEnd, char sst, int dstBegin) copies characters from this string to the target character array.
15 int hashCode()
Returns the hash code for this string.
16 int indexOf(int ch)
Returns the index where the specified character first appears in this string.
17 int indexOf(int ch, int fromIndex)
Returns the index at which the specified character first appears in this string, starting with the specified index.
18 int indexOf(String str)
Returns the index where the specified substring first appears in this string.
19 int indexOf(String str, int fromIndex)
Returns the index at which the specified substring first appears in this string, starting with the specified index.
20 String intern()
Returns a normalized representation of the string object.
21 int lastIndexOf(int ch)
Returns the index where the specified character last appeared in this string.
22 int lastIndexOf(int ch, int fromIndex)
Returns the index at which the specified character last appeared in this string, starting with a reverse search at the specified index.
23 int lastIndexOf(String str)
Returns the index that specifies where the substring appears on the far right of the string.
24 int lastIndexOf(String str, int fromIndex)
Returns the index at which the specified substring last appeared in this string, starting with a reverse search of the specified index.
25 int length()
Returns the length of this string.
26 boolean matches(String regex)
Tells this string if it matches a given regular expression.
27 boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Test whether the two string regions are equal.
28 boolean regionMatches(int toffset, String other, int ooffset, int len)
Test whether the two string regions are equal.
29 String replace(char oldChar, char newChar)
Returns a new string, which is obtained by replacing all oldChars that appear in this string with newChar.
30 String replaceAll(String regex, String replacement
Replace this string with a given replacement for all substrings that match a given regular expression.
31 String replaceFirst(String regex, String replacement)
Replace this string with a given replacement to match the first substring of a given regular expression.
32 String[] split(String regex)
Split this string based on a match for a given regular expression.
33 String[] split(String regex, int limit)
Split this string based on matching a given regular expression.
34 boolean startsWith(String prefix)
Test whether this string starts with the specified prefix.
35 boolean startsWith(String prefix, int toffset)
Test whether this string starts with a substring that starts with the specified index and starts with a specified prefix.
36 CharSequence subSequence(int beginIndex, int endIndex)
Returns a new sequence of characters, which is a subsethic of this sequence.
37 String substring(int beginIndex)
Returns a new string, which is a substring of this string.
38 String substring(int beginIndex, int endIndex)
Returns a new string, which is a substring of this string.
39 char[] toCharArray()
Convert this string to a new array of characters.
40 String toLowerCase()
Use the rules of the default locale to convert all characters in this String to small case.
41 String toLowerCase(Locale locale)
Use the rules for a given Locale to convert all characters in this String to small case.
42 String toString()
Return this object itself (it is already a string!) )。
43 String toUpperCase()
Use the rules of the default locale to convert all characters in this String to capital.
44 String toUpperCase(Locale locale)
Use the rules of a given Locale to convert all characters in this String to capital.
45 String trim()
Returns a copy of the string, ignoring leading and tail white space.
46 static String valueOf(primitive data type x)
Returns a string representation of a given data type type x argument.