String
String
CHAPTER 9:STRINGS
1. Using string literal - A new string object is created by using double quotation marks like
2. U singthenewkeyword,i.e.,usingtheStringclassconstructor-Anewstringobjectiscreatedbyusingthe
Stringclassconstructors.Thereare13constructorsintheStringclasswhichcanbeusedtocreateastring
object. The most common ones are
Using the new keyword creates a new String object each time in the heap memory.
Let’s write these 4 lines of code and see how the string objects are stored in the diagram below.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new
Scanner(System.in);
String user_input = sc.nextLine();
System.out.println(user_input);
}
}
Notice that we used sc.nextLine() totakeastringinputbecausenextLine()takestheinputuntilanewlineis
e ncountered i.e. a \n is encountered.
The output of the above code is 11 since there are 11 characters in str5 including the spaces.
inde 0 1 2 3 4 5 6 7 8 9 1
11 1
1
1
1
1
1
x 0 2 3 4 5 6 7
P r o g r a m m i n g i s f u n
It can be seen that the first element can be found in index=0 and the last element can be found in index=
length-1.
I nordertoaccessaparticularelementfromthestring,wecanusethemethodcharAt().Thismethodtakesan
indexnumberasanargumentandreturnstheparticularelementinthatposition.Let’sextractthecharacters‘P’
at index=0, ‘n’ at index=17 and ‘g’ at index 10.
Page|47
9.7 MU
TABILITY OF STRINGS
I ntheprevioussection9.3,wesawhowwecanaccesstheelementsinastring.However,wecannotmodifya
stringbecauseinJava,stringsareimmutable.Thismeansthatwecannotmodifytheelementswhichmakeup
the string. If we want to modify a string then a new string needs to be created which would contain the
modifications, leaving the original string unchanged.
he output of the above code is:I love Java programmingvery much. The output is a new string which is stored
T
in s3. Let’s see another example:
tring s1 = “CSE”;
S
int num = 110;
String output = s1 + num
System.out.println(output)
;
ere,theoutputis:Fall2023.Notehowoperatorprecedencecausestheconcatenationofthestring“Fall”tothe
H
integer20atfirstwhichcreatesthestring“Fall20”andthenthisstringisconcatenatedtotheinteger23which
creates the output string “Fall2023”.
adwewritten:Stringoutput=y1+23+semester,thentheoperatorprecedencewouldcausetheintegerin
H
y1andtheinteger23tobeaddedusingthe+operatortoproduceaninteger43andthenthisintegerwouldbe
concatenated to the string “Fall” to produce a string “43Fall”. Try this out yourself.
Here,theoutputofthefirstprintstatementisfalsesincetheelementsofs1ands2areidenticalandtheoutputof
the second print statement istruesince the elementsof s1 and s3 are identical.
Note: equals() method is case sensitive and so the strings “Let us code” and “LetusCode”willyieldfalse.
owever, another methodequalsIgnoreCase()will ignorethe case differences and will yield true.
H
● = = operator - The == operator in Java checks whether two string objects have the same
reference/location or not. Let us see an example:
● c ompareTo() - This method compares two strings lexicographically. It returns 0 if both strings are
equal with identical characters in the samepositions.Itreturnsapositiveintegerifthefirststringis
lexicographically greater than the second string and it returns a negative integerifthefirststringis
lexicographically smaller than the second string. Let’s see a few examples.
Page|49
tring s1 = “Java”;
S
String s2 = “Java”;
String s3 = “Jade”;
String s4 = “Lava”;
System.out.println(s1.compareTo(s2))
;
System.out.println(s1.compareTo(s3))
;
System.out.println(s1.compareTo(s4))
;
Thefirstoutputis0sinceboths1ands2areidentical.Thesecondoutputis18since“v”is18morethan“d”
lexicographically. The third output is -2 since “J” is 2 less than “L” lexicographically.
● indexOf()-Thismethodtakesacharacter/substringasanargumentandfindsthepositionofthefirst
occurrence of the character/substring in the string.
● lastIndexOf() - This methodtakesacharacter/substringasanargumentandfindsthepositionofthe
last occurrence of the character/substring in the string.
he output of the first print statement is Programming is fun andtheoutputofthesecondprintstatementis
T
program. Notice that the end_index is exclusive which means the substring will stopattheindexbeforethe
end_indexand not include the character at theend_indexitself.
9.12 MO
DIFYING A STRING
Page|50
tring s1 = “marathon”;
S
String new_s1 = s1.replace(“a”, “e”);
String new_s2 = s1.replace(“mara”,
“py”);
System.out.println(new_s1);
System.out.println(new_s2);
heoutputofthefirstprintstatementismerethon.Wecanseethatalltheoccurrencesof“a”havebeenreplaced
T
by “e”. The output of the second print statement is python. We can see that the substring “mara” has been
replaced by the substring “py”.
The output of the above code isJavawithout the whitespaces before and after the word “Java”.
tring s2 = "Java,is,,fun";
S
String [] s2_array =
s2.split(“,”);
● toLowerCase() - This method converts all uppercase letters to lowercase in a string and returns a new
modified string.
● toUpperCase() - This method converts all lowercase letters to uppercase in a string and returns a new
modified string.
System.out.println(upper_s2);
The output of the above code isI LOVE TO CODEwhereall characters are presented in uppercase.
tring s1 = String.valueOf(digit);
S
System.out.println(s1);
tring s2 = String.valueOf(decimal);
S
System.out.println(s2);
tring s3 = String.valueOf(letter);
S
System.out.println(s3);
The variable s1 will contain a string representation of 85 (“85”), the variable s2 will contain a string
r epresentation of 54.643 (“54.643”) and the variable s3 will contain a string representation of ‘A’ (“A”).
ometimes we need to work with ASCII values of strings or characters. In that case we needtoconvertan
S
elementinastringintoitscorrespondingUnicodevalue. WecanusethecodePointAt()methodwhichtakesan
index of a string as a parameter and returns the Unicode value of the element in the given index.
9.18 WO
RKSHEET
. Write a Java program that takes a string as input and reverses it.
A
Sample input 1:
Programming
Sample output 1:
gnimmargorP
B. W riteaJavaprogramthattakesastringasinputandcountsthenumberofvowels(a,e,i,o,u)present
in the string.
Sample input 1:
Programming
Sample output 1:
3
. Write a program which takes a string as input and returns the number of characters in the string.
D
Sample input 1:
Programming
Sample output 1:
11
F. Y ourtaskistoinputawordintoaString.ThenprintcodeforeachcharacterintheStringusingthe2nd
method discussed above.
Sample input 1:
Pro
Sample output 1:
P : 80
r : 114
o : 111
Page|54
G. P rintthestatisticsofoccurrenceofeachcharacteronalinebyitself.Assumethatuserwillonlygive
CAPITAL letters. So, you will have to count values of CAPITAL letters only.
Sample input 1:
BALL