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

Module 02 - Text

Uploaded by

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

Module 02 - Text

Uploaded by

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

Module 02

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.

• The String class provides a variety of constructors:


1) To create a String initialized by an array of characters,
• String(char[ ] chars)

Ex: char[] chars = {'a','b','c’};


String s = new String(chars);
• This initializes s with the characters abc
The String Constructors
2) You can specify a subrange of a character array as an initializer using the constructor:
• String(char[ ] chars, int startIndex, int numChars)

Here, startIndex 🡪 specifies the index at which the subrange begins, and
numChars 🡪 specifies the number of characters to use.

• Ex: char[] chars = {'a', 'b', 'c', 'd', 'e', 'f' };


String s = new String(chars, 2, 3);
• This initializes s with the characters cde.

3) You can construct a String object that contains the same character sequence as another
String object using this constructor:
• String(String strObj)

Here, strObj is a String object.


The String Constructors
Ex: // 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);
}
}
Output:
• Java
• Java
Here, s1 and s2 contain the same string.
The String Constructors
4) Java’s char type uses 16 bits to represent the basic Unicode character set,
• Because 8-bit ASCII strings are common on the Internet, the String class provides
constructors that initialize a string when given a byte array.
• Two forms are shown here:
• String(byte[ ] chrs)
• String(byte[ ] chrs, int startIndex, int numChars)

Here, chrs 🡪 specifies the array of bytes.


The second form allows you to specify a subrange.
• In each of these constructors, the byte-to-character conversion is done by using the
default character encoding of the platform.
The String Constructors
Ex:
String Length
• The length of a string is the number of characters that it contains.
• To obtain this value, call the length( ) method:
• int length( )
• Ex:
char[] chars = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());

• 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:

char[] chars = { 'a', 'b', 'c' };


String s1 = new String(chars);
(or)
String s2 = "abc"; // use string literal

• 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:

String s = "four: " + 2 + 2;


System.out.println(s);

• 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);

assigns the value b to ch.


Special String Operations
Character Extraction
getChars( )
• Used to extract more than one character at a time,
• It has this general form:
void getChars(int sourceStart, int sourceEnd, char[ ] target, int targetStart)

• 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.

• To perform a comparison that ignores case differences, call equalsIgnoreCase( ).


• Whenit compares two strings, it considers A-Z to be the same as a-z.
• It has this general form:
• boolean equalsIgnoreCase(String str)
String Comparison
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. Here are the
general forms for these two methods:

❑ boolean regionMatches(int startIndex, String str2,


int str2StartIndex, int numChars)
❑ boolean regionMatches(boolean ignoreCase,
int startIndex, String str2, int str2StartIndex, int numChars)

• 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:

• boolean startsWith(String str)


• boolean endsWith(String str)

• 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:

• If you want to ignore case differences:


String Comparison
compareTo( )
• Here is a sample program that sorts an array of strings.
• The program uses compareTo( ) to determine sort ordering for a bubble sort:
Searching Strings
• The String class provides two methods that allow you to search a string for a specified
character or substring:
indexOf( ) 🡪 Searches for the first occurrence of a character or substring.
lastIndexOf( ) 🡪 Searches for the last occurrence of a character or substring.
• These two methods are overloaded in several different ways.
• In all cases, the methods return the index at which the character or substring was found, or –1
on failure.
• To search for the first occurrence of a character 🡪 int indexOf(int ch)
• To search for the last occurrence of a character 🡪 int lastIndexOf(int ch)
• Here, ch is the character being sought.

• To search for the first or last occurrence of a substring:


int indexOf(String str)
int lastIndexOf(String str)
• Here, str specifies the substring.
Searching Strings
• You can specify a starting point for the search using these forms:
• int indexOf(int ch, int startIndex)
• int lastIndexOf(int ch, int startIndex)
• int indexOf(String str, int startIndex)
• int lastIndexOf(String str, int startIndex)
Here, startIndex specifies the index at which point the search begins.

• 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.

You might also like