Name
String
Synopsis
The String
class
represents a read-only string of characters. A
String
object is created by the Java compiler
whenever it encounters a string in double quotes; this method of
creation is typically simpler than using a constructor. The static
valueOf( )
factory methods create new
String
objects that hold the textual
representation of various Java primitive types. There are also
valueOf( )
methods, copyValueOf(
)
methods and String( )
constructors for
creating a String
object that holds a copy of the
text contained in another String
,
StringBuffer
, StringBuilder
, or
a char
or int
array. You can
also use the String( )
constructor to create a
String
object from an array of bytes. If you do
this, you may explicitly specify the name of the charset (or
character encoding) to be used to decode the bytes into characters,
or you can rely on the default charset for your platform. (See
java.nio.charset.Charset
for more on charset
names.)
In Java
5.0, the
static format( )
methods provide another useful
way to create String
objects that hold formatted
text. These utility methods create and use a new
java.util.Formatter
object and behave like the
sprintf( )
function in the C programming language.
length( )
returns the
number of characters in a string. charAt( )
extracts a character from a string. You can use these two methods to
iterate through the characters of a string. You can obtain a
char
array that holds the characters of a string
with toCharArray( )
, or use getChars( ...
Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.