0% found this document useful (0 votes)
53 views

Characters Strings and StringBuilder

The document discusses different classes used to work with character data in Java - Character, String, StringBuilder, and StringBuffer. The Character class holds a single character value and defines methods to manipulate single character data. The String class represents fixed character strings, while StringBuilder and StringBuffer classes store and manipulate changeable character data. The document then provides details on using methods of these classes, such as comparing strings with equals() versus ==, concatenating strings, extracting substrings, converting between strings and numbers, and inserting/appending content into StringBuilder and StringBuffer.

Uploaded by

Neil Basabe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

Characters Strings and StringBuilder

The document discusses different classes used to work with character data in Java - Character, String, StringBuilder, and StringBuffer. The Character class holds a single character value and defines methods to manipulate single character data. The String class represents fixed character strings, while StringBuilder and StringBuffer classes store and manipulate changeable character data. The document then provides details on using methods of these classes, such as comparing strings with equals() versus ==, concatenating strings, extracting substrings, converting between strings and numbers, and inserting/appending content into StringBuilder and StringBuffer.

Uploaded by

Neil Basabe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Character, String, and

StringBuilder

Instructor: Mr. Neil A. Basabe, MIT


Understanding String Data Problems

Classes to use when working with character data

Character
Instances hold a single character value
Defines methods that can manipulate or inspect single-character
data

String
A class for working with fixed-string data
Unchanging data composed of multiple characters

StringBuilder and StringBuffer


Classes for storing and manipulating changeable data composed of
multiple characters
Using Character Class Methods
The String Class

The java.lang.String class represents character strings. You have


already used string literals, such as the parameter in println(String s)
method. The Java compiler actually converts the string literal into a
string object and passes it to println.
Constructing a String
To create a string explicitly, use a syntax like this one:
String newString = new String(s);
The argument s is a sequence of characters enclosed inside
double quotes. The following statements creates a String object
message for the string literal “Welcome to Java!”:
String message = new String(“Welcome to Java!”);
Since strings are used frequently, Java provides a simple
notation for creating a string;
String message = “Welcome to Java”;
String comparisons
Often, in a program, you need to compare the contents of two
strings. You might attempt to use the == operator, as follows:
if(string1==string2)
System.out.println(“string1 and string2 are the same
object”);
else
System.out.println(“string1 and string2 are different
objects”);
However, the == operator only checks whether string1 and
string2 refer to the same object; it does not tell you whether string1
and string2 contain the same contents when they are different
objects. Therefore, you cannot use the == operator to find out
whether two string variables have the same contents. Instead, you
should use the equals() method for an equality comparison of the
contents of objects.
if(string1.equals(string2))
System.out.println(“string1 and string2 have the same
contents”);
else
System.out.println(“string1 and string2 are not equal”);

The compareTo() method can also be used to


sompare two strings. Example:
s1.compareTo(s2);
the method returns the value 0 if s1 is equal to s2,
a value less than 0 if s1 is lexicographically less
than s2, and a value greater than 0 if s1 is lexicographically
greater than s2.
Syntax errors will occur if you compare strings by using comparison operators,
such as >, >=,<, <=.

The String class also provides equalsIgnoreCase and regionMatches methods for
comparing strings. The equalsIgnoreCase method ignores the case of the letters
when determining whether two strings are equal. The regionMatches method
Compares portions of two strings for equality.

String concatenation
You can use the concat method to concatenate two strings. Example,
String s3 = s1.concat(s2);
Since string concatenation is heavily used in programming, Java provides a
convenient way to concatenate strings. You can use the plus sign to concatenate
two or more strings. Example,
String myString = message + “ and ” + “HTML!”;
Recall that you have used the + sign concatenate a number with a
string in the println method. A number is converted into a string and
then concatenated.

Substrings

String is an immutable class. After a string is created, its value


cannot be changed individually. For example, you cannot change
“Java” in message to “HTML”. So what can you do if you need to
change the message string? You assign a new string to message.
Example,
message = “Welcome to HTML!”

As an alternative, you can use the substring method. You extract


a substring from a string by using the substring method in the String
class.
The substring method has two versions:
1. public String substring(int beginIndex, int endIndex)
This returns a new string that is a substring of this string. The
substring begins at the specified beginIndex and extends to the
character at index endIndex-1. Thus the length of the substring is
endIndex-beginIndex. The first character in a Java string has a
position of 0.
2. public String substring(int beginIndex)
This returns a new string that is a substring of this string. The
substrings begins with the character at the specified index and
extends to the end of this string.
For example,
String message = “Welcome to Java”.substring(0, 10) + “HTML!”;
The string message now becomes “Welcome to HTML!”.
String Length and Retrieving Individual Characters
in a String
You can get the length of a string by invoking
its length() method. For example,
message.length() returns the length of the string
message.

