Using Library Classes (Chap – 10)
Strings in Java
A string is a sequence of one or more characters enclosed in double quotes. In Java, strings
are class objects instantiated using two classes defined in [Link]:
1. String
2. StringBuffer
Using the String class
Creation (Syntax): String <stringName> = new String ( );
For e.g., String s = new String ( ); // creates an empty string
The string creation process can also be written individually as:
String s; // reference creation
s = new String ( ); // memory allocation
Initialization:
1. Using a String literal:
String s = new String (“May”);
String s = “May”;
String x = new String(s); // creates String x from String s
2. Using a Scanner / Inputstream object:
String s = [Link] ( ); // br is a BufferedReader object
String s = [Link] ( ); // inputs a word - sc is a Scanner object
String s = [Link] ( ); // inputs a text - sc is a Scanner object
3. Using a Character Array:
char chrs[ ] = { „S‟, „u‟, „n‟, „d‟, „a‟, „y‟ } ;
String s1 = new String (chrs);
String s2 = new String (chrs, 0, 3); // creates string “Sun”
String s3 = new String (chrs, 3, 3); // creates string “day”
String Accessor Methods:
Method Format Description + Example
Returns the number of characters in the string.
String a = "Work hard" ;
int length ( )
[Link]([Link]( ));
[Link]("Java".length( ));
Returns the character from the ith position of a string.
String a = "Application" ;
char charAt (int i)
char c = [Link] (3);
[Link]("Computer".charAt (4 ));
Returns the position for the first occurrence of the
int indexOf (int ch) specified character ch.
String x = "Tomorrow" ; int p = [Link] ('o');
returns the position for the first occurence of the
int indexOf (int ch, int i) specified character ch from the specified position.
[Link]("success".indexOf ('s',1 ));
Returns the position for the last occurrence of the
specified character.
int lastIndexOf (int ch)
String y = "Mississippi" ;
[Link]([Link]('s'));
Returns the substring that begins from the nth index.
String substring (int n) String x = "Halfyearly" ;
[Link]([Link](4));
Returns the substring that begins from the nth
String substring (int n, int m) character upto (m-1)th character.
[Link]("Hello".substring(0,4 ));
Returns true, if two string objects are exactly same,
boolean equals (String s) including their case.
[Link]("BlueJ".equals("bluej" ));
Same as above, but differing only in their case.
boolean equalsIgnoreCase (String s) String a = "Run" ; String b = "run" ;
[Link]([Link](b ));
Compares two strings of same case in dictionary
order. [Link] (s2) returns
int compareTo (String obj) < 0 (s1<s2), > 0 (s1>s2), 0 (s1=s2)
[Link]("lock".compareTo("look" )); // -12
[Link]("loc".compareTo("lock" )); // -1
Same as above, but ignores the case of the letters.
int compareToIgnoreCase (String obj) String x = "Aptitude" ; String y = "attitude" ;
[Link]([Link](y ));
Returns a new string after replacing all occurrences of
String replace(char old, char new)
the old character with the new character in a given
string.
String x = "Truck".replace('u', 'a' );
Returns a new string after replacing all occurrences of
an old substring with the new substring of the invoked
String replace (String old, String new) string.
String x = "You are good when your actions are good";
[Link] ([Link]("good", "bad" ));
Returns a new after removing any leading or trailing
String trim ( ) spaces from the invoked string.
String s = "" Computer is Fun "".trim( );
Returns a new string after joining a given string with
String concat (String s) the specified string. String x = "Annual" ;
[Link]([Link](" Exam"));
Returns a new string after converting all lower case
String toUpperCase ( ) letters of a given string to upper case.
[Link]("Test".toUpperCase( ));
Returns a new string after converting all upper case
String toLowerCase ( ) letters of a given string to lower case.
[Link]("coMpuTer".toLowerCase( ));
Returns a character array after transferring all
characters of a string into it.
char[ ] toCharArray ( ) String s = "Java Creator" ;
char cha[ ] = [Link]( );
[Link](cha[0] = = [Link] (5));
Returns a string representation of the argument which
may be of any primitive or reference data type.
int iv = 4 ; double fv = 0.5 ;
String valueOf (arg)
String x = [Link] (iv); // "4"
String y = [Link] (fv);
[Link](x + y ); // "40.5"
Using ‘+’ operator:
For e.g.,
int m = 5 , n = 7 ;
[Link](m + n + “ = m+n”) ;
[Link](“m + n = “ + m + n) ;
[Link](“m + n = “ +(m + n)) ;
[Link](“24” + „A‟) ; // 24A
[Link]('A' + „1‟ + 'C') ; // 181
String x = “Con” ; String y = “cate” ;
[Link]([Link](y) + “nation”) ; // "Concatenation"
String Array: A list of strings is a 1D array of strings.
Creation (Syntax): String arrayname [ ] = new String [size];
For e.g., String name [ ] = new String [3];
Initialization:
Syntax: String array-name [ ] = { “String1”, “String2”,…,”StringN” };
For e.g., String mth[ ] = { “Jan”, “Feb”, “Mar”, “Apr”, “May” } ;
String arr[ ] = { “East”, “West”, “North”, “South” } ;
[Link]([Link]) ; // gives number of strings
Accession:
Each individual string can be accessed as:
[Link](mth[1]) ; // “Feb”
[Link](arr[2].length( )) ; // 5
Each individual character of a string can be accessed as:
[Link](mth[4].charAt(0)) ; // „M‟
[Link](arr[0].charAt(0)) ; // „E‟
// To check for a palindrome string
import [Link].* ;
class Palin {
public static void main(String args[ ]) {
int n, i ;
String str, revstr = “”;
Scanner sc = new Scanner ([Link]);
[Link](“String ”) ;
str = [Link]( ) ; // string input
n = [Link]( ) ;
for (i = n–1 ; i >= 0 ; i– –)
revstr = revstr + [Link](i) ;
if ([Link](revstr))
[Link](“Palindrome”) ;
else [Link](“Not Palindrome”) ;
}
} // end of main and class
// To print strings in increasing order of their lengths
import [Link].* ;
class Arrange {
public static void main(String args[ ]) {
int i, j, m, n ;
String sa[ ] = new String[3] ; // String array
Scanner sc = new Scanner ([Link]);
[Link](“Enter 3 words : “) ;
for (i = 0; i < 3 ; i++)
sa[ i ] = [Link]( ) ; // input string array
// bubble sorting
for (i = 0 ; i < 2 ; i++) {
for (j = 0 ; j < 2 – i ; j++) {
m = sa[j].length ( );
n = sa[ j+1 ].length( ) ;
if (m > n) {
// swap strings
String t1 = sa[j]; String t2 = sa[ j+1] ;
sa[ j ] = t2 ;
sa[ j+1] = t1 ;
} // end of if
} // end of inner for loop
} // end of outer for loop
for(i = 0; i < 3 ; i++)
[Link](sa[ i ]) ;
} // end of main
} // end of class
String StringBuffer
It creates strings of fixed length. It creates strings of flexible length.
The contents of the string cannot T h e c o n te n ts o f th e s trin g c a n b e
be changed. changed in both length and contents.
Using the StringTokenizer class
The processing of text consists of parsing the text into a set of discrete parts or tokens.
A StringTokenizer breaks an input string into tokens using a delimiter pattern which by default is
a white space character (space, tab, newline etc.).
Syntax:
StringTokenizer stObj = new StringTokenizer (String str);
StringTokenizer stObj = new StringTokenizer (String str, String pattern);
Here, pattern specifies a set of one or more delimiters like comma(“ , “), semicolon(“ ; “), colon(“
: “), or a period (“.”).
The StringTokenizer class of [Link] package contains the following methods:
Method Description
nextToken( ) Returns the next token as a String.
hasMoreTokens( ) Returns true, if one or more tokens remain in the string, and false if there are none.
countTokens( ) Returns the number of tokens to be parsed, using the current set of delimiters.
// Parsing an input stream text into tokens
import [Link].* ;
class ParseText {
public static void main(String args[ ]) {
Scanner sc = new Scanner ([Link]) ;
StringTokenizer st ;
[Link](“Enter words separated by a comma and space”) ;
st = new StringTokenizer(sc . nextLine( ), “, “) ;
[Link](“No. of words : “ +[Link]( )) ;
while ([Link]( )) {
[Link]([Link]( )) ;
}
} // end of main
} // end of class