Você está na página 1de 7

Characters and Strings

The Java platform contains four classes that you can use when working with character
data:
Character: A class whose instances can hold a single character value
String : A class for working with immutable (unchanging) data composed of multiple
characters.
StringBuffer: A class for storing and manipulating mutable data composed of multiple
characters
StringBuilder: A faster, drop-in replacement for StringBuffer, designed for use by a
single thread only.

Character : An object of Character type contains a single character value. You use a
Character object instead of a primitive char variable when an object is required
for example, when passing a character value into a method that changes the value or
when placing a character value into a data structure, such as an ArrayList, that requ
ires objects. *Example(CharacterDemo)
Character a = new Character('a');

Strings and String Buffers The Java platform has always provided two classes, String,
and StringBuffer, which store and manipulate strings- character data consisting of
more than one character.

The String class provides for strings whose value will not change.

The StringBuffer class provides for strings that will be modified; you use string
buffers when you know that the value of the character data will change. You typically
use string buffers for constructing character data dynamically
String buffers are safe for use in a multi-threaded environment

String builder in the same way as a string buffer, but only if it's going to be accessed by
a single thread.

Question Which class to use under what conditions


• If your text is not going to change, use a string.
• If your text will change, and will only be accessed from a single thread, use a
string builder.
• If your text will change, but will be accessed from multiple threads, use a string
buffer.

A string is often created from a string literal—a series of characters enclosed in double
quotes.
You can also create String objects as you would any other Java object: using the new
keyword and a constructor. The String class provides several constructors that allow
you to provide the initial value of the string, using different sources, such as an array o
f characters, an array of bytes, a string buffer, or a string builder.

String str = "abc";


is equivalent to:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
*
Constructors in the String Class
Constructor Description
String() Creates an empty string.
String(byte[]) Creates a string whose value is set from the contents of an
String(byte[], int array of bytes. The two integer arguments, when present, set th
offset,int length)
String(byte[], int, i
e offset and the length, respectively, of the subarray from whic
nt, String) h to take the initial values. The String argument, when present,
String(byte[], String specifies the character encoding to use to convert bytes to char
) acters.
Creates a string whose value is set from the contents of an
String(char[])
String(char[], int,
array of characters. The two integer arguments, when present, s
int) et the offset and the length, respectively, of the subarray from
which to take the initial values.
Creates a string whose value is set from another string. Using
String(String) this constructor with a literal string argument is not recommen
ded, because it creates two identical strings.
String(StringBuffer) Creates a string whose value is set from a string buffer.
String(StringBuilder) Creates a string whose value is set from a string builder.

Constructors in the StringBuffer Class


Constructor Description
Creates an empty string buffer whose initial capacity is 16
StringBuffer()
characters.
Constructs a string buffer containing the same characters as
StringBuffer(CharSequence) the specified CharSequence. This constructor was introduce
d in JDK 5.0.
Creates an empty string buffer with the specified initial
StringBuffer(int)
capacity.
Creates a string buffer whose value is initialized by the
StringBuffer(String) specified String. The capacity of the string buffer is the lengt
h of the original string plus 16.

Getting the Length of a String or String Buffer


Methods used to obtain information about an object are known as accessor
methods. One accessor method that you can use with strings, string buffers, and string b
uilders is the length method, which returns the number of characters contained in the
object.
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
The StringBuffer and StringBuilder classes have a method called capacity, which
returns the amount of space allocated rather than the amount of space used.
String class doesn't have a capacity method, because a string cannot change

Getting Characters by Index from a String or String Buffer


You can get the character at a particular index within a string, string buffer, or
string builder by invoking the charAt accessor method.
Example
String anotherPalindrome = "Niagara. O roar again!";
char aChar = anotherPalindrome.charAt(9);
Indices begin at 0, so the character at index 9 is 'O'
Note
To compute the index of the last character of a string, you have to subtract 1 from the
value returned by the length method.

If you want to get more than one character from a string, string buffer, or string builder,
you can use the substring method.
Method Description
Returns a new string that is a substring of this string, string
String substring(int buffer, or string builder.The first integer argument specifies the
beginIndex) index of the first character. The second integer argument is the i
String substring(int ndex of the last character -1. The length of the substring is ther
beginIndex, int endIn efore the second int minus the first int. If the second integer i
dex)
s not present, the substring extends to the end of the original str
ing.

Example What will be the output of the following?


String anotherPalindrome = "Niagara. O roar again!";
String roar = anotherPalindrome.substring(11, 15);
Answer roar

Searching for a Character or a Substring within a String(*Example StringsIndexof)


The String class provides two accessor methods that return the position within
the string of a specific character or substring: indexOf and lastIndexOf.

The indexOf and lastIndexOf Methods in the String Class


Method Description
int indexOf(int ch)
int lastIndexOf(int
Returns the index of the first (last) occurrence of the
ch) specified character.
int indexOf(int ch, Returns the index of the first (last) occurrence of the
int fromIndex)
int lastIndexOf(int specified character, searching forward (backward) from the spe
ch, int fromIndex) cified index.
int indexOf(String
str) Returns the index of the first (last) occurrence of the specified
int lastIndexOf(Strin string.
g str)
int indexOf(String,
int) Returns the index of the first (last) occurrence of the specified
int lastIndexOf(Strin string, searching forward (backward) from the specified index
g, int)

Comparing Strings and Portions of Strings

