Professional Documents
Culture Documents
String
String
240 0
(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.
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") ,
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 .'
[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
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 <;<.;
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
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>.
System.out.println("LENGTH OF STRING") ;
/" #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
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
...... ...... ........ .......................................................... ..
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.
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.
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)
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,
-- 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""
Program 8.2
/*
* 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 {
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( ) ) ;