The s.charAt(index) method can be used to


retrieve a specific character in a string s, where
the index is between 0 and s.length()-1. For
example, message.charAt(0) returns the
character w.
Converting String Objects to Numbers
• Integer class Integer class valueOf() method
– Part of java.lang Converts a String to an Integer
– Automatically imported into class object
programs
Integer class intValue() method
– Converts a String to an Extracts the simple integer from its
integer wrapper class
– parseInt() method
Double class
• Takes a String
• A wrapper class
argument • Imported into programs
• Returns its integer value automatically
• Wrapper • parseDouble() method
Takes a String argument
– A class or an object and returns its double value
“wrapped around” a simpler
element
StringBuilder and StringBuffer Classes
• StringBuilder
– More efficient
• StringBuffer
– Thread safe
– Use in multithreaded programs

• setLength() method
– Changes the length of a String in a StringBuilder object
• length property
– An attribute of the StringBuilder class
– Identifies the number of characters in the String contained in the
StringBuilder
• capacity() method
– Finds the capacity of a StringBuilder object
StringBuilder Example
• Using StringBuilder • append() method
objects – Adds characters to the end of a
– Provides improved StringBuilder object
computer performance over • insert() method
String objects – Adds characters at a specific
location within a
– Can insert or append new StringBuilder object
contents into
• setCharAt() method
StringBuilder
– Changes a character at a
• StringBuilder constructors specified position within a
– public StringBuilder StringBuilder object
() • charAt() method
– public StringBuilder – Accepts an argument that is
(int capacity) the offset of the character
position from the beginning of
– public StringBuilder a String
(String s) – Returns the character at that
position
StringBuffer

The StringBuffer Class


The StringBuffer class is an alternative to the String class. In
general, a string buffer can be used wherever a string is used.
StringBuffer is more flexible than String. You can add, insert, or
append new contents into a string buffer. However, the value of a
string is fixed once the string is created.
The StringBuffer class provides 3 constructors:
1. public StringBuffer()
Constructs a string buffer with no characters in it and an initial
capacity of 16 characters.
2. public StringBuffer(int length)
Constructs a string buffer with no characters in it and an initial
capacity specified by the length argument.
3. public StringBuffer(String string)
Constructs a string buffer for the string argument. The initial
capacity of the string buffer is 16 plus the length of the string
argument.
Appending and Inserting New Contents into a StringBuffer
You can append new contents at the end of a string buffer or insert new
contents at a specified position in a string buffer.
The StringBuffer class provides 10 overloaded methods to append
boolean, char, char array, double, float, int, long, String and so on, into a
string buffer. For example, the following code appends strings and
characters into strBuf to form a new string, “Welcome to Java”.

StringBuffer strBuf = new StringBuffer();


strBuf.append(“Welcome”);
strBuf.append(‘ ‘);
strBuf.append(“to”);
strBuf.append(‘ ‘);
strBuf.append(“Java”);

The StringBuffer class also contains nine overloaded methods to insert


boolean, char, array, double, float, int, long, String, and so on, into a string
buffer.char
The capacity, reverse, length, setLength, charAt, and setCharAt methods

public int capacity()


This method returns the current capacity of the string buffer. The capacity is
the number of new characters that can be stored in it.
public synchronized StringBuffer reverse()
This method reverses the sequence of the string contained in the string
buffer.
public int length()
This method returns the number of characters in a string buffer.
public synchronized setLength(int newLength)
This method sets the length of the string buffer.
public synchronized charAt(int index)
This method returns the character at a specific index in the string buffer.
public synchronized void setCharAt(int index, char ch)
This method sets the character at the specified index of the string buffer to
ch.

The StringTokenizer Class


This class is used to break a string into pieces so that information contained
in it can be retrieved and processed. The delimiters break a string into pieces
known as tokens.
StringTokenizer constructors:
public StringTokenizer(String s, String delim, boolean returnTokens)
This constructor constructs a StringTokenizer for string s with specified
delimiters. If returnTokens is true, the delimiter is returned in a token.
public StringTokenizer(String s, String delim)
This constructor constructs a StringTokenizer for string s with specified
delimiters delim, and the delimiter is not considered in a token.
public StringTokenizer(String s)
This constructor constructs a StringTokenizer for string s with default
delimiters “ \t\n\r”, and the delimiter is not considered in a token.

StringTokenizer instance methods:

public boolean hasMoreTokens()


This method returns true if there is any token left in the string.
public String nextToken()
This method returns the next token in the string.
public String nextToken(String delim)
This method returns the next token in the string after resetting the delimiter
to delim.

You might also like