Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

COMPUTER ·\Prl ICM It )NS X

240 0

U'llt<.{4 CY' ' ~


8.2 Working with $tr ings ~
In Java, you can work "·ith ch,n,Wtl'r d,11,1, <'., single l h,1r,H"h'1 <H group nt I h,1r,11 tt>r I c, strm
in three different \\',n s. J,n ,l l,ttcrs 1111!'1' d,1Ssl'S In work. "ilh l h,ir,H tcr d.it,1.

(i) d,1,:; wlwsl' msl,ltll'l':- lH t1bjl'cts c.111 lwld single <h,ir,H tcr d,11,1. This cla
Clz111,1t'f1•1
offers m,1ny nwthl1ds h, manipulalt' t1r 11,s~,l'CI single-t h,1r,1cter d<1t,1.
(ii) Strrns c"1ss whost.' instances or objects c,m lwkl und1,1ngtng string (immutable -.tnng
i.e., m1ct' initialized its contents c,mnot be moditicd.
(iii) Stri11sB1,_tfcr d,1ss whose instances or objects can bold (mutable)
changed or modified.
\Ve are not going to discuss Ch11mctcr dass, which is a wrapper class.

8.3 C reating and Using String Objects


Strings in Java are created by declaring object of String type class and initializing it '-Vlth a
string literal e.g.,
St ring name= "I am a student" ;

You can also create String objects as you would any other Java object i.e., using nQw operator
with a constructor e.g.,
String yourname = new String( "I do not know your name") ,

To create empty string, just give :


String 91 = new String ( ) ;

The String type of Java is actually a class defined in java.lang package. It is a\·ailable bv
default as java.lang is available by default. String type has some specific features. su..::h as :
(i) It stores the sequence of character data in memory whicl1 are accessible b~· its name.
(ii) It offers many methods offering different functionality such as conc,1ten.1tiL-in L-it
string, comparison of string, find sub string etc.
(iii) Most importantly, String types are immutable (i.e., unchangeable). Th,1t 1s L-i111.:·e \ L-iu
have created a string type object and assigned some string v,1lue tL) it , l-iu c..1m1L)t
change it. -
Here, one thing you need to notice is that even if you assign a ne\\ , .1luL' tL) ::-t, 1'\ 1..-ibjc::'ct J.n .1
will not raise any error. That is, following code fragment will I1L)t r.1ise ,m erwr· ·
String sname = "Chintan ";
System.out.println(sname);
sname = "Rubal ; " • - - - - - - - - HF). 11·, /IIM ~"'" 1/i,11 S111 11 l\p, • b .. c ·'
System. out. println ( sname); 1•,i/111' c,111/IOI /,, l h,, 1i«I /11.1 /.11,1 r,r, rt«/
/IV l ,,,,, ! \\ 111 .'

The above code will produce output as :


Chintan
Rubal
Chapter 8 : STRING HANDLING
241
There is an explanation t . b .
Java d"d
1 h o ,\ ovcb'6ehnv1our
, of Java. lntcmally
not c angc the Strin O
ne tr· b" g Jcct 8 value rather it created a
o Jcct and n~1mcd il as sname (as explained in
f0 l; s. m~.tigure
owmg 8. l) is Immutable class,
means that once an
String sname = "Chintan" . object of its type is created,
snarne == "Rubal" J• ' we cannot change its content.

Java internally created


new string object with
new value ("Rubal")
sname and gave it the name
as sname

[String objects are immutable in Java i.e., their value cannot be changed in same memo .
every change creates a new object in memory.] String objects are Immutable ry'

Figure 8.1

8.4 Creating and Using StringBuffer Objects

StringBuffer is another class in Java (in java.lang) that lets you hold and process a sequence of
characters. Contrary to String objects, the StringBuffer objects are mutable, i.e., you can
change the contents of a StnngBuffer object at its own memory location just like you change the
values of primitive type variables.

StringBuffer objects are always created with new operator. But there are three ways in which
you can do so :
{z) StringBuffer sBuffer = new StringBuffer( ) ;
(ii) StringBuffer strBufferl = new StringBuffer("First") ;
(iii) int n = 15 ;
StringBuffer strBuffer2 = new StringBuffer(n) ;

