Updated Module 2
Updated Module 2
String Handling: The String Constructors, String Length, Special String Operations, Character
Extraction, String Comparison, Searching Strings, Modifying a String, Data Conversion Using
valueOf( ), Changing the Case of Characters Within a String, joining strings, Additional String
Methods, StringBuffer, StringBuilder
Unlike some other languages that implement strings as character arrays, Java implements strings as
objects of type String.
package Strings;
public object_types() {
// TODO Auto-generated constructor stub
}
o/p
The String class supports several constructors. To create an empty String, call the default constructor.
For example,
Frequently, you will want to create strings that have initial values. The String class provides a variety of
constructors to handle this. To create a String initialized by an array of characters, use the constructor
shown here:
char chars={‘a’,’b’,’c’};
String s= new String(chars);
String(char chars[ ])
Here is an example:
This constructor initializes s with the string "abc".
// Construct one String from another.
class MakeString {
public static void main(String[] args) {
char[] c = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
o/p
Java
Java
o/p
ABCDEF
CDE
String Length
The length of a string is the number of characters that it contains. To obtain this
value, call the length( ) method, shown here:
int length( )
The following fragment prints 3, since there are three characters in the string s:
Special String Operations
String Literals
System.out.println(“abc”.length());
String Concatenation
In general, Java does not allow operators to be applied to String objects. The one exception to this rule
is the + operator, which concatenates two strings, producing a String object as the result. This allows
you to chain together a series of + operations.
o/p
This could have been a very long line that would have wrapped around. But string concatenation
prevents this.
String Concatenation with Other Data Types
You can concatenate strings with other types of data. For example, consider this slightly different
version of the earlier example:
In this case, age is an int rather than another String, but the output produced is the same as before. This
is because the int value in age is automatically converted into its string representation within a String
object. This string is then concatenated as before. The compiler will convert an operand to its string
equivalent whenever the other operand of the + is an instance of String.
Be careful when you mix other types of operations with string concatenation expressions, however. You
might get surprising results. Consider the following:
String Conversion and toString( )
If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the String representation of the object.
If you print any object, Java compiler internally invokes the toString() method on the object. So overriding
the toString() method, returns the desired output, it can be the state of an object etc. depending on your
implementation.
class Student{
int rollno;
String name;
String city;
o/p
Character Extraction
charAt( )
To extract a single character from a String, you can refer directly to an individual
character via the charAt( ) method. It has this general form:
char charAt(int where)
Here, where is the index of the character that you want to obtain. The value of where
must be nonnegative and specify a location within the string. charAt( ) returns the
character at the specified location. For example,
getBytes()
getBytes() method does the encoding of string into the sequence of bytes and keeps it in an array of
bytes.
o/p
65 66 67 68 69 70 71
toCharArray()
In Java, the toCharArray() method of the String class converts the given string into a character array.
// Define a string
String s = "AIET";
o/p
AIET
Explanation: In the above example, the toCharArray() method breaks the string "AIET" into individual
characters for processing. Then a for-each loop iterates through the array and prints each character
String Comparison
The String class includes a number of methods that compare strings or substrings
within strings. Several are examined here.
o/p
regionMatches( )
The regionMatches( ) method compares a specific region inside a string with another specific region in
another string. There is an overloaded form that allows you to ignore case in such comparisons
In Java, regionMatches() method of the String class compares parts (regions) of two strings to see if
they match. It offers both case-sensitive and case-insensitive comparison options. This method is
commonly used in string matching and validation tasks
System.out.println("" + res);
}
}
o/p
true
String defines two methods that are, more or less, specialized forms of regionMatches( ). The
startsWith( ) method determines whether a given String begins with a specified string. Conversely,
endsWith( ) determines whether the String in question ends with a specified string.
In Java, the startsWith() and endsWith() methods of the String class are used to check whether a string
begins or ends with a specific prefix or suffix, respectively.
Example:
This example demonstrates the usage of the startsWith() and endsWith() methods in Java.
o/p
equals( ) Versus ==
It is important to understand that the equals( ) method and the == operator perform two different
operations. As just explained, the equals( ) method compares the characters inside a String object.
The == operator compares two object references to see whether they refer to the same instance. The
following program shows how two different String objects can contain the same characters, but
references to these objects will not compare as equal
// equals() vs ==
class EqualsNotEqualTo {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = new String(s1);
o/p
compareTo( )
Often, it is not enough to simply know whether two strings are identical. For sorting applications, you
need to know which is less than, equal to, or greater than the next. A string is less than another if it
comes before the other in dictionary order. A string is greater than another if it comes after the other in
dictionary order. The method compareTo( ) serves this purpose. It is specified by the Comparable<T>
interface, which String implements. It has this general form:
int compareTo(String str)
Here, str is the String being compared with the invoking String. The result of the comparison is
returned and is interpreted as shown here:
o/p
Searching Strings
The String class provides two methods that allow you to search a string for a specified character or
substring:
System.out.println(s);
System.out.println("indexOf(t) = " +
s.indexOf('t'));
System.out.println("lastIndexOf(t) = " +
s.lastIndexOf('t'));
System.out.println("indexOf(the) = " +
s.indexOf("the"));
System.out.println("lastIndexOf(the) = " +
s.lastIndexOf("the"));
System.out.println("indexOf(t, 10) = " +
s.indexOf('t', 10));
System.out.println("lastIndexOf(t, 60) = " +
s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = " +
s.indexOf("the", 10));
System.out.println("lastIndexOf(the, 60) = " +
s.lastIndexOf("the", 60));
}
}
o/p
Modifying a String
Because String objects are immutable, whenever you want to modify a String, you must either copy it
into a StringBuffer or StringBuilder.
substring( )
You can extract a substring using substring( ). It has two forms. The first is
Here, startIndex specifies the index at which the substring will begin. This form returns a copy of the
substring that begins at startIndex and runs to the end of the invoking string.
The second form of substring( ) allows you to specify both the beginning and ending index of the
substring:
Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. The string
returned contains all the characters from the beginning index, up to, but not including, the ending
index.
In Java, substring() method of String class returns a substring from the given string. This method is
most useful when you deal with text manipulation, parsing, or data extraction.
This method either take 1 parameter or 2 parameters i.e. start and end value as arguments.
In case, if the end parameter is not specified then the substring will end at the end of the string.
Syntax:
Example 1: Here, we are using the substring(int begIndex) method to extract a substring from the given
string starting at index 6 and ending at the end of the string. The substring begins at index 7, and since
no endIndex is provided, it continues to the end of the string. begIndex is inclusive.
Output
Substring: rGeeks
Example 2: Here, we will use the String substring(begIndex, endIndex) method. This method will
return the substring that begins with the character at the specified index and ends at endIndex – 1
Substring: Welcome to G
concat( )
You can concatenate two strings using concat( ), shown here:
String concat(String str)
This method creates a new object that contains the invoking string with the
contents of str appended to the end. concat( ) performs the same function as +. For
example,
puts the string "onetwo" into s2. It generates the same result as the following
sequence:
replace( )
The replace( ) method has two forms. The first replaces all occurrences of one
character in the invoking string with another character. It has the following general
form:
The second form of replace( ) replaces one character sequence with another. It
has this general form:
trim( )
The trim( ) method returns a copy of the invoking string from which any leading andtrailing whitespace
has been removed. It has this general form:
String trim( )
Here is an example:
The trim( ) method is quite useful when you process user commands. For example, the following
program prompts the user for the name of a state and then displays that state’s capital. It uses trim( ) to
remove any leading or trailing whitespace that may have inadvertently been entered by the user.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class UseTrim {
public static void main(String[] args)
throws IOException {
// create a BufferedReader using System.in
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("Enter 'stop' to quit.");
System.out.println("Enter State: ");
do {
str = br.readLine();
str = str.trim(); // remove whitespace
if (str.equals("Illinois"))
System.out.println("Capital is Springfield.");
else if (str.equals("Missouri"))
System.out.println("Capital is Jefferson City.");
else if (str.equals("California"))
System.out.println("Capital is Sacramento.");
else if (str.equals("Washington"))
System.out.println("Capital is Olympia.");
// ...
} while (!str.equals("stop"));
}
}
o/p
stop
The valueOf( ) method converts data from its internal format into a human-readable
form. It is a static method that is overloaded within String for all of Java’s built-in
types so that each type can be converted properly into a string. valueOf( ) is also
overloaded for type Object, so an object of any class type you create can also be
used as an argument. (Recall that Object is a superclass for all classes.) Here are a
few of its forms:
static String valueOf(double num)
static String valueOf(long num)
static String valueOf(Object ob)
static String valueOf(char chars[ ])
The String.valueOf() method in Java is a multipurpose static method. Its major function lies in the
conversion of types of data, such as primitive types and objects, into strings. The technique provides an
efficient and convenient way to construct string objects from different sources.
Java's valueOf() method is overloaded with numerous forms, each of that is designed to handle specific
data types. It can handle converting boolean, char, char array, double, float, int, long, and Object types
into their respective string representations.
With the help of valueOf(), developers can get back string representations of variables and objects
without the need to concatenate or modify strings directly. It simplifies the code and enhances
readability by offering a cleaner option instead of string conversion with the hands.package Strings;
The method toLowerCase( ) converts all the characters in a string from uppercase to lowercase. The
toUpperCase( ) method converts all the characters in a string from lowercase to uppercase.
String toLowerCase( )
String toUpperCase( )
Both methods return a String object that contains the uppercase or lowercase equivalent of the invoking
String. The default locale governs the conversion in both cases.
Here is an example that uses toLowerCase( ) and toUpperCase( ):
class ChangeCase {
public static void main(String[] args) {
String s = "This is a test.";
o/p
String joining
It is used to concatenate two or more strings, separating each string with a delimiter, such as a space or
a comma. It has two forms. Its first is shown here:
static String join(CharSequence delim, CharSequence ... strs)
Here, delim specifies the delimiter used to separate the character sequences specified by strs. Because
String implements the CharSequence interface, strs can be a list ofstrings. (See Chapter 18 for
information on CharSequence.) The following program demonstrates this version of join( ):
o/p
Alpha Beta Gamma
In the first call to join( ), a space is inserted between each string. In the second call, the delimiter is a
comma followed by a space. This illustrates that the delimiter need not be just a single character.
StringBuffer
StringBuffer supports a modifiable string. As you know, String represents fixed- length, immutable
character sequences. In contrast, StringBuffer represents growable and writable character sequences.
StringBuffer may have characters and substrings inserted in the middle or appended to the end.
StringBuffer will automatically grow to make room for such additions and often has more characters
preallocated than are actually needed, to allow room for growth.
StringBuffer Constructors
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
StringBuffer(CharSequence chars)
length( ) and capacity( )
The current length of a StringBuffer can be found via the length( ) method, while the total allocated
capacity can be found through the capacity( ) method. They have the following general forms:
int length( )
int capacity( )
Here is an example:
o/p
Since sb is initialized with the string "Hello" when it is created, its length is 5. Its capacity is 21
because room for 16 additional characters is automatically added.
ensureCapacity( )
If you want to preallocate room for a certain number of characters after a StringBuffer has been
constructed, you can use ensureCapacity( ) to set the size of the buffer. This is useful if you know in
advance that you will be appending a largenumber of small strings to a StringBuffer. ensureCapacity( )
has this general form:
void ensureCapacity(int minCapacity)
Here, minCapacity specifies the minimum size of the buffer. (A buffer larger than minCapacity may be
allocated for reasons of efficiency.)
setLength( )
To set the length of the string within a StringBuffer object, use setLength( ). Its general form is shown
here:
void setLength(int len)
Here, len specifies the length of the string. This value must be nonnegative.
When you increase the size of the string, null characters are added to the end. If you call setLength( )
with a value less than the current value returned by length( ), then the characters stored beyond the new
length will be lost. The setCharAtDemo sample program in the following section uses setLength( ) to
shorten a StringBuffer.
o/p
getChars( )
To copy a substring of a StringBuffer into an array, use the getChars( ) method. It has this general form:
GetChars( )
If you need to extract more than one character at a time, you can use the getChars( ) method
class getCharsDemo {
public static void main(String[] args) {
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char[] buf = new char[end - start];
append( )
The append( ) method concatenates the string representation of any other type of data to the end of the
invoking StringBuffer object. It has several overloaded versions. Here are a few of its forms:
The string representation of each parameter is obtained, often by calling String.valueOf( ). The result is
appended to the current StringBuffer object. The buffer itself is returned by each version of append( ).
This allows subsequent calls to be chained together, as shown in the following example:
// Demonstrate append().
class appendDemo {
public static void main(String[] args) {
String s;
int a = 42;
StringBuffer sb = new StringBuffer(40);
s = sb.append("a = ").append(a).append("!").toString();
System.out.println(s);
}
}
o/p
a=42!
insert( )
The insert( ) method inserts one string into another. It is overloaded to accept values of all the primitive
types, plus String S , Object S , and CharSequence S . Like append(), it obtains the string representation
of the value it is called with. This string is then inserted into the invoking StringBuffer object. These
are a few of its forms:
// Demonstrate insert().
class insertDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("I Java!");
o/p
I like Java!
reverse( )
You can reverse the characters within a StringBuffer object using reverse( ), shown here:
StringBuffer reverse( )
This method returns the reverse of the object on which it was called. The following program
demonstrates reverse( ):
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
o/p
abcdef
fedcba
sb.delete(4, 7);
System.out.println("After delete: " + sb);
sb.deleteCharAt(0);
System.out.println("After deleteCharAt: " + sb);
}
}
o/p
replace( )
You can replace one set of characters with another set inside a StringBuffer object by calling replace( ).
Its signature is shown here:
StringBuffer replace(int startIndex, int endIndex, String str)
The substring being replaced is specified by the indexes startIndex and endIndex. Thus, the substring at
startIndex through endIndex–1 is replaced. The replacement string is passed in str. The resulting
StringBuffer object is returned.
The following program demonstrates replace( ):
// Demonstrate replace()
class replaceDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("This is a test.");
sb.replace(5, 7, "was");
System.out.println("After replace: " + sb);
}
}
After replace: This was a test.
Substring( )
The first form returns the substring that starts at startIndex and runs to the end of the invoking
StringBuffer object. The second form returns the substring that starts at startIndex and runs through
endIndex–1. These methods work just like those defined for String that were described earlier
StringBuilder
StringBuilder is similar to StringBuffer except for one important difference: it is not synchronized,
which means that it is not thread-safe. The advantage of StringBuilder is faster performance. However,
in cases in which a mutable string will be accessed by multiple threads, and no external
synchronization is employed, you must use StringBuffer rather than StringBuilder.