Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java String Class

Java String Class

Strings are widely used in Java programming. In Java, strings are 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

=

"

Runoob

"

;

When the compiler encounters a string constant in the code, here the value is "Runoob", the compiler uses that value to create a String object.

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

Creating a string with a constructor:

String

str2

=

new

String

(

"

Runoob

"

)

;

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

String

s1

=

"

Runoob

"

;

//

String created directly

String

s2

=

"

Runoob

"

;

//

String created directly

String

s3

=

s1

;

//

Same reference

String

s4

=

new

String

(

"

Runoob

"

)

;

//

String object created

String

s5

=

new

String

(

"

Runoob

"

)

;

//

String object created

The String class has 11 constructors that provide different parameters to initialize a string, such as providing a character array parameter:

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 compilation and execution results of the above example are as follows:


runoob

**Note:** The String class is immutable, so once you create a String object, its value cannot be changed (see the notes section for details).

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


String Length

Methods used to obtain 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 executes, the len variable equals 14:

StringDemo.java file code:

public

class

StringDemo

{

public

static

void

main

(

String

args

[

]

)

{

String

site

=

"

www.runoob.com

"

;

int

len

=

site

.

length

(

)

;

System

.

out

.

println

(

"

Runoob Tutorial URL length :

"

len

)

;

}

}

The compilation and execution results of the above example are as follows:


Runoob Tutorial网址长度 : 14

Concatenating Strings

The String class provides methods to concatenate two strings:

string1

.

concat

(

string2

)

;

Returns a new string with string2 concatenated to string1. You can also use the concat() method on string constants, as in:

"我的名字是 ".concat("Runoob");

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


"Hello," + " runoob" + "!"

The result is as follows:


"Hello, runoob!"

Here is an example:

StringDemo.java file code:

public

class

StringDemo

{

public

static

void

main

(

String

args

[

]

)

{

String

string1

=

"

Runoob Tutorial URL:

"

;

System

.

out

.

println

(

"

1.

"

string1

"

www.runoob.com

"

)

;

}

}

The compilation and execution results of the above example are as follows:


1、Runoob Tutorial网址:www.runoob.com

Creating Formatted Strings

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

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

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

As shown below:

System

.

out

.

printf

(

"

The value of the floating-point variable is

"

"

%f, the value of the integer variable is

"

"

%d, the value of the string variable is

"

"

is %s

"

,

floatVar

,

intVar

,

stringVar

)

;

You can also write it like this

String

fs

;

fs

=

String

.

format

(

"

The value of the floating-point variable is

"

"

%f, the value of the integer variable is

"

"

%d, the value of the string variable is

"

"

%s

"

,

floatVar

,

intVar

,

stringVar

)

;


String Methods

The following are the methods supported by the String class; for more details, see the 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)
Compares this string with another object.
3 int compareTo(String anotherString)
Compares two strings lexicographically.
4 int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences.
5 String concat(String str)
Concatenates the specified string to the end of this string.
6 boolean contentEquals(StringBuffer sb)
Returns true if and only if the string has the same sequence of characters as the specified StringBuffer.
7 static String copyValueOf(char[] data)
Returns the String representing the character sequence in the specified array.
8 static String copyValueOf(char[] data, int offset, int count)
Returns the String representing the character sequence in the specified array.
9 boolean endsWith(String suffix)
Tests whether this string ends with the specified suffix.
10 boolean equals(Object anObject)
Compares this string with the specified object.
11 boolean equalsIgnoreCase(String anotherString)
Compares this String with another String, ignoring case differences.
12 byte[] getBytes()
 Encodes this String into a byte sequence using the platform's default charset and stores the result in a new byte array.
13 byte[] getBytes(String charsetName)
Encodes this String into a byte sequence using the specified charset and stores the result in a new byte array.
14 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
15 int hashCode()
Returns the hash code of this string.
16 int indexOf(int ch)
Returns the index of the first occurrence of the specified character in this string.
17 int indexOf(int ch, int fromIndex)
Returns the index of the first occurrence of the specified character in this string, starting the search from the specified index.
18 int indexOf(String str)
 Returns the index of the first occurrence of the specified substring in this string.
19 int indexOf(String str, int fromIndex)
Returns the index of the first occurrence of the specified substring in this string, starting from the specified index.
20 String intern()
 Returns the canonical representation of the string object.
21 int lastIndexOf(int ch)
 Returns the index of the last occurrence of the specified character in this string.
22 int lastIndexOf(int ch, int fromIndex)
Returns the index of the last occurrence of the specified character in this string, searching backward from the specified index.
23 int lastIndexOf(String str)
Returns the index of the rightmost occurrence of the specified substring in this string.
24 int lastIndexOf(String str, int fromIndex)
 Returns the index of the last occurrence of the specified substring in this string, searching backward from the specified index.
25 int length()
Returns the length of this string.
26 boolean matches(String regex)
Tells whether this string matches the given regular expression.
27 boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Tests whether two string regions are equal.
28 boolean regionMatches(int toffset, String other, int ooffset, int len)
Tests whether two string regions are equal.
29 String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
30 String replaceAll(String regex, String replacement)
Replaces all substrings of this string that match the given regular expression with the given replacement.
31 String replaceFirst(String regex, String replacement)
 Replaces the first substring of this string that matches the given regular expression with the given replacement.
32 String[] split(String regex)
Splits this string around matches of the given regular expression.
33 String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.
34 boolean startsWith(String prefix)
Tests whether this string starts with the specified prefix.
35 boolean startsWith(String prefix, int toffset)
Tests whether the substring of this string starting at the specified index starts with the specified prefix.
36 CharSequence subSequence(int beginIndex, int endIndex)
 Returns a new character sequence that is a subsequence of this sequence.
37 String substring(int beginIndex)
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 into a new character array.
40 String toLowerCase()
Converts all characters in this String to lowercase using the rules of the default locale.
41 String toLowerCase(Locale locale)
 Converts all characters in this String to lowercase using the rules of the given Locale.
42 String toString()
 Returns this object itself (it is already a string!).
43 String toUpperCase()
Converts all characters in this String to uppercase using the rules of the default locale.
44 String toUpperCase(Locale locale)
Converts all characters in this String to uppercase using the rules of the given Locale.
45 String trim()
Returns a copy of the string with leading and trailing whitespace omitted.
46 static String valueOf(primitive data type x)
Returns the string representation of the x argument of the given data type.
47 contains(CharSequence chars)
Determines whether it contains the specified sequence of characters.
48 isEmpty()
Determines whether the string is empty.