*
Methods in the String Class for Comparing Strings
Method Description
Returns true if this string ends with or begins with
boolean endsWith(String) the substring specified as an argument to the method.
boolean startsWith(String)
boolean startsWith(String, The integer argument, when present, indicates the off
int) set within the original string at which to begin looki
ng.
Compares two strings lexicographically and
returns an integer indicating whether this string is
int compareTo(String) greater than (result is > 0), equal to (result is = 0),
int compareTo(Object)**
int or less than (result is < 0) the argument. The Object
compareToIgnoreCase(String)** argument is converted to a string before the comparis
on takes place. The com-pareToIgnoreCase method i
gnores case; thus, “a” and “A” are considered equal.
Returns true if this string contains the same
boolean equals(Object) sequence of characters as the argument. The Object
boolean argument is converted to a string before the comp
equalsIgnoreCase(String) arison takes place. The equalsIgnoreCase method ig
nores case; thus, “a” and “A” are considered equal.

Manipulating Strings
Can we manipulate Strings.
The String class has several methods that appear to modify a string. Of course,
strings can't be modified, so what these methods really do is create and return a seco
nd string that contains the result.

Methods in the String Class for Manipulating Strings


Method Description
Concatenates the String argument to the end of this string.
String concat(String) If the length of the argument is 0, the original string object is r
eturned.
Replaces all occurrences of the character specified as the first
String replace(char,
char) *Example(Replac
argument with the character specified as the second argumen
eDemo) t. If no replacements are necessary, the original string object is
returned.
String trim() Removes white space from both ends of this string.
String toLowerCase() Converts this string to lower- or uppercase. If no
String toUpperCase()
conversions are necessary, these methods return the original str
ing.

Modifying String Buffers


String buffers and String builders can change their content after they've been
created. Both classes provide various methods for modifying their data.

*
Methods for Modifying a String Buffer
Method Description
StringBuffer append(boolean)

StringBuffer append(char)
StringBuffer append(char[])
StringBuffer append(char[], Appends the argument to this string buffer. The data is
int, int)
StringBuffer append(double) converted to a string before the append operation
StringBuffer append(float) takes place.
StringBuffer append(int)
StringBuffer append(long)
StringBuffer append(Object)
StringBuffer append(String)

StringBuffer delete(int
start, int end)**
StringBuffer Deletes the specified character(s) in this string buffer.
deleteCharAt(int index)**

StringBuffer insert(int
offset, boolean b)
. StringBuffer insert(int of
fset, char c)
StringBuffer insert(int offs
et, char[]str)
StringBuffer insert(int, dou
ble) Inserts the second argument into the string buffer. The
StringBuffer insert(int, flo first integer argument indicates the index before which
at) the data is to be inserted. The data is converted to a str
StringBuffer insert(int, int
ing before the insert operation takes place.
)
StringBuffer insert(int, lon
g)
StringBuffer insert(int, Obj
ect)
StringBuffer insert(int, Str
ing)

StringBuffer replace(int
start, int end, String str) Replaces the specified character(s) in this string
buffer.

StringBuffer reverse()
Reverses the sequence of characters in this string
buffer

Strings and the Compiler


The compiler uses the String and the StringBuffer classes behind the scenes
to handle literal strings and concatenation.

Use String methods directly from a literal string:


int len = "Goodbye Cruel World".length();
use + to concatenate strings:
String cat = "cat";
System.out.println("con" + cat + "enation");
Behind the scenes, the compiler uses string buffers to implement concatenation
String cat = "cat";
System.out.println(new StringBuffer().append("con").
append(cat).append("enation").toString());

Question 1: What is the initial capacity of the following string buffer? StringBuffer sb =
new StringBuffer("Able was I ere I saw Elba.");
Answer 1: It's the length of the initial string + 16: 26 + 16 = 42.
Question 2: Consider the following string:
String hannah = "Did Hannah see bees? Hannah did.";
Question 2a: What is the value displayed by the expression hannah.length()?
Answer 2a: 32.
Question 2b: What is the value returned by the method call hannah.charAt(12)?
Answer 2b: e.
Question 2c: Write an expression that refers to the letter b in the string referred to by
hannah.
Answer 2c: hannah.charAt(15).
Question 3: How long is the string returned by the following expression? What is the
string?
"Was it a car or a cat I saw?".substring(9, 12)
Answer 3: It's 3 characters in length: car. It does not include the space after car.

The Wrapper Classes


Each Java primitive data type has a corresponding wrapper class. A
wrapper class is simply a class that encapsulates a single, immutable value.
For example, the Integer class wraps up an int value, and the Float class
wraps up a float value. The wrapper class names do not perfectly match
the corresponding primitive data type names.
Primitive Data Type Wrapper Class
boolean Boolean
byte Byte
char Character
short Short
int Integer
long Long
float Float
double Double

The following code fragment shows how to construct an instance of each wrapper type:

boolean primitiveBoolean = true;


Boolean wrappedBoolean =new Boolean(primitiveBoolean);

byte primitiveByte = 41;


Byte wrappedByte = new Byte(primitiveByte);
char primitiveChar = ‘M’;
Character wrappedChar = new Character(primitiveChar);

There is another way to construct any of these classes, with the exception of
Character: You can pass into the constructor a String that represents the value
to be wrapped. Most of these constructors throw NumberFormatException,
because there is always the possibility that the string will not represent a
valid value. Only Boolean does not throw this exception.

Boolean wrappedBoolean = new Boolean(“True”);


try {
Byte wrappedByte = new Byte(“41”);
Short wrappedShort = new Short(“31313”);
Integer wrappedInt = new Integer(“12345678”);
Long wrappedLong = new Long(“12345678987654321”);
Float wrappedFloat = new Float(“1.11f”);
Double wrappedDouble = new Double(“1.11111111”);
}
catch (NumberFormatException e) {
System.out.println(“Bad Number Format”);
}

Você também pode gostar