.::=, The first method creates an empty StringBuffer object namely sBuffer .

.::=, The second method creates a StringBuffer object namely StrBuffer and initializes it with
string value "first".

> The third declaration statement creates the StringBuffer with an initial capacity equal to
n (=15 here) number of characters. It reserves memory to hold 15 characters in
StringBuffer object named strBuffer2. This ensures only one memory allocation for this
because it's just big enough to contain the characters that will be copied to it. By
initializing the string buffer's capacity to a reasonable first guess, you minimize the
number of times memory must be allocated for it. This makes your code more efficient
because memory allocation is a relatively expensive operation.
~~ s,~l•o~ 5J &uiod ~
242 ::;;() p(~ ~ < t )Ml'I If f f{ APPi 1r A I I< >t I'.., X

e>6
8.5 s1, 1nq Cle,~~ /\A0!11c 1ll'
f , t 111 , kr lC ,wr 1 ,1•, ti< 11' ,, or 1111'/ l11ul,
t\1f•lhthi"- \IQ1'd hi ,,ht,,m ml,111n,,t11111 ,1 I 1<!111 ,111 n I11<, < , ,·d ' to
111•rf11t111 opr•r,111<,11, ''" c,lrJ11;
1

String }'rt." 1dl''- """n' ,1,, 1._.,,,, 1111'1!1nrf., I I1,11 n 1,1y 1< 11 , ,
T,,hlc (l ,,bll' R 1) 11..,,., i-i lllH' ll lP'-1 ll '-I'd •H < ,,s..,01 11 H 'I IHid., of {;1 ri 11 g c l.i <;<.;

Table 8.1 Sa H? mo,t used n<<l'w11 method\ of fiflinq rlnss


Description
Ntthod prototype
f{!'1t
11
m th<' ch,1r,1rtcr ,it the ',pNif1r>rJ inrJP./.
~ , charAt (mt 111dcx)
Return\ mc1xim1Jrn no. of rh,trrH lr>r', thnt r;in l)p PnrP(er:J ,., ~h"
~ a pacity( ) rnrrent string object(this) i.P.., it', <np;irit·;.
1
Comp;:ires two strings lexirographiri:lll'J
J compareTo (String 1, anothc1Sl1 ing)

Compares two strings ignoring cr1ses of IPtt~r,.


~pareTolgnoreCase(String Strl , anotherString)
Concatenates the specified string to the end of this ~•, rg
/nng concat(String str) (current Stn'ng object) string.
Concatenation operator (i.e., + ), achieves same a-; concat
strl + str2
method.
Tests if the this string (current Stn'ng object) ends N1th ·"e
~lean endsWith (String str)
specified suffix (str).
Compares the this string (current String object) to ~ne
?lean equals (String str)
specified object str.

J>tr5lean equalslgnoreCase (String str) Compares the this string (current String object) ·o str
ignoring case considerations.

_...:sit index:Of(char ch) Returns the index2 within the this string (current St ng
object) of the first occurrence of the specified cha•acter

~ lastlndexOf (char ch) Returns the index within the this string of the last occJrrenc'-'
of the specified character.
Returns the length of the this string
~

r length()

replace (char oldChar, char newChar) Returns a new string resulting from replacing J~l OLCurre ct:s
of oldChar in the this string with newChar .
..,/_o 1-an startsWlth (String str) Tests tf the this string starts with the spcc1fieu ~ufrix S"tr)
fir · ~ .substring { nt beginlndex, int endlnde,,c) Returns a new string that is a substring ot the this st ,ny.
~ ring tol.owerCase ( ) Converts all of the characters i11 the this Str111g to lower i~e

Stnng toSbing ( ) Returns the string itselt .


..,,,..sfring toUpperC.ase ( ) Converts all of the character~ in Lhe this ',lnr,y tu uµµer 1.11 e
~ ng trim( ) Re111uves white !>~ldce from both end~ ut the this '.)tn11y.
~ g valueOf (all types) Returns string representation of the fJJ~~d Jryu111e11t e (J. 12
represented d!i "12"

There are many more and als o vanatH>llS · · on tlw method..., pn'M!ntl'd 111 I <1ble 8.1. Fullo\11 mg
( flA
..VV v,,'(J
:la~plA~p:rooJ:rr:aim..8.
~~ ~ ( M'\i
n 11 : ~
l:Wp'rl~J ,
1ll1~u..,tratPs Ow u ,av,•• , ,f nl 111 y <Jf ab t ti 1
rn ,~ m<' 10, ,.
Chup/e, 8 : STRING I 1/\NDI ING
243
ro~,.ra111 tel ifl1t~tratc , ,
11 11 11
It ~ s,· 11 11d /11111'/i,111 11 / 11'
class
11 ___Stringtx
_ { .11 °1 "'""Y St, 111,'\ 1111'1/1otlf>.

/ * unethod MEiHODs fallow .


Usin ,~
_
g va, ious Java functions */
PUblic. Void Test( )
{

String name1 - "\


. - U00S2\u0041\U004D\u0041\U004E"
String name2 = "ARORA" .
t J

S ring name 3 = "Vincent Roberts" .

~/ Sequence of method calls illus~rating string manipulation


engthOfString(name1).
'
c h arcaterAtlndexN(name1); I I #1
comparestrings(name1,name2); I I #2
concatinationl(namel,name 2 ); I I #3
concatination2 (namel,name2) I I #4
occurancesOfN(name3); I I #5
substring(name3) ; I I #6
replaceCharacter(name3) I I #7
caseConversion(namel); I I #8
} I I #9

I* #1 LENGTH Of STRING : Example method to illustrate use of length method *I


public static void lengthOfStr-ing(String name)
{

System.out.println("LENGTH OF STRING") ;

} System.out.println("Length of string"+ name+" is"+ name.length( )) ;

/" #2 CHARACTER AT INDEX N : Example method illustrating use of charAt method. *I


public static void charcaterAtindexN(String name)
{
System. out. println ( "\nCHARACTER AT INDEX N") ;
System.out.println("At 0 the character is"+ name.charAt(0))
System.out.princ.rn("At 3 the character is"+ name.charAt(3)) ;
}

/" #3 COMPARE STRINGS : Example method illustrating use of compareTo and equals methods *I
public static void compareStrings(String namel, String name2)
{
Systern.out.println("\nCOMPARE STRINGS") ;
/ / Using the compareTo method
system.out.println("Compare" + name1 +" and "-t name2 + " • " t namel.cQ!!lpareTo(name2)) ;
System.out.println{"Compare" + name2 +"and"+ namel + " =" + IW!e2.CQl!PilreTO(llillllll));
System.out.println("Compare" + name2 -t "and"+ name2 +" • " + llilll2.c~To(N!11112));
4 COMPUl [ R /\PPI IC A 1IONS X

System.out.print(namel- + "and"+ name2 +"are") ;


// Using the compareTo method within an if-else statement
if (namel. compareTo(name2) - 0)
System.out. println( "the same") ;
else
System. out. println ("not the same") ;
I I The equals method
System.out.println("Equ als" + name2 + "and"+ namel + "=" + name2.equals(name1) )
System.out.println("Equ als" + name2 +"and"+ name2 + "=" + name2.equals(name2) )
}

/* #4 CONCATENATION 1 : Example method illustring use of concat method*/


public static void concatinationl(String namel, String name2)
{
System. out. println ( "\nCONCATENATION 1") ,
namel = name 1. con cat (" ") ;
namel = namel. concat(name2) ;
System.out.println("nam el =" + namel) ,
}

/* #5 CONCATENATION 2 : Example method illustrating use of+ (concatenation)


operator. Same effect as above. */
public static void concatination2(String namel, String name2)
{ System.out.println("CONCA TENATION 2") ;
namel = namel + " " + name2 ;
System. out. println ( "namel =" + namel) ;
}

/* #6 OCCURANCES OF N : Example method illustrating use of indexOf and lastindexOf method */


public static void occurancesOfN(String name)
{
System. out. println ( "OCCURANCES OF n") ;
// Find first and last occurrences of 'n' in argument
System.out.println("First occurance of 'n' in"+ name+ "is at index"+ name.indexOf('n') );
System.out.println("Last occurance of 'n' in"+ name+ "is at index"+ name.lastindexOf('n') );
I I What happens if we are looking for the index of something
I I that does not exist in the given string ?
System.out.println("First occurance of 'Z' in"+ name+ "is at index"+ name.indexOf('Z') );
}

!* #7 SUBSTRINGS : Example method illustrating use of substring method */


public static void subString(String namel)
{
System.out.println("\nSU BSTRINGS");
/ / Substring from index 4 onwards
System.out.println("Subs tring from index 4 onwards ="+ namel.substring(4))
/ / Substring comprising all of input
Chapter 8 : STRING f IANDLING 245
String name2 = namel.substring(0,namel.length( )) ;
System.out. println( "Entire copy of" + namel + "=" + name2) ;
I I Substring from N to M
name2 = name 1. substring ( 0, 2) ;
System.out.println("Substring from index 0 to 2 =" + name2) ;
I I Substring made up of name2 from above ( first three charcaters
// of namel) plus substring from the first occurance of a space
I I (' ' ) in name 1 to three charcaters beyond it.
name2 = name2.concat(namel.substring(namel.index0f(' '),
namel. indexOf(' ') + 3)) ;
System. out. println ( "name2 =" + name2) ;
}

/*#8 REPLACE CHARACTER : Example method illustrating use of replace method */


public static void replaceCharacter(String name)
{
System. out. println ( "\nREPLACE CHARACTER")
I I Replace R and O with.
name= name.replace('R','.')
name= name.replace('O','.');
System. out. println ("name =" + name) ;
}

/* #9 CASE CONVERSION : Example method illustrating use of tolowercase


and toUpperCase methods */
public static void caseConversion(String namel)
{
System.out. println( "CASE CONVERSION")
/ / Upper to lower case conversion
namel = namel. toLowerCase( ) ;
System.out.println("namel =" + namel)
/ / Lower to upper case conversion
namel = namel. toUpperCase( ) ;
System.out.println("namel =" + namel)
/ / Substrings and case conversion
String name2 = namel. substring(0, 1)
string name3 = namel. substring(l, 5) ;
name2 ~ name2.concat(name3.tolowerCase( )) ;
System.out.println("name2 =" + narne2)
}

} //end of class StringEx


246 COMPUTER APPLICATION':> Z

The output produced by Tc~t( ) of above class is as foJlows:

LENGTH OF STRING
Length of stringRAMAN is 5
CHARACTER AT INDEX N
At O the character is R
At 3 the character is A
COMPARE STRINGS
Compare RAMAN and ARORA= 17
compare ARORA and RAMAN= - 17
Compare ARORA and ARORA= 0
RAMAN and ARORA are not the same
Equals ARORA and RAMAN= false
Equals ARORA and ARORA= true
CONCATENATION 1
namel = RAMAN ARORA
CONCATENATION2
namel = RAMAN ARORA
OCCURANCES OF n
First occurance of 'n' in Vincent Roberts is at index 2
Last occurance of 'n' in Vincent Roberts is at index 5
First occurance of 'z' in Vincent Roberts is at index - 1
SUBSTRINGS
substring from index 4 onwards= ent Roberts
Entire copy of Vincent Roberts= Vincent Roberts
substring from index O to 2 = vi
name2 = Vi Ro
REPLACE CHARACTER
name= Vincent .oberts
CASE CONVERSION
namel = raman
namel = RAMAN
name2 = Raman
...... ...... ........ .......................................................... ..

Let us briefly discuss what happened in above program :

1. The length method returns the length of the string i.e., the number of characters in the
string.
2 We used the charAt method to return the character value at a particular posibon.
3. When using the compareTo method, the method returns an integer indicating the
5t
lexicographic (alphabetic) location of the first letter of the first string with the fir
letter of the second string. If the first letters are both different, integer is returned
th
indicating the relative alphabetic location of the second start letter compared with e
Chopte, 8 · Sl RING I1.1\NDI IN(,
247
first, rH.'g,,tiYc it t h1..' s , , \ . , • •
18 1
If l 0 t\ . 'u nt1l l'Xll ogr,,phtr,,lly ,1ft1•t llw first ,111d positive otherwise
" . 'l Slnn~s .H°1..' id1..'n\k,1I llwn ,1 0 v,1lt1(' is rt'lurned. If both \i,ive th,, sc1me st;:ir~
l c t t1..'l "Ut ,1\'1..' nn\ tlw , 111 , , ti , . 1 2 ·
, nd . . s, l l 1 it 1 , 1 or 12 1s n•turiwd ,1n:ording to wh<·thl•r the
S\;'('o _,s k:tt\)f,l'<lphkally bl'forl' or ,iller the first. The compareTo method can thuc;
b1..' u~etully mcorporalt'd into sek,rtion slatenwnts (if-elst', switch).
4. AltenntiYe\y if :i.ll , . · t ~ · • .
' : • Wt: ,lie m eresteo m its direct comparison, we c,,n use the equals
method which returns a /100/cn11 value.

5. :'he_ concate1:ation method appends its argument (which must be a string) to the
m~1cat~d stnng and returns a 1ww i11sta11cc of tlie class String. In the example this new
strmg 1s also called namel thus overwriting the previous instance of that name.
l). The concatenation operator (+) can be used to produce the same result as the concat
method.

7. The indexOf and lastlndexOf methods find occurrences of a particular character


starting from the start or end of the string respectively, and return the index to that
character. If the occurrence cannot be found, the methods return -1. A variation on
the indexOf method includes a second argument to indicate a start index for the
search.

8. The subString method is used to create new instances of the class String from
existing instances. The new string is specified by giving the required index range
within the existing string (inclusive of the start index and exclusive of the end index).
If no upper bound is specified for the substring, Java assumes that this is the upper
bound of the given string. The method can also be used to create a copy of a string.
9. The replace method is used to replace each occurrence of the first argument in a
string with the second argument.

10. The toUpperCase and toLowerCase methods convert a given string to lower case or
uppercase characters respectively.

More about StringBuffer class

As you know that the StringBuffer class, which is part of java.lang p.:i.ckag~, is al_temL1tive to
the String class. A StringBuffer object contains a memory block called a l111ifer which ma.y not
contain a string. You have already learnt to create StringBuffer obiects. Let us now learn about
some more facts about StringBuffer class.
~ The length of the string may not be the same as the length of the buffer. (Fig. 8.2)

~ The length of the buffer is referred to as the capacity L)f the StringBuffer object.
~ You can change the length of a string in a StringBuffer object with the setlength( )
method.
~ When the StringBuffer object's length is longer th,m the string it holds, the extra
characters contain '\ u0000' ·
~ If you use the setLength( ) method to specify a length shorter than its String, the string is
truncated.
248 l ( 1 :\ \l'l 111 R \t 1f'll1 'II( IN I X

1 1111
I'~'''"'~' UIH h ,h•~ tlw dHh 1 1, 1 1H't' bd\\t't'I\ 11•111 th( ) 11,d 'I' H ih ( l •llu,d

I , lh\ ' O
( Ip 111\() II

t 1 1 1 1 1 \ I l If• tn I 1 Ill I 1

t
l\ 1 ,n (l II
I 1 l l I " I I I I I 1,I I I " I I
I I I I I I

I 1111At11t111 JIil( ) I)

1lllh I 11111,11111/ 111 '111111' r,l 1111q 111111 I 11111

OU
l su\C. ~trinp,Buttt't ,\bl'-, 1, l'"'' ,d,· ""'"' 1l,·\ll 1 11t1, lh,111 Stritt~ 11!,1,·l i,.; I 1·t HI ,,
,ln1,,,,...1i1.1 iw" ,,1nh·nt-.. 11 ,t,1 ., Sttin~Hnth•t \II tlw .,1 1,n ,. ►~•' ,·11 slrn1r, lrnh t111n..,
\\"1th ~trin~Ruftl•r ,·I.,:-, l h,,, ,,, ,,, tlwn' ,Ill' :--Pnh' .1dd1l11 u,,tl 11wll11 ,d-. th.ii ll I

Stnn,.~Buft~r , '1"1', t,

Let u, t;ilk zibout tlw~l' .,,td1tH1n,1l ~1ringlh1lkr ml'lh,,d:-- :

-- appe-ndb.:) mNhod. l l'I~ ,·,,u ,1dd , d1.1r,1d,·rs 1t1 tlw end ,,t .1 StrmbHuttL'r l jl'd

..... insert(offs"t, x) mt'tholi. Id~ y,ll1 ,1dd ., d1.1r,1d,•rs .11 .1 ,p,·, 111,·d I,,, .it11>n off~l't v thtr 1

StnngBuftt>r ol,Jt', I.
St'tCharAt(index, d nH•thod. t\11,•rs just ,Hw d1,H-.1d,•r II rq1l,1ll'..,, h.ir.1der lt 1111/i•l "'1t
c m n StnngButkr .
.... dele-tt"(beg, end) method. (),,Ides d1.1r,h.' ll'l's ,11 ind,·, l 1,·:,: th, u c·11cf
;:;: setLength(n) method. Sd:,. tlw l,•nglh lll tlw ui111l'11t fl, ,, h l'tllw1 trunt. ,tin~ lJII ·nt
ronh.>nt or t xtendmg 11 "1th tlw mill d1.i1 ,I\ ll'r (' \ ulltlllll ) enc.th((J) tl 1

stnngbufltr
r-evel'St'() method. R,,,t>1-..,':-. th,· l,,111l'nh ,,1 s1,11,gButll'1

An Ulh restmg aspt l I of Uw appl•nJ( ) ,llld inst•rt( ) 111\'thud-. ,.., th.1t tlw pM 11111;.•tcr 11'\J\ L' '
ml) f)pe 1111?St' nwtl1,>ds ,tll' o, ,,, hi.1d,•d .111d "di pt•1 tP1 n, tlu, dl.'t.iult ll•II\ 1.:r..,lllll 01 ill
pnnutnt: f)pts and \-\Ill ,,111 tlw toStringt) mdlHld 101 ,1111.,bfl'd""

Somt: String8uffer mt thods rf•tum a StdngHutfer \ ,1h1t· t, \; append() m:,~1t( ) 111 t td


the) return lht me StringBuffer th.it \\ .1s u,t•d 111 thl: l 111
'Ihis allow ,,,,, of c ill , ~

If x 1s 5 and } 1 2. tlw abo, l' lOdt: w 11! 1\ ult mto ), )


2SO COMPUTER APPLICATIONS- X

Program 8.2

Program to check whether a string is palindrome or not.

import java. io. * ;


public class Palindrome
{

/*
* Program execution starts here. The String. musteach
be surrounded in
word will be
* quotes, if it has any blank spaces. Otherwise,
* tested to see if it is a palindrome. */
public void PalindromeTest( ) throws IOException
{
/ I run sample tests
showPalindrome("mom")
showPalindrome("dad")
showPalindrome("radar")
showPalindrome( "Mom") ;
InputStreamReader isr = new InputStreamReader(System. in )
BufferedReader stdin = new BufferedReader(isr) ;
// Now ask the user to type a string and then test it
try {

System. out. println ( "\nEnter a string for palindrome test")


String input = stdin. read Line( ) ;
showPalindrome(input)
}
catch(Exception e){}
} / / end of method

/* Displays results of testin the S . .


public static void showP 1 · gd trin~ with each type of palindrome. */
{ a in rome ( String s)
System.out.print(s);
if(isPalindrome(s))
System. out. Println (". IS a 1·
e 1 self
· (isPalindrome2(s))
. · pa indrome 1. ")
System.out.println("·
1 · IS a Palindrom · f .
e se 1
• You ignore case! .. ) ;
System. out. print1n (" . Is N
} // end showPalindrome . OT a Palindrome!")

I* *'
Returns true if St .
public static boole ~1.ng of characters is a Palind
{ an 1.sPalindrome(st . rome. */
ring s)
StringBuffer rev
er~ed ::: (new St .
return s,equals(reversed t S ringBuffer(s)).reverse()
} / / end isPalindrome · 0 tr1ng( ) ) ;

You might also like