0% found this document useful (0 votes)
4 views9 pages

String Handling and Library Class Notes

The document provides an overview of strings in Java, detailing their creation, initialization, and various accessor methods. It explains the use of the String and StringBuffer classes, including syntax for creating and manipulating strings, as well as examples of string operations. Additionally, it includes code snippets for checking palindromes and sorting strings by length.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views9 pages

String Handling and Library Class Notes

The document provides an overview of strings in Java, detailing their creation, initialization, and various accessor methods. It explains the use of the String and StringBuffer classes, including syntax for creating and manipulating strings, as well as examples of string operations. Additionally, it includes code snippets for checking palindromes and sorting strings by length.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

C ITY MONTESSORI SCHOOL

SECTOR-D, LDA COLONY, KANPUR ROAD, LUCKNOW (INDIA)

STRINGS(ISC)
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 java.lang:
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 = br.readLine( ) ; // br is a BufferedReader object
String s = sc.next( ) ; // inputs a word - sc is a Scanner object
String s = sc.nextLine( ) ; // 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:

M e th o d F o rm a t D e s c rip tio n + E x a m p le

returns the number of characters in the string.


String a = "Work hard" ;
in t le n g th
(
)

System.out.println a.length ;
((

(
)
()

System.out.println "Java".length ;
)
)

returns the character from the ith position of a string.


c h a r ch a rA t in t i String a = "Application" ; char c = a.charAt 3 ;
(

)(
))

System.out.println "Computer".charAt 4 ;
(

returns the position for the first occurence of the


int indexOf int ch specified character c h .
(

String x = "Tomorrow" ; int p = x.indexOf 'o' ;


(

returns the position for the first occurence of the


int indexOf int ch,int i specified character c h from the specified position.
(

System.out.println "success".indexOf 's',1 ;


(

)
)

(51)
M e th o d F o rm a t D e s c r ip t io n + E x a m p le

re tu rn s th e p o s itio n fo r th e la s t o c c u re n ce o f th e s p e c ifie d
c h a ra c te r.
in t la s tI n d e x O f in t c h

)
S trin g y = " M is s is s ip p i" ;
S y s te m .o u t.p rin tln y .la s tI n d e x O f 's ' ;

)
)
re tu rn s th e s u b s trin g th a t b e g in s fro m th e n th in d e x .
S t r in g s u b s t r in g in t n S trin g x = " H a lfy e a rly " ;

)
S y s te m .o u t.p rin tln x .s u b s trin g 4 ;

(
)
)
re tu rn s th e s u b s trin g th a t b e g in s fro m th e n th c h a ra c te r u p to
S t r in g s u b s t r in g in t n , in t m m -1 th c h a ra c te r.
(

)
S y s te m .o u t.p rin tln " H e llo " .s u b strin g 0 ,4 ;

)
)
re tu rn s t r u e , if tw o s trin g o b je c ts a re e x a c tly s a m e , in c lu d -
b o o le a n e q u a ls S trin g s in g th e ir c a s e .
(

S y s te m .o u t.p rin tln " B lu e J " .e q u a ls " b lu e j" ;

)
)
s a m e a s a b o v e , b u t d iffe rin g o n ly in th e ir c a s e .
b o o le a n e q u a ls I g n o re C a s e S trin g s S trin g a = " R u n " ; S trin g b = " ru n " ;
(

S y s te m .o u t.p rin tln a .e q u a ls I g n o re C a s e b ;

)
)
c o m p a re s tw o s trin g s o f s a m e c a s e in d ic tio n a ry o rd e r.
s 1 .c o m p a re T o s 2 re tu rn s < 0 s 1 <s 2 ,> 0

)
in t c o m p a re T o S trin g o b j s 1 >s 2 ,0 s1=s2 .
(

)
S y s te m .o u t.p rin tln " lo c k " .c o m p a re T o " lo o k " ; // - 1 2

