Module 3
Module 3
Module - 3
String Handling
• One of the most important of Java’s data type is String.
• constructor.
• For example,
• Frequently, you will want to create strings that have initial values.
String(char chars[ ])
• Here is an example:
class stringexample
char[] chars={'a','b','c','d','e','f','g','f','i','j'};
System.out.println(s);
class stringexample1
char chars[]={'a','b','c','d','e','f','g','f','i','j'};
System.out.println(s);
• You can construct a String object that contains the same character
sequence as another
String(String strObj)
class MakeString
System.out.println(s1);
System.out.println(s2);
}}
String(byte asciiChars[ ])
class SubStringCons
System.out.println(s1);
System.out.println(s2);
}}
ABCDEF
CDE
String Length
int length( )
• EX:
System.out.println(s.length()); //3
1.String Literals
• Because a String object is created for every string literal, you can use
a string literal any place you can use a String object.
System.out.println("abc".length());
2.String Concatenation
EX:
System.out.println(s);
• For example,
int age = 9;
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.
Example
class Sub
System.out.println(a);
System.out.println(b);
String toString( )
EX:
class Box
double width;
double height;
double depth;
width = w;
height = h;
depth = d;
}}
class toStringDemo
System.out.println(b);
System.out.println(s);
}}
Output
• D:\ec>javac toStringDemo.java
• D:\ec>java toStringDemo
Character Extraction
1.charAt():
EX:
class charat{
char ch;
ch = "rnsit".charAt(1);
System.out.println(ch);
}}
2.getChar():
• If you need to obtain more than one character at a time, you can
use the getChar() method.
class getCharsDemo
System.out.println(buf); }}
demo
3.toCharArray():
• char[] toCharArray()
• Ex:
class Chararray {
char[] chrs=str.toCharArray();
System.out.println(chrs);
4.getBytes( )
byte[ ] getBytes( )
• EX:
String s1="ABCDEFG";
byte[] barr=s1.getBytes();
for(int i=0;i<barr.length;i++)
System.out.print(barr[i]+ “ “);
OUTPUT
65 66 67 68 69 70 71
4.regionMatches()
5.compareTo() and compareToIgnoreCase()
System.out.println(str1.equals(str3));
System.out.println(str1.equalsIgnoreCase(str4));
}
}
Output
D:\ec>java Test
false
true
true
import java.io.*;
class mca311
{
public static void main(String args[])
{
String Str = new String("Welcome to rnsit");
iv. regionMatches():
• The regionMatches() method compares a subset of a string
with a subset of another string.
• The general form is,
• boolean regionMatches(int startIndex,String
str2,int str2StartIndex ,int numChrs);
• boolean regionMatches(boolean ignoreCase, int
startIndex,String str2,int str2StartIndex ,int numChrs);
• For both versions, startIndex specifies the index at which
the region to compare 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 region being compared is passed in
numChrs.
• The first version is case sensitive.
• In the second version, if ignoreCase is true, the case of the
Characters is ignored.
Ex:1
class CompareRegions
{
public static void main(String[] args)
{
String str1 = "rnsit in bangalore";
String str2 = "bangalore channasandra rnsit";
System.out.println(str1.regionMatches(0, str2, 23, 3));
}
}
Ex:2
class CompareRegions2
{
public static void main(String[] args)
{
String str1 = "rnsit in bangalore";
String str2 = "bangalore channasandra RNSit";
if(str1.regionMatches(true,0, str2, 23, 3))
System.out.println("Regions match");
else
System.out.println("Regions unmatch");
}
}
v. compareTo()
• The java string compareTo() method compares the given
string with current string lexicographically.
• It returns positive number, negative number or 0.
• It compares strings on the basis of Unicode value of each
character in the strings.
• if s1 > s2, it returns positive number
• if s1 < s2, it returns negative number
• if s1 == s2, it returns 0
EX:
public class Test26
{
public static void main(String args[])
{
String s1="hello";
String s2="hello";
String s3="meklo";
String s4="flag";
System.out.println(s1.compareTo(s2));
//0 because both are equal
System.out.println(s1.compareTo(s3));
//-5 because "h" is 5 times lower than "m"
System.out.println(s1.compareTo(s4));
//2 because "h" is 2 times greater than "f“
}
}
compareToIgnoreCase()
• This method compares two strings lexicographically,
ignoring case differences.
Example
public class Test25
{
public static void main(String args[])
{
String str1 = "rnsit";
String str2 = "Rnsit";
String str3 = "mca";
System.out.println(str1.compareToIgnoreCase( str2 ));
System.out.println(str2.compareToIgnoreCase( str3 ));
System.out.println(str3.compareToIgnoreCase( str1 ));
}
}
Searching Strings
• The String class provides two methods that allow you to
search a string for a specified character or substring:
indexOf( )
lastIndexOf( )
• indexOf( ) Searches for the first occurrence of a character
or substring.
• lastIndexOf( ) Searches for the last occurrence of a
character or substring.
Modifying a String
1.substring
• The substring() method returns a new string that contains a
specified portion of the invoking string.
• The form of substring() is
String substring(int startIndex)
String substring(int startIndex,int endIndex);
• Here, startIndex specifies the beginning index and
• endIndex specifies the stopping point.
2.concat
• The String concat() method concatenates the specified
string to the end of current string.
Ex:
class TestStringConcatenation3
{
public static void main(String args[])
{
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3); //SachinTendulkar
}
}
3.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:
String replace(char original, char replacement)
• The second form of replace( ) replaces one character
sequence with another.
• It has this general form:
String replace(CharSequence original, CharSequence
replacement)
EX:
public class Replace
{
public static void main(String[] args)
{
String str = "hello hai";
String rs = str.replace("h","s");
System.out.println(rs);
rs = rs.replace("s","h");
System.out.println(rs);
}
}
Example2
public class Replace2
{
public static void main(String args[])
{
String s1="mca mba ec java";
String replaceString=s1.replace("mba","puc");
System.out.println(replaceString);
}
}
sb.replace(3, 6, “JAVA");
System.out.println(sb);
}
}
4.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( )
Example
public class trim1
{
public static void main(String args[])
{
String s = " Hello World ".trim();
System.out.println(s);
}
}
EX:
class ChangeCase
{
public static void main(String args[])
{
String s = "This is a test.";
System.out.println("Original: " + s);
String upper = s.toUpperCase();
String lower = s.toLowerCase();
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
}
}
StringBuffer
• Java StringBuffer class is used to created mutable
(modifiable) string.
• The StringBuffer class in java is same as String class
except it is mutable i.e. it can be changed.
• A string that can be modified or changed is known as
mutable string.
• StringBuffer and StringBuilder classes are used for creating
mutable string.
• StringBuffer Constructors
• setLength
• The setLength(int newLength) method of StringBuffer
class is the inbuilt method used to set the length of the
character sequence equal to newLength.
• If the newLength passed as argument is less than the old
length, the old length is changed to the newLength.
class GFG2
{
public static void main(String[] args)
{
StringBuffer str = new StringBuffer("Welcome to rnsit");
System.out.println("String length = " + str.length() + " and
contains = " + str);
str.setLength(12);
System.out.println("After setLength() String = "+
str.toString());
}
}
append( ):
• the append() method of StringBuilder class is used to add
data to the end of an existing StringBuilder object.
EX:
class append10
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints HelloJava
}
}
insert( ):
• The insert() method inserts the given string with this string
at the given position.
EX:
class insert10
{
public static void main(String args[])
{
reverse()
• The reverse() method of StringBuilder class reverses the
current string.
EX:
public class reverse10
{
public static void main(String args[])
{
StringBuffer sbf = new StringBuffer("RNSIT");
System.out.println("String buffer = " + sbf);
sbf.reverse();
System.out.println("String buffer after reversing = " + sbf);
}
}
delete() Method
• The delete() method of StringBuffer class deletes the string
from the specified beginIndex to endIndex.
public class delete10
{
deleteCharAt()
• method removes the char at the specified position in this
sequence.
public class delete11
{
public static void main(String[] args)
{
StringBuffer buff = new StringBuffer("Java lang");
System.out.println("buffer = " + buff);
buff.deleteCharAt(2);
System.out.println("After deletion = " + buff);
}
}
substring( )
• In StringBuffer class, there are two types of substring
method depending upon the parameters passed to it.
• The substring(int start) method of StringBuffer class is
the inbuilt method used to return a substring start from
index start and extends to end of this sequence.
• The string returned by this method contains all character
from index start to end of the old sequence.
• The substring(int start, int end) method of StringBuffer
class is the inbuilt method used to return a substring start
from index start and extends to the index end-1 of this
sequence.
Example
class substring
{
public static void main(String[] args)
{
StringBuffer str= new StringBuffer("bangalorernsit");
System.out.println("String contains = " + str);
System.out.println("SubSequence = " + str.substring(5));
System.out.println("SubSequence = " + str.substring(5, 8));
}
}
StringBuilder
• Java StringBuilder class is used to create mutable
(modifiable) string.
• The Java StringBuilder class is same as StringBuffer class
except that it is non-synchronized,which means that it is
not thread-safe.
• The advantage of StringBuilder is faster performance.
• However, in cases in which you are using multithreading,
you must use StringBuffer rather than StringBuilder.
• . It is available since JDK 1.5.
Ex:
• stringbuffer methods