Latest web development tutorials

Java String class

String widely used in Java programming in Java objects belonging to the string, Java provides the String class to create and manipulate strings.


Creating strings

The easiest way to create a string as follows:

String greeting = "Hello world!";

Encountered string constants in the code, where the value is "Hello world!", The compiler will use this value to create a String object.

And other objects, you can use keywords and constructors to create String objects.

String class has 11 kinds of construction methods that provide different parameters to the initialization string, such as a character array parameters:

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 compiled results are as follows:

hello.

Note: String class is immutable, so once you create a String object that its value can not be changed. If you need to do a lot of modifications to the string, you should choose to use StringBuffer & StringBuilder class .


String length

The method used to obtain information about the object called accessor methods.

An access control method of the String class is the length () method, which returns the number of characters contained object.

After the following code executes, len variable is equal to 14:

public class StringDemo {
    public static void main(String args[]) {
        String site = "www.w3big.com";
        int len = site.length();
        System.out.println( "本教程网址长度 : " + len );
   }
}

The above examples compiled results are as follows:

本教程网址长度 : 14

Connection String

String class provides a way to concatenate two strings:

string1.concat(string2);

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

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

More common is to use the '+' operator to concatenate strings, such as:

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

The results are as follows:

"Hello, world!"

Here is an example:

public class StringDemo {
    public static void main(String args[]) {     
        String string1 = "本教程网址:";     
        System.out.println("1、" + string1 + "www.w3big.com");  
    }
}

The above examples compiled results are as follows:

1、本教程网址:www.w3big.com

Create a formatted string

We know that the digital output format can use printf () and format () method. String class using the static method format () Returns a String object rather than a PrintStream object.

Static method format String class () can be used to create a formatted string reusable, and not just for a printout. As follows:

System.out.printf("浮点型变量的的值为 " +
                  "%f, 整型变量的值为 " +
                  " %d, 字符串变量的值为 " +
                  "is %s", floatVar, intVar, stringVar);

You can also write

String fs;
fs = String.format("浮点型变量的的值为 " +
                   "%f, 整型变量的值为 " +
                   " %d, 字符串变量的值为 " +
                   " %s", floatVar, intVar, stringVar);
System.out.println(fs);

String Methods

Here is the String class supports methods for more details, see Java String API documentation:

SN (serial number) Method Description
1 char charAt (int index)
Returns the char value at the specified index.
2 int compareTo (Object o)
To compare strings and other objects.
3 int compareTo (String anotherString)
Compares two strings lexicographically.
4 int compareToIgnoreCase (String str)
Compares two strings lexicographically, ignoring case.
5 String concat (String str)
The specified string connected to this end of the string.
6 boolean contentEquals (StringBuffer sb)
If and only if the specified string StringButter have the same sequence of characters returns true.
7 static String copyValueOf (char [] data )
Returns String array represents the character sequence.
8 static String copyValueOf (char [] data , int offset, int count)
Returns String array represents the character sequence.
9 boolean endsWith (String suffix)
Tests if this string ends with the specified suffix.
10 boolean equals (Object anObject)
Compares this string to the specified object.
11 boolean equalsIgnoreCase (String anotherString)
Compare this String to another String, ignoring case considerations.
12 byte [] getBytes ()
Using the platform's default character set this String encoded byte sequence and stores the result into a new byte array.
13 byte [] getBytes (String charsetName)
Using the specified character set this String encoded byte sequence and stores the result into a new byte array.
14 void getChars (int srcBegin, int srcEnd , char [] dst, int dstBegin)
The characters from the string copied to the destination character array.
15 int hashCode ()
Returns the hash code for this string.
16 int indexOf (int ch)
Returns the specified character index within this string of the first occurrence.
17 int indexOf (int ch, int fromIndex )
Returns the index within this string of the specified character appears at first to start the search at the specified index.
18 int indexOf (String str)
Returns the specified substring in this string at the first occurrence of the index.
19 int indexOf (String str, int fromIndex )
Returns the specified substring in this string at the first occurrence of the index, starting at the specified index.
20 String intern ()
Returns a string representation of the object of standardization.
twenty one int lastIndexOf (int ch)
Returns the specified character index within this string of the last occurrence.
twenty two int lastIndexOf (int ch, int fromIndex )
Returns the specified character index within this string of the last occurrence of the specified index from the start reverse search.
twenty three int lastIndexOf (String str)
Returns the specified substring in this string in the index of the rightmost occurrence.
twenty four int lastIndexOf (String str, int fromIndex )
Returns the specified substring in this string at the last occurrence of the index, starting at the specified index of reverse search.
25 int length ()
Returns the length of this string.
26 boolean matches (String regex)
Inform this string matches the given regular expression.
27 boolean regionMatches (boolean ignoreCase, int toffset , String other, int ooffset, int len)
Tests if two string regions are equal.
28 boolean regionMatches (int toffset, String other , int ooffset, int len)
Tests if two string regions are equal.
29 String replace (char oldChar, char newChar )
It returns a new string that is by replacing all oldChar this string with newChar obtained.
30 String replaceAll (String regex, String replacement
Using the given replacement string replaces all matching the given regular expression substring.
31 String replaceFirst (String regex, String replacement )
Using the given replacement Replace this string matches the given regular expression first substring.
32 String [] split (String regex)
According to the given regular expression matching split this string.
33 String [] split (String regex, int limit)
According to match the given regular expression to split this string.
34 boolean startsWith (String prefix)
Tests if this string starts with the specified prefix.
35 boolean startsWith (String prefix, int toffset )
Substring test this string beginning at the specified index starts with the specified prefix.
36 CharSequence subSequence (int beginIndex, int endIndex )
It returns a new character sequence that is a subsequence of this sequence.
37 String substring (int beginIndex)
It returns a new string that is a substring of this string.
38 String substring (int beginIndex, int endIndex )
Returns a new string that is a substring of this string.
39 char [] toCharArray ()
Converts this string to a new character array.
40 String toLowerCase ()
Using rules of the default locale in this String all the characters are converted to lowercase.
41 String toLowerCase (Locale locale)
Given Locale rules in this String all the characters are converted to lowercase.
42 String toString ()
Returns this object itself (which is already a string!).
43 String toUpperCase ()
Using rules of the default locale in this String all the characters are converted to uppercase.
44 String toUpperCase (Locale locale)
Given Locale rules in this String all the characters are converted to uppercase.
45 String trim ()
Returns a copy of the string, ignoring leading and trailing whitespace.
46 static String valueOf (primitive data type x )
Returns a string given data type to the type of x parameter representation.