((

))
)
S y s te m .o u t.p rin tln " lo c " .c o m p a re T o " lo c k " ; // - 1

)
s a m e a s a b o v e , b u t ig n o re s th e c a s e o f th e le tte rs .
in t c o m p a re T o I g n o re C a s e S trin g
(

S trin g x = " A p titu d e " ; S trin g y = " a ttitu d e " ;


obj
)

S y s te m .o u t.p rin tln x .c o m p a re T o I g n o re C a s e y ;


(

)
)
re tu rn s a n e w s trin g a fte r re p la c in g a ll o c c u re n c e s o f th e
S trin g re p la c e c h a r o ld ,ch a r n e w o ld c h a ra c te r w ith th e n e w c h a ra c te r in a g iv e n s trin g .
(

S trin g x = " T ru c k " .re p la c e 'u ', 'a ' ;


(

)
re tu rn s a n e w s trin g a fte r re p la c in g a ll o c c u re n c e s o f a n o ld
s u b s trin g w ith th e n e w s u b strin g o f th e in v o k e d s trin g .
S trin g re p la c e S trin g o ld ,S trin g n e w
(

S trin g x = " Y o u a re g o o d w h e n y o u r a c tio n s a re g o o d " ;


S y s te m .o u t.p rin tln x .re p la ce " g o o d " , " b a d " ;
(

)
)
re tu rn s a n e w a fte r re m o v in g a n y le a d in g o r tra ilin g s p a c e s
S trin g trim fro m th e in v o k e d s trin g .
(
)

S trin g s = " C o m p u te r is F u n " .trim ;


(
)

re tu rn s a n e w s trin g a fte r jo in in g a g iv e n s trin g w ith th e


S trin g c o n c a t S trin g s s p e c ifie d s trin g . S trin g x = " A n n u a l" ;
(

S y s te m .o u t.p rin tln x .c o n c a t " E x a m " ;


(

)
)

re tu rn s a n e w s trin g a fte r c o n v e rtin g a ll lo w e r c a s e le tte rs


S trin g to U p p e rC a s e o f a g iv e n s trin g to u p p e r c a s e .
(
)

S y s te m .o u t.p rin tln " T e s t" .to U p p e rC a s e ;


(

(
)
)

re tu rn s a n e w s trin g a fte r c o n v e rtin g a ll u p p e r c a s e le tte rs


S trin g to L o w e rC a s e o f a g iv e n s trin g to lo w e r c a s e .
(
)

S y s te m .o u t.p rin tln " c o M p u T e r" .to L o w e rC a s e ;


(

(
)
)

re tu rn s a c h a ra c te r a rra y a fte r tra n s fe rrin g a ll c h a ra c te rs o f


a s trin g in to it. S trin g s = " J a v a C re a to r" ;
c h a r[ ] to C h a rA rra y
(
)

c h a r c h a [ ] = s .to C h a rA rra y ;
(
)

S y s te m .o u t.p rin tln c h a [0 ] = = s .c h a rA t 5 ;


(

)
)

