11
166 Prognmmingwith Java: A Pimer String fr,ll-Name String citYl where namel and name} are Java strings containing strin$ constants. Another example is: System.out.println (firstName + "Kumar") ; String Arrays We can also create and use arrays that contain strings. The s*"aicn^ent String itemArray[ ] : new String[3]; will create an itemArray of size 3 to hold three strin$ constants. We can assi$,n the strin$s to the itemArray element by element using three different statements or more efficiently usin$ a for loop. String Methods The String class defines a number of methods that allow us to accomplish a variety of strin$ manipulation tasks. Table 9.1 lists some of the most commonly used strin$ methods, and their tasks program 9.3 shows the use of the method compareTo( ) to sort an attay of strin$s in alphabetical order. Table 9.1 Some Most Commonly Used String Methods namel + name2; ttNew" + "De]-hi"; Method Call Task performed " Jv N* s2 : sl.tolowercasei s2 = sl.touppercase,' s2 : s1. replace ( 'x' , s2 : sl.trimO; s1.equals (s2) s1 . equalslgnoreCase ( s2 ) sl.lensth O . p&\, sr.cnarfut (nl eh s1 . con$areTo (s2) sl.concat(s2) s1 . substring (n) sl-. substring (n, m) "\t Strins y'rueof (n) p. tostring ( ) s1. indexOf ( 'x' ) sl.indexOf('X'rn) String.falueOf (Variable) Converts the string s1 to all lowercase Converts the string s1 to all Uppercase 'y') ; Replace allappearatces of xwithy Remove white spaces at the be$innin$ and end of the string s1 Returns 'true'if s1 is equal to s2 Returns 'true'if s1 = s2, i$norin$ the case of characters Gives the len$th of sl Gives nth character of s1 Returns negative ifsl< s2, positive if s1 > s2, and zero if sl is equal s2 Concatenates s1 and s2 Gives substring starting from n'h charactet Gives substring starting from n'h character up to m'h (not including m'h) Creates a string object of the parameter p (simple tlpe or object) Creates a string representation of the object p Gives the position of the first occurrence of'x' in the string, s1 Gives the position of 'x' that occurs after nth position in the string s1 Converts the parameter value to string representation ftan cllLass { 5t l t u ft mN fr 3!i &i GreT GI d

ftan · 2014-08-08 · Gives substring starting from n'h charactet Gives substring starting from n'h character up to m'h (not including m'h) Creates a string object of the parameter

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: ftan · 2014-08-08 · Gives substring starting from n'h charactet Gives substring starting from n'h character up to m'h (not including m'h) Creates a string object of the parameter

166 Prognmmingwith Java: A Pimer

String fr,ll-NameString citYl

where namel and name} are Java strings containing strin$ constants. Another example is:

System.out.println (firstName + "Kumar") ;

String Arrays

We can also create and use arrays that contain strings. The s*"aicn^ent

String itemArray[ ] : new String[3];

will create an itemArray of size 3 to hold three strin$ constants. We can assi$,n the strin$s to the

itemArray element by element using three different statements or more efficiently usin$ a for

loop.

String Methods

The String class defines a number of methods that allow us to accomplish a variety of strin$

manipulation tasks. Table 9.1 lists some of the most commonly used strin$ methods, and their

tasks program 9.3 shows the use of the method compareTo( ) to sort an attay of strin$s in

alphabetical order.

Table 9.1 Some Most Commonly Used String Methods

namel + name2;ttNew" + "De]-hi";

Method Call Task performed

" JvN*

s2 : sl.tolowercaseis2 = sl.touppercase,'s2 : s1. replace ( 'x' ,

s2 : sl.trimO;s1.equals (s2)

s1 . equalslgnoreCase ( s2 )

