M3-Advanced Java...
M3-Advanced Java...
String Handling
(Module 3 )
String(StringBuilder sbo)
• Supports the new StringBuilder class.
• This constructs a String from the StringBuilder passed in sbo.
The String Length
• The length of a string is the number of characters that it contains.
• Use int length( )
class stringlength
{
public static void main(String args[])
{
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
}
}
Special String Operations
1) The automatic creation of new string instances from string literals.
2) Concatenation of multiple String objects by use of the + operator.
3) The conversion of other data types to a string representation.
class ppp
{
public static void main(String args[])
{
char chars[] = {'a','b','c’};
String s1 = new String (chars);
String s2 = "abc"; OUTPUT:
System .out.println(s1); abc
System .out.println(s2); abc
3
System .out.println("abc".length());
}
}
The String Concatenation
• The + operator, which concatenates 2 strings, producing a
String object as the result.
class p
{
public static void main(String args[])
{
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);
}
}
OUTPUT
He is 9 years old
String Concatenation with Other Data Types:
• We can concatenate strings with other types of data. For example,
consider this slightly different version of the earlier example:
class concat
{
public static void main(String args[])
{
int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s);
}
} OUTPUT: He is 9 years old
Note: Here, 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.
Note: Be careful when you mix other types of operations with
string concatenation expressions,
class Example1
{
public static void main(String args[])
{
String s = "four: " + 2 + 2;
System.out.println(s); OUTPUT:
}
} four: 22
class Example2
{
public static void main(String args[])
{
OUTPUT:
String s = "four: " + (2 + 2);
four: 4
System.out.println(s);
}
}
String Conversion and toString( ):
class Box
{ double width, height, depth;
Box(double w, double h, double d)
{ width = w;
height = h;
depth = d;
}
public String toString()
{ return "Dimensions are " + width + " by " + depth + " by " + height + ".";
}
}
class example3
{ public static void main(String args[])
{ Box b = new Box(10, 12, 14);
String s = "Box b: " + b; // concatenate Box object
System.out.println(b); // convert Box to string
System.out.println(s);
}
}
CharacterExtraction
• The String class provides a number of ways in which characters can
be extracted from a String object.
• charAt( ): To extract a single character from a String, we can refer
directly to an individual character via the charAt( ) method.
char charAt(int where) //from which index to extract
• The value of where must be nonnegative and specify a location
within the string.
• charAt( ) returns the character at the specified location.
class p
{
public static void main(String args[])
{
char ch;
ch = "abc".charAt(1);
System.out.println(ch);
}
}
The getChars( )
• The getChars( ) method is used to extract more than one character at
a time.
void getChars(int where, int to, char target[], int targetstart)
• Here, where specifies the index of the beginning of the substring,
and to specifies an index that is one past the end of the desired
substring.
• 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.
• Always the target array is large enough to hold the number of
characters in the specified substring.
class getCharsDemo
{
public static void main(String args[])
{
String s = "This is a demo of the getChars method.";
int start = 10, end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}
OUTPUT:
demo
getBytes( )
• There is an alternative to getChars( ) that stores the characters in an
array of bytes.
• The getBytes( ) uses the default character-to-byte conversions
provided by the platform.
byte[ ] getBytes( )
• It is the most useful when we are exporting a String value into an
environment that does not support 16-bit Unicode characters.
• For example, most Internet protocols and text file formats use 8-bit
ASCII for all text interchange.
toCharArray( )
• The toCharArray( ) is used to convert all the characters in a String
object into a character array.
• It returns an array of characters for the entire string.
char[ ] toCharArray( )
String Comparison
• The String class includes several methods that compare strings or
substrings within strings.
equals( ) and
equalsIgnoreCase( )
• To compare two strings for equality, use equals( ).
Syntax: boolean equals(Object str)
• Here, str is the String object being compared with the invoking
String object.
• Returns: True, if the string contain the same characters in the same
order, otherwise False.
equalsIgnoreCase( ):
• To perform a comparison that ignores case differences, call
equalsIgnoreCase( ).
Syntax: boolean equalsIgnoreCase(String str)
class stringcompare
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " +s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " +s1.equals(s4));
System.out.println(s1+ " equalsIgnoreCase " + s4 + " -> "
+s1.equalsIgnoreCase(s4));
}
} Output:
Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true
The regionMatches( ):
• This method compares a specific region inside a string with another
specific region in another string.
• It has two methods:
public class regionmatching
{
public static void main(String args[])
{
String str1 = "Collection of tutorials";
String str2 = "Consists of different tutorials";
/* Matches characters from index 14 in str1 to characters from index 22 in str2
considering same case of the letters.*/
boolean match1 = str1.regionMatches(14, str2, 22, 9);
System.out.println("region matched = " + match1);
str2 = "Consists of different Tutorials";
match1 = str1.regionMatches(14, str2, 22, 9);
System.out.println("region matched = " + match1);
//considering different case, "true" is set which will ignore case when matched
str2 = "Consists of different Tutorials";
match1 = str1.regionMatches(true, 14, str2, 22, 9);
System.out.println("region matched = " + match1);
}
}
The startsWith( ) and endsWith( ) methods
• These are the specialized forms of regionMatches( ).
• startsWith( ), determines whether a given String begins with a
specified string.
• endsWith( ) determines whether the String in question ends with a
specified string.
boolean startsWith(String str)
boolean endsWith(String str)
• Here, str is the String being tested. If matches, true is returned.
Otherwise, false is returned.
"Foobar".endsWith("bar") and
"Foobar".startsWith("Foo") are both true.
• 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.
"Foobar".startsWith("bar", 3) returns true.
The equals( ) Versus ==
• The equals( ) method and the == operator perform two different operations.
• The equals( ) method compares the characters inside a String object.
• The == operator compares two object references refer to the same instance.
public class equals==
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1.equals(s2));
System.out.println((s1 == s2));
Output:
}
True
}
false
• The values of s1 and s2 are same. So s1.equals(s2) is true.
• The objects s1 and s2 are not referencing to same instance. So s1==s2 is false.
The compareTo( ) method
• This method is used to check which string is less than, equal to, or
greater than the next.
• It provides the following result which depends on the condition.
class replacechar
{
public static void main(String args[])
{
String s = "Hello".replace('l', 'w’);
System.out.println(s);
String s1 = "Hellommmmmmm".replace("mm", "nn");
System.out.println(s1);
OUTPUT:
}
Hewwo
}
Hellonnnnnnn
The trim( ):
• It returns a copy of the invoking string from which any leading and
trailing whitespace has been removed.
String trim( )
class trimstring
{
public static void main(String args[])
{
String s = " Hello World ";
System.out.println(s.length());
System.out.println(s);
String s1 = s.trim(); OUTPUT:
System.out.println(s1); 19
System.out.println(s1.length()); Hello World
} Hello World
} 11
Data Conversion using valueOf()
• The valueOf() method converts all the different types of values into
human readable string format.
• It has various overloaded forms:
static String valueOf(double num)
static String valueOf(long num)
static String valueOf(Object ob)
static String valueOf(char chars[ ])
public class dataconversion
{
public static void main(String args[])
{
int value=30;
String s1;
//s1=value; // error : incompatible types
s1=String.valueOf(value);
System.out.println(“Result 1: ”+ s1+10);//concatenating string with 10
char[] arr = {'a', 'b', 'c', 'd', 'e', 'f','g' };
//s1=arr; // error : incompatible types
s1=String.valueOf(arr);
System.out.println(“Result 2: ”+ s1);
}
}
OUTPUT:
Result 1: 40
Result 2: abcdefg
Changing the case of the characters within a String
• toLowerCase( ) converts all the characters in a string from
uppercase to lowercase.
• toUpperCase( ) method converts all the characters in a string from
lowercase to uppercase.
• Nonalphabetical characters, such as digits, are unaffected.
String toLowerCase( )
String toUpperCase( )
• Both methods return a String object that contains the uppercase or
lowercase equivalent of the invoking String.
class ChangeCase
{
public static void main(String args[])
{
String s = "This is a test.";
System.out.println("Original: " + s);
String upper = s.toUpperCase();
Changing the case of the characters within a String
String lower = s.toLowerCase();
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
}
}
OUTPUT:
Original: This is a test.
Uppercase: THIS IS A TEST.
Lowercase: this is a test.
ADDITIONAL STRING METHODS :
StringBuffer
It is a peer a class of String class.
Why StringBuffer?
1) The String class is used to manipulate character strings that cannot
be changed, objects of type String are read only and immutable.
2) The StringBuffer class is used to represent characters that can be
modified.
3) String represents fixed-length, immutable character sequences.
4) StringBuffer represents growable and writeable character
sequences.
5) StringBuffer may have characters and substrings inserted in the
middle or appended to the end.
6) Even String class is used more, StringBuffer is more
advantageous.
• StringBuffer defines four constructors:
• StringBuffer( ): The default constructor reserves room for 16
characters without reallocation
• StringBuffer(int size): It accepts an integer argument that explicitly
sets the size of the buffer.
• StringBuffer(String str): Accepts a String argument
• StringBuffer(CharSequence chars): Creates an object that contains
the character sequence contained in chars.
length( ) and capacity( )
• The length() is used to find the length of a StringBuffer.
• The capacity() is used to find the total allocated capacity. Additional
room will be automatically created for the string buffer object.
int length( )
int capacity( )
class lenghthandcapacity
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer(“Hello”);
System.out.println(“Buffer = " + sb);
System.out.println(“Length = " + sb.length());
OUTPUT:
System.out.println(“Capacity = " + sb.capacity());
Buffer = Hello
}
} Length = 5
Capacity = 21
ensureCapacity( )
• This method is used to preallocate room for a certain number of
characters after a StringBuffer has been constructed.
• The ensureCapacity( ) sets the size of the buffer.
• It is useful if we know in advance that we will be appending a large
number of small strings to a StringBuffer.
void ensureCapacity(int capacity)
• Here, capacity specifies the size of the buffer.
setLength( )
• The setLength( ) is used to set the length of the buffer within a
StringBuffer object.
void setLength(int len)
• Here, len specifies the length of the buffer. This value must be
nonnegative.
charAt( ) and setCharAt( )
• The charAt( ) is used to obtain the value of a single character from a
StringBuffer.
char charAt(int where)
• Here, where specifies the index of the character being obtained.
• The setCharAt( ) is used to set the value of a character within a
StringBuffer.
void setCharAt(int where, char ch)
• Here, where specifies the index of the character being set, and ch
specifies the new value of that character.
class setCharAtDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
System.out.println(“Buffer before = " + sb);
System.out.println(“The charAt(1) before = " + sb.charAt(1));
sb.setCharAt(1, 'i’);
sb.setLength(2);
System.out.println(“Buffer after = " + sb);
System.out.println(“The charAt(1) after = " + sb.charAt(1));
} OUTPUT:
} buffer before = Hello
charAt(1) before = e
Buffer after = Hi
The charAt(1) after = i
getChars( )
• The getChars( ) is used to copy a substring of a StringBuffer into an
array.
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
• Here, sourceStart - index of the beginning of the substring.
sourceEnd - index that is one past the end (end-1) of the desired
substring. target[] – receives the string. targetStart-starting index of
target.
class getchars
{
public static void main(String args[])
{
StringBuffer s=new StringBuffer("This is a GECK of the getChars method");
int start = 10, end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}
OUTPUT:
GECK
append( )
• It concatenates the string representation of any other type of data to
the end of the invoking StringBuffer object.
• It has several overloaded versions.
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
• String.valueOf( ) is called automatically for each parameter to obtain
its string representation.
class appendDemo
{ OUTPUT:
public static void main(String args[]) The value of a = 42!
{
int a = 42;
StringBuffer sb = new StringBuffer(“The value of ”);
String s = sb.append("a = ").append(a).append("!").toString();
System.out.println(s);
}
}
insert( )
• It inserts one string into another.
• It is overloaded to accept values of all the simple types, plus
Strings, Objects, and CharSequences.
• Like append( ), it calls String.valueOf( ) automatically to obtain
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:
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)
• Here, index specifies the index at which point the string will be
inserted into the invoking StringBuffer object.
class insertDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
}
}
OUTPUT:
I like Java!
reverse( )
• It is used to reverse the characters within a StringBuffer object:
StringBuffer reverse( )
class ReverseDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("abcdef");
System.out.println(sb);
sb.reverse();
System.out.println(sb);
}
}
OUTPUT:
abcdef
fedcba
delete( ) and deleteCharAt( ):
• The delete( ) deletes a sequence of characters from invoking object.
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
• Here, startIndex - index of the first character to remove. endIndex -
indexone past (end-1) the last character to remove.
• The deleteCharAt( ) deletes the character at index specified by loc.
class Delete
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("This is a test");
sb.delete(4, 7);
System.out.println("After delete: " + sb);
sb.deleteCharAt(5);
System.out.println("After deleteCharAt: " + sb); OUTPUT:
} After delete: This a test
} After deleteCharAt: This test
replace( ):
• It is used to replace one set of characters with another set inside a
StringBuffer object.
StringBuffer replace(int startIndex, int endIndex, String str)
• Here, startIndex and endIndex represents the substring being
replaced between. (end-1). The str - replacement string.
class p
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("This is a test.");
sb.replace(5, 7, "was"); //7 means upto 6 only
System.out.println("After replace: " + sb);
}
} OUTPUT:
After replace: This was a test.
substring( ):
• It is used to obtain a portion of a StringBuffer. It has 2 forms.
String substring(int startIndex)
String substring(int startIndex, int endIndex)
• First: Returns the substring that starts at startIndex and runs to the
end of the invoking StringBuffer object.
• Second: Returns the substring that starts at startIndex and runs
through endIndex–1.
• Note: These methods same as those defined for String class.
class Substring
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer(“KKGEC KRPET");
String sb1=sb.substring(2, 9);
System.out.println(sb1);
OUTPUT:
}
GEC KRP
}
• The lastIndexOf()
class IndexOfDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("one two one");
int i = sb.indexOf("one");
System.out.println("First index: " + i);
i = sb.lastIndexOf("one");
System.out.println("Last index: " + i);
}
}
OUTPUT:
First index: 0
Last index: 8
StringBuilder
• J2SE 5 adds a new string class to Java’s already powerful string
handling capabilities, which is called StringBuilder.
• It is identical 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 we are using multithreading, we
must use StringBuffer rather than StringBuilder.