re tu rn s a s trin g re p re s e n ta tio n o f th e a rg u m e n t w h ic h m a y
b e o f a n y p rim itiv e o r re fe re n c e d a ta ty p e .
in t iv = 4 ; d o u b le fv = 0 .5 ;
S t r in g v a lu e O f a rg
(

S trin g x = S trin g .v a lu e O f iv ; // " 4 "


((

))

S trin g y = S trin g .v a lu e O f fv ;
S y s te m .o u t.p rin tln x + y ; // " 4 0 . 5 "
(

(52)
Using ‘ + ’ operator:
For e.g.,
int m = 5 , n = 7 ;
System.out.println(m + n + “ = m+n”) ;
System.out.println(“m + n = “ + m + n) ;
System.out.println(“m + n = “ +(m + n)) ;
String x = “Con” ; String y = “cate” ;
System.out.println(x.concat(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” } ;
System.out.println(arr.length) ; // gives number of strings

Accession:
Each individual string can be accessed as:
System.out.println(mth[1]) ; // “Feb”
System.out.println(arr[2].length( )) ; // 5

Each individual character of a string can be accessed as:


System.out.println(mth[4].charAt(0)) ; // ‘M’
System.out.println(arr[0].charAt(0)) ; // ‘E’

// To check for a palindrome string


import java.util. ;
class Palin {
public static void main(String args[ ]) throws Exception {
int n, i ;
String str, revstr = “ ” ;
Scanner sc = new Scanner(System.in) ;
System.out.println(“String “) ;
str = sc.next( ) ; // string input
n = str.length( ) ;
for(i = n–1 ; i >= 0 ; i– –)
revstr = revstr + str.charAt(i) ;
if(str.equals(revstr))
System.out.println(“Palindrome”) ;
else System.out.println(“Not Palindrome”) ;
} }// end of main and class

// To print strings in increasing order of their lengths


import java.util. ;
class Arrange {
public static void main(String args[ ]) throws Exception
{
int i, j, m, n ;
String sa[ ] = new String[3] ; // String array
(53)
Scanner sc = new Scanner(System.in) ;
System.out.println(“Enter 3 words : “) ;
for(i = 0; i < 3 ; i++)
sa[ i ] = sc.next( ) ; // 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++)
System.out.println(sa[ i ]) ;
} // end of main
} // end of class

Using the StringBuffer class

S tr in g S trin g B u ffe r

It create s string s o f fixed leng th . It crea tes string s o f flexible le ng th .

T h e con te nts of the string can no t T h e c o n t e n t s o f t h e s t r i n g c a n b e


b e cha nged . ch ange d in bo th le ng th a nd co nten ts.

Creation (Syntax):
1) StringBuffer sb = new StringBuffer( ) ; // creates an empty string with default buffer size of 16 characters
2) StringBuffer sb = new StringBuffer(25) ; // creates an empty string with buffer size of 25 characters

Initialization:
1) StringBuffer sb = new StringBuffer(“June”) ; // creates a string “June” with buffer capacity of 20 characters
length of string + default buffer size)
2) StringBuffer x = sb ;
3) StringBuffer sb = new StringBuffer(sc.next( )) ;

StringBuffer Accessor Methods:


1. length( ) and capacity( ):-
i) int length( ) – returns the current length of a buffered string.
ii) int capacity( ) – returns the total allocated buffer space of a buffered string.
For e.g. StringBuffer x = new StringBuffer(“Hello”) ;
System.out.println(“Length = “+x.length( )) ; // 5
System.out.println(“Buffer = “+x.capacity( )) ; // 21

2. void setLength(int n) – sets the length of the string within a buffer to store n characters. For e.g.
(54)
StringBuffer sb = new StringBuffer(“Nightmare”) ;
sb.setLength(5) ;
System.out.println(“String = “+sb) ; // “Night”

3. void setCharAt(int i, char c) – replaces the character at the specified index with character c of a given buffered
string. For e.g.
StringBuffer sb = new StringBuffer(“match maker”) ;
sb.setCharAt(0, ‘c’) ;
sb.setCharAt(6, ‘t’) ;
System.out.println(“String = “+sb) ; // “catch taker”

4 StringBuffer reverse( ) – reverses the characters within a given buffered string. For e.g.
StringBuffer sb = new StringBuffer(“not war”) ;
sb.reverse( ) ;
System.out.println(“String = “+sb) ; // “raw ton”

5. StringBuffer append(String s) – adds a specified string at the end of the given buffered string. For e.g.
StringBuffer sb = new StringBuffer(“Nation”) ;
StringBuffer x = sb.append(“al”) ;
System.out.println(“String = “+x) ; // “National”

StringBuffer sb = new StringBuffer( ) ;


System.out.println(sb.append(“Novell “). append(“Netware” ));

6. StringBuffer insert(int i, char c) -


StringBuffer insert(int i, String s) – inserts a specified character or string at the ith position of a given buffered
string. For e.g.
StringBuffer sb = new StringBuffer(“Net System”) ;
System.out.println(sb.insert(3,” Security”)) ;

