Module 02 - Text
Module 02 - Text
String Handling
Overview:
• In Java a string is a sequence of characters.
• But, unlike some other languages that implement strings as character arrays,
• Java implements strings as objects of type String.
• Strings are Immutable 🡪 once a String object has been created, you cannot change
the characters that comprise that string.
• How to make it mutable?
• Using StringBuffer and StringBuilder Classes in java.lang package
• Note: The contents of the String instance cannot be changed after it has been created but a variable
declared as a String reference can be changed to point at some other String object at any time.
The String Constructors
• The String class supports several constructors.
• To create an empty String, call the default constructor.
• String s = new String();
will create an instance of String with no characters in it.
Here, startIndex 🡪 specifies the index at which the subrange begins, and
numChars 🡪 specifies the number of characters to use.
3) You can construct a String object that contains the same character sequence as another
String object using this constructor:
• String(String strObj)
• The following fragment prints "3", since there are three characters in the string s.
Special String Operations
String Literals
• Instead of new operator, there is an easier way to create a String instance using a string
literal.
• For each string literal in your program, Java automatically constructs a String object.
• Thus, you can use a string literal to initialize a String object.
For ex: the following code fragment creates two equivalent strings:
• Because a String object is created for every string literal, you can use a string literal any
place you can use a String object.
ex: call the length( ) method on the string "abc".
System.out.println("abc".length());
o/p: it prints "3.
Special String Operations
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.
• For example, the following fragment concatenates three
strings:
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);
• o/p: He is 9 years old.
• One practical use of string concatenation is found when
you are creating very long strings.
• Instead of letting long strings wrap around within your
source code, you can break them into smaller pieces,
using the + to concatenate them.
Special String Operations
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:
int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s);
• 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.
Special String Operations
String Concatenation with Other Data Types
• Consider the following:
• This fragment displays four: 22 rather than the four: 4 that you probably expected.
• Here’s why?
• Operator precedence causes the concatenation of "four" with the string equivalent of 2 to take
place first. This result is then concatenated with the string equivalent of 2 a second time.
• To complete the integer addition first, you must use parentheses, like this:
String s = "four: " + (2 + 2);
• Now s contains the string "four: 4".
Special String Operations
String Conversion and toString( )
valueOf( ):
• The method valueOf( ) defined by String converts data into its string representation.
• valueOf( ) is overloaded for all the primitive types and for type Object.
• For the primitive types, valueOf( ) returns a string that contains the human-readable equivalent
of the value with which it is called.
• For objects, valueOf( ) calls the toString( ) method on the object.
toString( )
• Every class implements toString( ) because it is defined by Object.
• the default implementation of toString( ) is seldom sufficient.
• For most important classes that you create, you will want to override toString( ) and provide
your own string representations.
Special String Operations
String Conversion and toString( )
• The toString( ) method has this general form:
String toString( )
• To implement toString( ), simply return a
String object that contains the
human-readable string that appropriately
describes an object of your class.
• they can be used in print( ) and println( )
statements and in concatenation epressions.
• The following program demonstrates this by
overriding toString( ) for the Box class:
Special String Operations
Special String Operations
Character Extraction
charAt( )
• Use to extract a single character from a String.
• It has this general form:
char charAt(int where)
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.
• For example,
• char ch;
• ch = "abc".charAt(1);
• Here, sourceStart specifies the index of the beginning of the substring, and
• sourceEnd specifies an index that is one past the end of the desired substring.
• Thus, the substring contains the characters from sourceStart through sourceEnd–1.
• The array that will receive the characters is specified by target.
• The index within target at which the substring will be copied is passed in targetStart.
• Care must be taken to assure that the target array is large enough to hold the number of
characters in the specified substring.
Special String Operations
Special String Operations
Character Extraction
getBytes( )
• Stores the characters in an array of bytes.
• Uses the default character-to-byte conversions provided by the platform.
• Here is its simplest form:
byte[ ] getBytes( )
• getBytes( ) is most useful when you are exporting a String value into an environment that does not
support 16-bit Unicode characters.
toCharArray( )
• Converts all the characters in a String object into a character array.
• It returns an array of characters for the entire string.
• general form:
char[ ] toCharArray( )
String Comparison
The String class includes a number of methods that compare strings or substrings within strings.
equals( ) and equalsIgnoreCase( )
• To compare two strings for equality, use equals( ).
• It has this general form:
• boolean equals(Object str)
• Here, str is the String object being compared with the invoking String object.
• It returns true if the strings contain the same characters in the same order, and false otherwise.
• The comparison is case-sensitive.
• 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. Here are the
general forms for these two methods:
• startIndex specifies the index at which the region begins within the invoking String object.
• The String being compared is specified by str2.
• The index at which the comparison will start within str2 is specified by str2StartIndex.
• The length of the substring being compared is passed in numChars.
• In the second version, if ignoreCase is true, the case of the characters is ignored. Otherwise, case
is significant.
String Comparison
startsWith( ) and endsWith( )
• String defines two methods that are, more or less, specialized forms of regionMatches( ).
• startsWith( ) method determines whether a given String begins with a specified string.
• endsWith( ) determines whether the String in question ends with a specified string.
• They have the following general forms:
• Here, str is the String being tested. If the string matches, true is returned. Otherwise, false is
returned.
• For ex:
• "Foobar".endsWith("bar")
and
• "Foobar".startsWith("Foo")
are both true.
String Comparison
startsWith( ) and endsWith( )
• A second form of startsWith( ), shown here, lets you specify a starting point:
• boolean startsWith(String str, int startIndex)
• Here, startIndex specifies the index into the invoking string at which point the search will begin.
• For ex:
• "Foobar".startsWith("bar", 3)
returns true.
String Comparison
equals( ) Versus ==
• It is important to understand that the equals( ) method and the == operator perform two different
operations.
• equals( ) method compares the characters inside a String object.
• The == operator compares two object references to see whether they refer to the same instance.
// equals() vs ==
class EqualsNotEqualTo {
public static void main(String[] args)
{
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2)); Output:
Hello equals Hello -> true
} Hello == Hello -> false
}
String Comparison
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:
• For indexOf( ), the search runs from startIndex to the end of the string.
• For lastIndexOf( ), the search runs from startIndex to zero.
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, or use a String method that constructs a new copy of the string
with your modifications complete.
• A sampling of these methods are described here:
substring( )
• You can extract a substring using substring( ).
It has two forms:
• The first is
String substring(int startIndex)
• 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:
String substring(int startIndex, int endIndex)
• Here, startIndex specifies the beginning index, and endIndex specifies the stopping point.