Session 6
Session 6
TECHNOLOGY
AND PROGRAMMING
Strings
Strings
• Java implements strings as objects of type
String
• Java has methods to compare two strings,
search for a substring, concatenate two
strings, and change the case of letters within a
string.
The String Constructors
The String class supports several constructors. To create an
empty String, you call the default constructor. For example,
String s = new String();
will create an instance of String with no characters in it.
To create a String initialized by an array of characters, use the
constructor shown here:
String(char chars[ ])
Here is an example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
This constructor initializes s with the string “abc”
The String Constructors
You can specify a subrange of a character array as an initializer using the
following constructor:
String(char chars[ ], int startIndex, int numChars)
Here, startIndex specifies the index at which the subrange begins, and
numChars specifiesthe number of characters to use.
Here is an example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
This initializes s with the characters cde.
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.
Strings
String Literals
To create a String instance explicitly from an array of characters by using the
new operator
However, there is an easier way to do this 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
char chars[] = { 'a', 'b', 'c' };
String s1 = new String(chars);
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.
String Concatenation
Java does not allow operators to be applied to String objects
One exception to this rule is the + operator, which concatenates two strings,
producing a String object as the result.
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);
This displays the string “He is 9 years old.”
Use concatenation to prevent long lines
class ConCat {
public static void main(String args[]) {
String longStr = "This could have been " +
"a very long line that would have " +
"wrapped around. But string concatenation " +
"prevents this.";
System.out.println(longStr);
}}
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 sameas before.
This is because the int value in age is automatically converted into its string
representation within a String object
The compiler will convert an operand to its string equivalent whenever the
other operand of the + is an instance of String
String Concatenation
Be careful when you mix other types of operations with string concatenation
expressions,
You might get surprising results. Consider the following:
String s = "four: " + 2 + 2;
System.out.println(s);
This fragment displays
four: 22
rather than the
four: 4
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”.
Character Extraction
If you want to convert all the characters in a String object into a character
array, the easiestway is to call toCharArray( ).
general form:
char[ ] toCharArray( )
char[] ch=s1.toCharArray();
The String class includes several methods that compare strings or substrings
within strings
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.
Example:
int result = str1.compareTo( str2 );
System.out.println(result);
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.
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,
String s1 = "one";
String s2 = s1.concat("two");
puts the string “onetwo” into s2.
It generates the same result as the following sequence:
String s1 = "one";
String s2 = s1 + "two";
replace() & trim()
replace( )
The replace( ) method has two forms. The first replaces all occurrences of one character
in the invoking string with another character.
General form:
String replace(char original, char replacement)
trim( )
The trim( ) method returns a copy of the invoking string from which any leading and
trailing whitespace has been removed. It has this general form:
String trim( )
trim( )
String s = " Hello World ".trim();
This puts the string “Hello World” into s.
It uses trim( ) to remove any leading or trailing whitespace that may have
inadvertently been entered by the user.
Example:
String Str = new String(" Welcome to Tutorialspoint.com ");
System.out.print("Return Value :" ); System.out.println(Str.trim() );
Output:
Return Value :Welcome to Tutorialspoint.com