sl.lensth O . p&\,sr.cnarfut (nl ehs1 . con$areTo (s2)

sl.concat(s2)s1 . substring (n)

sl-. substring (n, m)

"\tStrins y'rueof (n)

p. tostring ( )

s1. indexOf ( 'x' )

sl.indexOf('X'rn)String.falueOf (Variable)

Converts the string s1 to all lowercase

Converts the string s1 to all Uppercase

'y') ; Replace allappearatces of xwithyRemove white spaces at the be$innin$ and end of the string s1

Returns 'true'if s1 is equal to s2

Returns 'true'if s1 = s2, i$norin$ the case of characters

Gives the len$th of slGives nth character of s1

Returns negative ifsl< s2, positive if s1 > s2, and

zero if sl is equal s2

Concatenates s1 and s2

Gives substring starting from n'h charactet

Gives substring starting from n'h character up to m'h

(not including m'h)

Creates a string object of the parameter p (simple tlpe or object)

Creates a string representation of the object p

Gives the position of the first occurrence of'x' in the string, s1

Gives the position of 'x' that occurs after nth position in the string s1

Converts the parameter value to string representation

ftancllLass

{5t

l

tu

ft

mN

fr

3!i&iGreT

GId

Page 2: ftan · 2014-08-08 · Gives substring starting from n'h charactet Gives substring starting from n'h character up to m'h (not including m'h) Creates a string object of the parameter

Amays, Sfnngsand I

Program 9-3

class StringOrdering{ '$ri^r- hmedabad"'

sLatic String name [ ] = {'.Madras,,, .rpg15i,,, .\A

..CaIcutta,r, "BombaY" ) ;

void main(String args[ ])public static{

int size =

String temP

for (int i{

name. Iength;= null;

= 0; i < size; i++;to thea for

of stringand theirtCrin$s in

object)

s1

for (int j = i+1i ) < siz€i j++)

' "<o)if (name Ij ] 'comPareTo (name Ii

{

/ / swaP the strin$stemP = namelil'name [i] = name [J ] inamelj] * temPi

)

)

)-for (int i = 0; i < size; i++)

iSYstem-out'Println (name til ) ;

)

Pro$ram 9.3 produces the followin$ sorted list:

AhmedabadBombaYCalcuttaDeIhiMadras : . i

StringBufrer Class

stringBufferisapeerclassofStrinc.whil:Stringcreatesstringsoffixed-length,stringBuffercreates strings ,f ft"r;;;;;,h it7,"u1n" *.a?*a in terms of both length and content' We

can insert "huru"t"rr'Lri;;";.*, in-the middle of a strin$' o' upp""d arnother strin$ to the

end. Table 9.2 lists ,#;;#;;'*E*r.a" tt ut u[ it"q"entlv used in string manipulations'

ltstrinf s1

Page 3: ftan · 2014-08-08 · Gives substring starting from n'h charactet Gives substring starting from n'h character up to m'h (not including m'h) Creates a string object of the parameter

16E Prognmmingwith Java: APiner

Table 9.2 Commonly Used StringBufrer Methods

Method Task

h*a)-t

/{ .0l

str-qs}'ste!

is1. setChartAt (n, 'x' )

s1 . append ( s2 )

s1. insert (n, s2)

s1 . setlength (n)

Modifies the nth character to x

Appends the string s2 to s1 at the end

Inserts the strin$ s2 at the position n of the strin$ s1

Sets the lenpth of the strin$ s1 to n' If n<s1'IengthO s1 is

truncated. If n>s1 . length ( ) zeros are added to s1

program 9.4 shows how some of the string methods are used for manipulating strings'

frogrom 9.4 MonrP"lrri"" "f