7. StringBuffer delete(int n, int m) – deletes a sequence of characters starting from the nth chr. upto (m–1)th
character of a given buffered string. For e.g.
StringBuffer sb = new StringBuffer(“Today”) ;
System.out.println(sb.delete(0, 2)) ; // “day”

8. StringBuffer deleteCharAt(int i) – deletes a character at the specified index of a given buffered string. For e.g.
StringBuffer sb = new StringBuffer(“sunday”) ;
System.out.println(sb.deleteCharAt(0)) ; // “unday”

9. StringBuffer replace(int n, int m, String s) – replaces a sequence of characters starting from the nth chr. upto
(m–1)th character of a given buffered string, with the specified string. For e.g.
StringBuffer sb = new StringBuffer(“This is a test”);
sb.replace(5,7,”was”) ;
System.out.println(sb) ; // “This was a test”

// To change the case of each character in a string


import java.util. ;
class Work {
public static void main(String args[ ]) throws Exception
{
int n, i ;
char c ;
StringBuffer sb ;
(55)
Scanner sc = new Scanner(System.in) ;
System.out.print(“String? “) ;
sb = new StringBuffer(sc.next( )) ; // string input
n = sb.length( ) ;
for(i = 0 ; i < n ; i++) {
c = sb.charAt(i) ;
if(c >= ‘A’ && c <= ‘Z’) c = (char) (c + 32) ;
else if(c >= ‘a’ && c <= ‘z’) c = (char) (c – 32) ;
sb.setCharAt(i, c) ;
} // end of for
System.out.println(sb) ;
} // end of main
} // end of class

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 java.util 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 java.util.* ;
class ParseText {
public static void main(String args[ ]) throws Exception {
Scanner sc = new Scanner(System.in) ;
StringTokenizer st ;
System.out.println(“Enter words separated by a comma and space”) ;
st = new StringTokenizer(sc . nextLine( ), “, “) ;
System.out.println(“No. of words : “ +st.countTokens( )) ;
while(st.hasMoreTokens( )) {
System.out.println(st.nextToken( )) ;
}
}} // end of class

The split( ) Method: It breaks or splits the invoked string into multiple string objects based on the given delimiter
pattern and returns the strings in the form of an array.
Syntax: String [ ] split (String expr)
Here, expr specifies a pattern of one or more delimiters like comma(“,“), semicolon(“;“), colon(“:“), or a period (“.”).

E.g.1: String str = "one-two-three" ;


(56)
String temp[ ] = str.split("-") ; // breaks the strings separated by -
for(int i = 0 ; i < temp.length ; i++) System.out.println(temp[i]) ;

E.g.2:
String str = "This is sentence. This is a question, right ? Yes! It is. " ;
String delims = "[ .,?!] + " ;
String temp[ ] = str.split(delims) ;
for(int i = 0 ; i < temp.length ; i++) System.out.println(temp[i]) ;

(57)
C ITY MONTESSORI SCHOOL
SECTOR-D, LDA COLONY, KANPUR ROAD, LUCKNOW (INDIA)

USING LIBRARY CLASSES(ISC)


Packages: A package is a group of logically related classes and interfaces of Java that are included in an application
program. Packages are of two types:
i) User defined package
ii) Pre defined packages (Java API) like java.io, java.util, java.lang, java.applet, etc.

The package statement in a program groups all the following classes into a user defined package. For e.g.
package MyPackage ;
The import statement makes a class or classes of a package available to the current program. For e.g.
import java. util . Scanner ;
import java . io. * ;

Streams: Java performs I/O through streams. Commonly used I/O streams present in java.io are:
i) System.in – object of InputStream for input purpose.
ii) System.out – object of OutputStream for printing purpose.
iii) System.err – object of OutputStream for error messages.

Pre – Defined Packages:


