String fforid1·
•~g
Leaming Scope
. M ti,ods of Stiing class Implementation of String
Stnng c1ass • e • I h c1ass rn
String toLower( ) String to Upper( ) • ml engt ( ). " char charAt(in;thOcl\.
int indexOf(char ch) • int lastlndexOf(~har ch) Stnng concat(Strin n)
boolean equals(String str) " mt compareTo(String str) g str)
• String replace(char old_char,char new_char) boolean startsWith(St .
~ boolean cndsWith(String str) • String valueOf(all types) String Buffer~ g st'.)
unctiont
You have already learnt about characters and different functions related to
. In th.1s chapter, we are gomg
. to discuss
.
handlino in Java programming. a b .charaq
. e•
t, . u1 1t-1n d
type that represents a set of characters as one umt, refers to as a Stnng. a~
String Class
Java Class Library (JCL) contains a class called
String which is available under java.lang package.
It allows the user to create an object or declare
· · 1111~
A string containing digits within
a variable to store a set of characters. Hence, a double quotes is treated as a
set of characters within double quotes is known symbol and hence can't be used
as a String. A string literal or string constant for any arithmetical calculation.
may consist of a set of only letters, a set of
alphanumeric characters or a set of only digits.
For example,
"COMPUTER", "UnDerSTanDing", "PAY2020", "6479", etc.
String Variable
String variable is a named memory location that contains a string constant or string
literal. The value of variable may change in the program. A variable declared with data
type String gains the capability of storing a set of characters.
::,,-. Assigning a String
A st ring can be assigned in two different ways as
follows:
I • 1111----
. · ·a1 value of{' 3
The default m1t1
"" I e
• Direct Assignment: In this method, a string string is represented ~s I dln~
double quotes witho~t inc u •
constant is directly assigned to a string variable.
any element within it).
Syntax:
<Strmg data type> <V· · bl . .
ana e> = <Stnng Literal>
260 I Understanding c .
omputer Applications with BlueJ-X
ding'';
/1', ,rst8fl ".
rl',1/1 ,(.)ndi; · js fun ,
r'\1 ~' ..,-,putcf · d str will ho ld "U ntlcrstantling" ·md '' C
/ii 1 ~t ,,CO"' . bles st an , • ornputcr is fun"
-l
~i,c. 11 ~
.,r ~ v,1r1a ,
. ~[(iflg; veyword: It a11ows. t he user. to assign. a st .
~ , ,111,; • , ,,ew ~·
.
· nng obJect
1t··-tivelY- l,Y r1s11tB . ble by
l~ e11f.,,er '.11tel·aJ/vafla I
a
;-
~ i''''
111 a stfl te"wof
d with the he P Constructor is a lunction
writte n w ith the same n or a method
i'' ~ ,1e11 .,.,ctof (I• 11·' ariable)).
, ·ill ' . " , .e . . amc a,; a cl
name and is used to initi alise the ob· ass
v•'\011S 1'.v Jjtera V ~eel.
ictflnh~ , (Stong , . . , . . .
,e> == new <construcl01 > <Stnng Iitcral/variahl .
J ~: obJect na 11 e>,
•intll c7 .(,
' . 11,1111
LJ:1'~ ,pfe, S •og("UNDERSTANDING" ); I
new' keyword is used
Jj
eiofl ew tn
ftir •n(l' str :::: 11 . object str is assigned with a lo allocate memory
. Slf1 " the Strlllg "
(i1 t J11eans ··UNDERSTANDING . dynamically for an
I literal FEST" object.
stri 11 g "COMPUTER ;
. st ::::
··) string ew String(st);
(11 . str :::: n •
5tfln,,
(1'
. biect str is assigned
str1ng o J
a Stn. ng " COMPUTER FEST" stored • t .
rn s n ng
Bere- the
~able st. . a data type creates a character array to store a set of char t .
1 fault, StrtJlo . . . . ac ers rn
BY de lls Thus, assigning a strmg ~eans ass1gnmg a character array to a String
oifferent ce · derstand with the followmg examples .
. t 1,et us un
~iec·
Example ,J:.-_ - - - - - - - - - - - - - - ,
public class Test
String st = "COMPUTER"·
I public static void main(String args[ ])
lclolMIPiulTIE.IR\
I Array of characters
char ch[ ] -- { 'C' ,'O' ,'M' , 'P' ,'U' , 'T' , 'E' , 'R' } ·,
String str = new String(ch);
System.out.println("The stored characters: +str; II )
l
I
Compilation and Execution:
-1) Bluel: Terminal W indow - Comp10 D X
~ Options
The stored characters: COMPUTER
r-- _ _ __
2!1 on l y ~ ~ -
ert er i npu~~ "'h 1 Ycur program is rt
•· le
String Handling I 261
, , the con•aructor String( ch) will allocate complete set of ch
Here;. . aracte
.t.e .. "CO~iPl.JTER") to the object str. rs of 'ch• ,
( ~rra}
Example 2:
, ~ublic class Test
! public static void main(String args[ ])
{
char ch[] = {'C','O','M','P','U','T','E','R'}:
String str = new String(ch,2,3);
System.ouLprintJn("The allocated characters: "+str):
l
Compilation and Execution:
.;J BlueJ: Terminal Window - Comp10 D X
Options
The allocated characters: MPU
Can only enter input while your progra::i ~s r,
In this example, the constructor String(ch,2,3) will allocate 3 characters from 200
index (i.e., "MPU") to the string object str.
262 I Understanding Computer Applications with BlueJ-X
~~ I
e taken as an input during execution of the
also b . . program. There
ing can •tring in Java programmmg. They arc discussed hclow:
a Str • ut a s
i or. s tO JO~ Scanner class) .
.1i,ir1 ,0t \va~ (t1Siflg ss, the followmg steps may be taken:
1' 1i~ft 5tJ'lllg anner CIa . .
i1 ~t 9 using Sc . . a rncrnber of java.utII package. Thus, lirst of all you need lo im
i 1~P put t1Y er c1ass _,s ur program as: port
J fl1 iO , 5cann kage in yo
I· . pac . *·
~eP till5 rtJ:l•
.
. ,,a utt 1• •
.
,,· 11pO or .
. tiJ.Scanner, .
ava.u . t of Scanner cIass m
.,,1n(1rt J
,,, r- an obJec
ate . ~ext( ) function allows user to
Z: Cre. tunctJOO. .
5teP fllaio( ) . _ new Scanner(System.m); mput a string as a single word
- . bl
scan oer in. to a string vana e: whereas, nextLine( ) accepts string
srnng as a text line.
. Joput a . t )·
51eP 3. . g st ::: ,n.nex ( ,
s~n t ::: in.nextLine( );
Stong s
array (using InputStreamReader cl~)
triDg to an .
!Jtput S . 10 . to an array, create a Stnng type array of required number of cells:
1DI . t stnng
fo 1npU
aample,
for [ l::: new String[lO];
. a str
51110~ 0 strings in the array as:
Jt stoit.S I .
. /\·j<I0;1++)
for(1::,,,,,
tr[i] :: in.next( );
s t input data using InputStreamReader class, take the following steps:
However, o
. InputStreamReader is a class of java.io package. Hence, first of all you need to
Step 1• import this package as: import
· · · *;
Java.10.
Step 2: Create objects of ~putStreamReader and BufferedReader classes simultaneously
under main( ) function as:
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
Step 3: Input the string to a string variable by using readLine( ) function.
String st = in.readLine( );
(c) Input a line (set of Strings) to an array
To input a set of strings, create a String type array of required number of cells:
For example,
Siring str[ l = new String[ 10];
Now, it will store IO different set of strings in the array as:
fo~i::Q;i<IO;i++)
str[i] = in.readLine( );
String Handling I 26.1
Oifferences between equals( ) and compareTo( )
equals( ) · . · comparcTo( >
. only c hecks whether two l. This function checks whether a string is
. ft1nct1on .cal or not.
'flJIS e idenll equal, bigger or smaller than other string
\. ·,.,rrs a.r or not.
stfl"t::>
. Boolean typ c value true/false.
su\ts 10
,,. \tre.
2. IL results 10 an integer type value.
. LL
A Glance
JlctioJ1S At Description
· .F<>rmat
,~g fl.1 ~etums t~e length of the characters present
a.length( );
m the stnng.
a = "Sunshine Vidyalaya";
a.length( );
Output: 18 (including one blank)
a.charAt(n); Re~ms a character of the string at nth position,
as 1t starts counting from 0 th position
a = "computer";
a.charAt(5);
Output: t (the character 't' is at 5 th position as
character 'c' is at 0 1h position)
a.roLowerCase( ); Converts all the characters of the string in
r nwercase( ) lowercase
jOµv
a="COMPUTER" ;
a.toLowerCase( );
Output: computer
a.toUpperCase( ); Converts al L the characters of the string m
toUpperCase( ) uppercase
a= "computer";
a.toUpperCase( );
O utput: COMPUTER
Replaces all the occurrences of the character
replace( ) a.replace('m', 'n');
'm' with 'n' in the string a.
a = "computer"
a.replace('m' ,'n');
Output: conputer
Replaces all the sub-strings 'black' with
replace( ) a.replace("black",
"white"); 'white' .
String a= ("black cat and black rat");
String p=a.replace("black", "white");
Output: white cat and white rat
equals( ) Checks whether two strings are equal or not.
a.equals( );
al = "Sunshine Vidyalaya";
a2 = "Sunshine Vidyalaya":
al.equals(a2);
Output: true
eqllalsI Returns true, if al and a2 are equal after
gnoreCase( ) al.equalslgnore ignoring cases of the strings and false, if they
Case(a2);
are unequal
al="Computer Application";
a2="COMPUTER APPLICATION";
al .equalslgnoreCase( a2);
Output: true
String Handling I 301
substring( ) a.substring(n): Returns the subst .
ring St
character of the strin ' cl11ing fro1n
a = " un derstanding"; g a. "'It'-
•ie r.
a.substring(5);
Output: standing (retu
. rns from th
the stnng as it starts . 5 Ch
counting f aracler
substring( ) a.substring(m.n): Returns a substring roni o1_ 01
.
Ieavmg , out of
the first m char n ch
" . acters of ar<teter
a = understanding"; the strin
a.substring(5, JO); 8·
Output: stand (returns 0
. Ut Of }Q
leaving first 5 characters f charac 1....
concat( ) o the Strin "'r1,
al.concat(a2); Concatenates (adds) al and a . g
2
al = "Sunshine"; Slnngs_
a2 = "Vidyalaya";
al .concat(a2);
Output: Sunshine Vidyalaya
indexOf() a.indexOf('m'); Returns the position of the first
'm' in the string a. occun-ence of
a="computer";
a.indexOf('m');
Output: 2 (The first occurrence of , , .
the 2 nd position) m 15 at
indexOf() a.i ndexOf('m', n); Returns the position of 'm' in the string fr
. . om
th e n th pos1t10n
a= "prime number";
a.indexOf('m',5);
Output: 8 (The next occurrence of 'm' in the
th
string from 5 position is at 8th location as
'p' is at 0 th position)
lastlndexOf( ) int n; This function returns 7 to the integer variable
String s = "MALAYALAM" n as the last index of occurrence of letter A
n=s.lastlndexOf('A'); is 7.
compareTo( ) al .cornpareTo(a2); Return s: a negative value, if al<a2; a positive
value, if al>a2 and zero, if al=a2
al="Computer Application";
a2="Computer Application";
al.compareTo(a2);
Output : 0
trim( ) a.trim( ); Removes all the white/blank spaces from the
beginning as well as the end of the string a.
a = " Sunshine Vidyalaya" ;
a.trim( );
Output: Sunshine Vidyalaya
302 I Unde rstanding Computer Applications with BlueJ- X
p.S·tartsWith(b) Returns true if the string p starts with the
specified String b.
p = "COMPUTER lS FUN";
b = "COMPUTER";
boolean x = p.startsWith(b)
Resu\t x = true
p .endsWith(b) R e turns true if the string p contains a suffix
specified by String b.
p = "COMPUTER IS FUN";
b = "FUN" ;
boolean x = p.endsWith(b)
Resu\t x = true