*Wclass StringManiPulation{

public static void main (String args I

{

StringBuffer str = new StringBufferSystem. out.println ("Origina1 String

/ / obtainin$ strin!! len$th

. System.out.println("Length of string ;" + str'lengthO );

/ / Accessin$ characters in a strin$

for (int i = 0; i < str.length0; i-++)

{

intP=i+1,svstlm'o"'-nll":'l';::::i::i:,li,f"""'"" : " t p *

)

/ / Insertin$ a strin$ in the middle

String aSLring : new String(str't'oStringO );int pos = asLring.indexOf(" language");str. insert (Pos, " Oriented ") ;System.out.printl-n("Modlfied string : " + str);

/ / ModifYin$ characters

str. setCharAL ( 6,'-') iSystem. out -prlntl-n ("String now i " I str) ;

l)

("object language") i:" + str)i

Outpiad

CriqrimLemqrthCharacCharacCharmCllaracCharacCharuClraracCharilCluruCharl(ChartCharaaCbaraChar-aCharanI{oCifistrim!ApP€mt

! r.!rr{fl--J

CandC+'be ueed usupport frthroughficreate a 6nr^rnher- tregt'greVa

rfr(Conthwed)

Page 4: ftan · 2014-08-08 · Gives substring starting from n'h charactet Gives substring starting from n'h character up to m'h (not including m'h) Creates a string object of the parameter

Anayq Stnngsand Veclors 169

Progam9.4 (Contimrcd)

/ / Appendin$ a strin$ at the end

str.apPend(" improves security"') ;

system. out.println ("Appended string a " I str);

t

i

i

Output of Pro$,ram 9.4 would be:

Original String : Oblect language

Length of st.ring : 15

Character at Position : 1 is 0

Character at Position : 2 is b

Character at Positlon : 3 is jCharacter at Position : 4 is e

Character at Position : 5 is c

Character at Position : 6 is tCharacter at Position : 7 isCharacter at Position : 8 is 1

Character at Position : 9 is a

Character at Position : 10 is n

CharacEgr at Position : 11 is g

Character at Position : 12 is u

Character at- Position : 13 is a

Character at Position : 14 is g

Character at Position : 15 is e

Modified string- : Object Oriented Ianguage

String now : Oblect-Oriented languaqe , r*.^Appended string : Object-Oriented language i-mproves security'

---9.6 VECTORSa-a

c and c + + programmers will know that generic utility functions with variable arguments can

be used to pass diff;; urc"*""ar a"p"r,ai"c ,po, the- callinf, situations' Java does not

support the corrcept of variable arguments ,o u i,.r""aion. This feature can be achieved in Java

through the use of the Vector classcontai"Ji" the java'util pa9!<age'This cLass can be used to

createa generic dynamic array known as-rs"cto, tLat can hold odects oi an'5t type and cuty

rumrber.The objects d";;; h;t" to be homogenous' Arrays can be easily implemented as

vectors. Vectors are created like arrays as follows:

Vector intVectVector list

: new Vector( ); // declatin$,withoutsize

new Vector (3) ; / / declarin$ with size

Page 5: ftan · 2014-08-08 · Gives substring starting from n'h charactet Gives substring starting from n'h character up to m'h (not including m'h) Creates a string object of the parameter

170 Prcgramming with Java: A Pimer

Note that a vector can be declared without specifying any size explicitly. A vector can

accommodate an unknown number of items. Even, when a size is specified, this can be

overlooked and a different number of items may be put into the vector. Remember, in contrast,ai array must always have its size specified.

Vectors possess a number of. advanta$es over arra)'s.

1. It is convenient to use vectors to store objects.

2. A vestor can be used to store a list of objects that may vary in size.

3. We can add and delete objects from the list as and when required.

A major constraint in usinf, vectors is that we cannot directly store simple data types in avector; we can onlystore objects. Therefore, we need to convert simple types to oblects. This can

be done using the c&raryer clssses discussed in the next section. The vector class supports anumber of methods that can be used to manipulate the vectors created. Important ones are

listed in Table 9.3.

Table 9.3 lmportant Vector Methods

Pr@tu.^Ii,sintStr1icsl'lfo,r{

Method Call Task performed

I ist . addElement ( it,em)list.elementAt (10)list. size ( )

List . removeElement ( item)Iist . removeElementAt (n)

Ij-st. removeAlfElements ( )

1ist. copylnto (array)list.insertElementAt (item, n)

Adde the item specified to the list at the end

Gives the name of the 10th objeatGives the number of objects present

Removes the specified item from the ltstRemoves the item stored in the nth position of the listRemoves all the elements in the listCopies all items from list to array

Inserts the item at nth Position

ComcC:!

r,n!rdslluc+m.In

--:/'gJ;trrf

Aspoimldouble- I!containolcorl€8pc

Program 9.5 illustrates the use of arrays, strin$s and vectors. This pro$ram converts a strin$vector into an array of. strings and displays the strings.

Program 9.5 Workingwithvecto?s and orrqfs

import ; ava. util . *;class LanguageVector{

/ / Importing Vector class

public static void main(String args[ ]){

Vector list = new Vector0;int length : args. length;for (inti:0; i<l-ength; i++){

l-ist.addElement (args til ) ;

(Contirwed)

Page 6: ftan · 2014-08-08 · Gives substring starting from n'h charactet Gives substring starting from n'h character up to m'h (not including m'h) Creates a string object of the parameter

Anays, Stningsand Vedors 171

Program 9.5 (Contitnrcd)can

be Iist . insertElementAt ( "CoBoL" ' 2 ) ;

int size : list. size O ;

String listArray[] = new StringIsizel;

list. coPYInto (IistArray) ;

System.out.prinLln ("List of Languages") i

for (int i = 0; i < size; i++1

{

System. out.println (IistArray Ii] ) ;

iinacan

aLfe

Command line inPut and outPut are:

C : \JAVA\Prog>j ava Languagevector

Llst of LanguagesAdaBASICCOBOL

C++FORTRANJava

WRAPPER CTASSES

Ada BASIC C++ FORTRAN Java

strinS

As pointed out earlier, vectors cannot handle primitive data tlpes like int' float' lon$' char' and

double. primitive data qpes may be converted into object types by usinf, the wrapper classes

contained in the java.iang package. Trbl; 9.4 shows thl simple data types and their

corresponding wrapper class types'

Table 9.4 Wrapper Ctasses for Converting Simple Types

Wrapper ClassSimple \Pe

booleanchardoublefloatintIong

BooleanCharacterDouble

FloatlntegerLong

Page 7: ftan · 2014-08-08 · Gives substring starting from n'h charactet Gives substring starting from n'h character up to m'h (not including m'h) Creates a string object of the parameter

W

li

l172 Programmingwith Java: A Pimer

The wrapper classes have anumber of unique methods for handling primitive data types and

ob.iects. They are listed in the followin$ tables'

Table 9.5 Converting Primitive Numberc to Obiect Numberc

Using Constructor Methods

Construetor Callin$ Conversion Action

Integer Intval : new Integer (i) ;

FloaL EloatVal = new Float (f) ;

Double DoubleVal : new oouble (d) ;

Long LongVal = new Long(l);

Primitive integer to Inte$er object

Primitive float to Float object

Primitive double to Double object

Primitive lon$ to Lon$ object

Note: i,f,d, and I are primitit:e.daia tsa,hrcs denotittg int, flaat, double dnd lane data' types'

fhey may be cott$:trts or va,riables'

Tableg.6ConvertingobjectNumberctoPrimitiveNumbersUsing tYPeValue( ) method

Method Calling Conversion Action

int i: IntVal.intVa1ue( );float f = EloatVal.ffoatValue( );Iong I = LongVal .Iongvatue(7)l'double d = DoubIeVaI.doubl'eVa1ue( );

Object to primitive integer

Object to primitive float

Object to primitive lon$

Object to primitive double

Table 9.7 Converting Numberc to Strings Using to String( ) Method

Conversion ActionMethod Callin$

str :str =

str =

str :

Integer . toStri-ng ( j- )

Eloat.toString(f);Double. toString (d) ;

Long.tostring (l) ;

Primitive

Primitive

PrimitivePrimitive

integer to string

float to stringdouble to string

lon$ to strin$

Table 9.8 Converting String obiects to Numeric obiects Using the static Method valueof( )

Method Callin$ Conversion Action

DoubleVaI

FloatvalIntVal :LongVal :

: Double.ValueOf (str) ;

= Eloat . Val-ueOf ( str ) ;

Integer. ValueOf (str) ;

Long.VaIueOf (str) ;

Converts string

Converts string

Converts string

Converts string

to Double object

to Float object

to Integer object

to Long object

Note: ?hese rnmeric obiects ma3t be ccmqoerted, to Wimitiae rrumbers usine the typeVahrc( )method qs shrxlrni/nTable 9.6.

TIMGft

int iIonq

Note: pcstls{rfu

Pro$,ro

Progrqn,l

import jrclass Im{

publit{

EUFLtidtrI

lc{

Page 8: ftan · 2014-08-08 · Gives substring starting from n'h charactet Gives substring starting from n'h character up to m'h (not including m'h) Creates a string object of the parameter

W

li

l172 Programmingwith Java: A Pimer

The wrapper classes have anumber of unique methods for handling primitive data types and

ob.iects. They are listed in the followin$ tables'

Table 9.5 Converting Primitive Numberc to Obiect Numberc

Using Constructor Methods

Construetor Callin$ Conversion Action

Integer Intval : new Integer (i) ;

FloaL EloatVal = new Float (f) ;

Double DoubleVal : new oouble (d) ;

Long LongVal = new Long(l);

Primitive integer to Inte$er object

Primitive float to Float object

Primitive double to Double object

Primitive lon$ to Lon$ object

Note: i,f,d, and I are primitit:e.daia tsa,hrcs denotittg int, flaat, double dnd lane data' types'

fhey may be cott$:trts or va,riables'

Tableg.6ConvertingobjectNumberctoPrimitiveNumbersUsing tYPeValue( ) method

Method Calling Conversion Action

int i: IntVal.intVa1ue( );float f = EloatVal.ffoatValue( );Iong I = LongVal .Iongvatue(7)l'double d = DoubIeVaI.doubl'eVa1ue( );

Object to primitive integer

Object to primitive float

Object to primitive lon$

Object to primitive double

Table 9.7 Converting Numberc to Strings Using to String( ) Method

Conversion ActionMethod Callin$

str :str =

str =

str :

Integer . toStri-ng ( j- )

Eloat.toString(f);Double. toString (d) ;

Long.tostring (l) ;

Primitive

Primitive

PrimitivePrimitive

integer to string

float to stringdouble to string

lon$ to strin$

Table 9.8 Converting String obiects to Numeric obiects Using the static Method valueof( )

Method Callin$ Conversion Action

DoubleVaI

FloatvalIntVal :LongVal :

: Double.ValueOf (str) ;

= Eloat . Val-ueOf ( str ) ;

Integer. ValueOf (str) ;

Long.VaIueOf (str) ;

Converts string

Converts string

Converts string

Converts string

to Double object

to Float object

to Integer object

to Long object

Note: ?hese rnmeric obiects ma3t be ccmqoerted, to Wimitiae rrumbers usine the typeVahrc( )method qs shrxlrni/nTable 9.6.

TIMGft

int iIonq

Note: pcstls{rfu

Pro$,ro

Progrqn,l

import jrclass Im{

publit{

EUFLtidtrI

lc{

Page 9: ftan · 2014-08-08 · Gives substring starting from n'h charactet Gives substring starting from n'h character up to m'h (not including m'h) Creates a string object of the parameter

r$

fopes ana

b

hi&

rh-r

f,rF

[i""t2.

Fet

[*rct

Ft

Amays, Sfrings aN Veturc

to Primitive Number.s Using Parsing Methods

173

l

Table 9.9 Converting Numeric Strings

Method Calling Conversion Aotion

intlong

Integer. parselnt ( str)Lonq.parselong (str) ;

Converts string to primitive integerConverts string to primitive long

t/

Note: pa,rselrt( ) ""d parsel,ong( ) metlads throro a NwnberFormatDxcqtion if the oahrc oJ the

str daes not revresent an hte$er.

Program 9.6 illustrates the use of some most commonly used wrapper class methods.

Progrom 9.6 Use of wrapper cross methods {.t*rycr't

import j ava. j-o. *;cl-ass InvesL{

public static void main(String args[ ]){

Float principalAmount = new Float (0) ;Fl-oat interestRate = new El-oat (0);int numYears ='0;try{' Datalnputstream in : new DatalnputStream(System.in)

System.out.print("Enter Principal Amount z "I iSystem. out. flush ( ) ;String principalString : in.readlineO ;principalAmount : Float. valueOf (principalstring) ;

System.ouL.print("Enter Interest Rate z ")iSyst.em. out. fl-ush ( ) ;String interestString : in.readline O ;interestRate = Float.va1ueOf (interestString) ;System.out.print("Enter Number of Years z "I;System. out . flush ( ) ;String yearsString = in.readlineO ;numYears = Integer.parselnt(yearsStritg) ;

Q#',

)

catch (IOException e){

Syst.em. out . printlnSystem.exit (1) ;

)

_t

(*I/o Error")

(Cottt*wed)

Page 10: ftan · 2014-08-08 · Gives substring starting from n'h charactet Gives substring starting from n'h character up to m'h (not including m'h) Creates a string object of the parameter

171 Pwnmningwith Java: A Pimer

ProProm 9.6 (Contirwed')

float val-ue : loan (principalAmount ' floatValue ( ) 'interestRate . floatValue ( ) , numYears ) ;

printline O ;System.out-printla("Einal Value = " * value)iprintline O ;

)

/ / Method to comPute Final Value

static float loan (f1oat p, floaL r' int n)

{

i-nt Year = 1;float sum : Piwhife (Year ': n)

{

sum = sum * (1+r);Year=Year+1;

)

return sumi

)

/ / Method to draw a line

static void Printline o{

for (int. i : 1; i <: 30; i++)t

System. out.PrinL ("=") i)

System.out.Println (" ") ;)

...r r t,iiPrW"'-aJ

In this cheafld vectm

o \Uh

clhlr ltrrr

o IIUr \\to IIocEo

\I-e hilprogrsil

REY'E;

9.1 I9.2 I9-3 I

iI

9-4 I

The output of Pro$ram 9.6 would be:

Enter PrinciPal Amount : 5000

EnLer Interest Rate : 0'15Enter Number of Years z 4

Final Value : 8745'03

Page 11: ftan · 2014-08-08 · Gives substring starting from n'h charactet Gives substring starting from n'h character up to m'h (not including m'h) Creates a string object of the parameter

Anayg Sfnngs and Vectors 175

J;,4:','':9.8: SUMMARYaJu

In this chapter, we ha'v'e discussed three important Java data structures namely arrays, strin$sand vectors. \\re learned the following:

o \l4rat is an array in Java

r How are a.rra1's 115gd

o I.Iow does Java handle stringsr How to use the String and StringBuffer classes

r What is a vector in Java

o [Iow to use vectors to store a list of objects that may vary in size

r How are wrapper classes useful

We have also seen some examples to illustrate v;here these structures can be used inprogramming.

9.4

REVIEW QUESTIONS

9.7 \!'hat is an array?

9.2 Why are arrays easier to use compared to a bunch of related variables?

9 .3 Write a statement to declare and instanti ate at array to hold marks obtained by studentsin different subjects in a class. Assume that there are up to 60 students in a class andthere are 8 subjects.

F'ind errors, if an-v, in the following code segment:

int m;int x[ ] : int[10];int [. ] y : int [11] ;

f or (m:1 ; m<:10 ; ++m)

x[m] : y[m] : m;

x:y:newint[20];f or (m:0,' m(10; ++m)

System. out.prlntln (x [m] )