1) java . io package: It contains a large number of stream classes used to read and write data to a file or I/O devices.
Stream classes are of two types:
i) Byte Streams: They are used for byte-oriented I/O. For e.g. DataInputStream, DataOutputStream. They
can be used as: DataInputStream dis = new DataInputStream(System.in) ;
ii) Character Streams: They are used for character-oriented I/O For e.g. BufferedReader, BufferedWriter. They
can be used as: BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
where, br is any character stream object linked to the keyboard and InputStreamReader class converts bytes
to characters.

2) java.lang package: It is the default package which gets included at the start of any Java program. It stores the
basic functions of the language. Commonly used classes in java.lang are:

a) Wrapper Classes:
i) They are a collection of classes that provide a mechanism to "wrap" primitive types into an object . Java has
a wrapper class for each of the eight primitive data types:
Primitive type Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
The wrapper object can be created by instantiating the wrapper class with the new operator. For e.g.
Character c = new Character('T') ; // creates a Character object with intial value 'T'
Integer y = new Integer(33) ; // creates a Integer object with initial value 33
(58)
Common Wrapper methods:
a) Wrapper.valueOf( ): takes a value (or string) as an argument and returns a newly created wrapped object
of the class that invoked the method. For e.g.
Character c = Character.valueOf(‘c’) ; // assigns 'c' to the Character object c
Float f = Float.valueOf(“3.14f”); // assigns 3.14 to the Float object f
b) typeValue( ) - such as intValue( ), doubleValue( ), charValue( ), etc. Each one of them returns a primitive
type equal to value of the wrapper object. For e.g.
int x = 25 ; Integer y = new Integer(42) ;
System.out.println(x + y.intValue( )) ; // 67
System.out.println(y.doubleValue( )) ; // 42.0
c) parseType(String str) - such as parseInt( ), parseDouble( ), parseFloat( ), etc. Each of them returns a
primitive type equivalent of the number contained in the String argument. For e.g.
int x = Integer.parseInt("1234") ; // converts a string integer into an int
d) Wrapper.toString( ) - such as Integer.toString( ), Double.toString( ), etc. Each of them accepts a primitive
type argument and returns its equivalent String representation. For e.g.
String s = Integer.toString (1234) ; // converts an int into a String object "1234"
System.out.println(“d = “ + Double.toString(3.14)) ; // result is “d = 3.14”

ii) The Character class: provides methods to manipulate and process characters.
Method Description
Returns true, if ch is a letter, otherwise it
boolean isLetter(char ch)
returns false.
Returns true, if ch is a digit, otherwise it
boolean isDigit(char ch)
returns false.
Returns true, if ch is a letter or a digit,
boolean isLetterOrDigit(char ch)
otherwise it returns false.
Returns true, if ch is a lowercase letter,
boolean isLowerCase(char ch)
otherwise it returns false.
Returns true, if ch is a uppercase letter,
boolean isUpperCase(char ch)
otherwise it returns false.
Returns true, if ch is whitespace, other wise
boolean isWhitespace(char ch)
it returns false.
char toLowerCase(char ch) Returns lowercase equivalent of ch
char toUpperCase(char ch) Returns uppercase equivalent of ch

class abc {
public static void main( ) {
char ch[ ] = {‘R’, ‘0’, '\t'} ;
System.out.println (Character.isLetter(ch[0]) ;
System.out.println (Character.isDigit(ch[1]) ;
System.out.println (Character.isUpperCase(ch[0]) ;
System.out.println (Character.toLowerCase(ch[0]) ;
System.out.println (Character.isLetterOrDigit(‘?’) ;
System.out.println (Character.isWhitespace(ch[2]) ;
}
}
b) String and StringBuffer classes: used to represent Strings in Java.
3) java.util package: It is a collection of utility classes.
a. Date – To create and manipulate calendar dates in system independent fashion.
b. StringTokenizer – Converts a string of text into tokens or words.
c. Scanner – It is used for text input processing from a keyboard, a file or a String. For e.g.
Scanner sc = new Scanner(System.in) ; // sc is a Scanner class object
d. Random – Implements a random number generator.
(59)

You might also like