0 ratings0% found this document useful (0 votes) 35 views8 pagesStrings
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
String (part - 1 - Immutable String)
Index
String Introduction 2
Immutable String 2
‘Without using new Keyword 3
Using new Keyword 3
Different Methods to Compare String - (examples pg. 6) 4
Concatenation of the strings - Adding of two string 4
Impact of Immutability 6
‘Comparing two string - example 8
Linkedin | Git-Hub Document created by - Shirish JaiswalString Introduction
In Java, strings are treated as objects; they represent a sequence of characters or char values.
Java.lang.String class is used to create strings and are always enclosed within double quote i.e., "
Strings are of two types Mutable (Changeable) and Immutable (Unchangeable) string.
Immutable string means reference of string can be mutable but instance is immutable...
For Mutable String we use the StringBuffer and StringBuilder class.
Immutable String
‘Syntax to declare the Immutable string:
1. Without using new Keyword Heap area
string ste = "Java"; arsaca
Datatype reference operator ~— value
one object is created in string pool
2. Using new Keyword
String str = new _String(“Java");
two object created one in string pool and another in heap area
3. From Character array to string
char [] ch = {7,'o, 'V, ‘a’;
String str = new _ String (ch);
Memory of every object in java will be allocated in the Heap Area and Strings are treated as objects.
1. Inside Heap area duplicates are allowed.
2, Inthe Heap area there is a String Constant Pool / String Pool where duplicates are not permitted.
1. Whenever we create string without using new keyword only one object is created in string
constant pool
2. Whenever we create a string using a new keyword two objects are created, one inside the String
constant pool and another in the Heap area.
Linkedin | Git-Hub Document created by - Shirish JaiswalWithout using new Keyword
String str1 = "Java"; Strt
String str2 = "Java";
‘str2,
‘System.out.printin (strl == str2);
Output: true
Before allocating the memory JVM will scan the entire string pool to find out whether the same object
already exists or not, if it exists the object will not be created and reference will refer to the already
created same object.
But if it does not exist then an object will be created in the string pool.
As duplicates are not allowed in the string constant pool. In the above example both the strings are
referring to the same object as they contain the same value.
Using new Keyword
String str3. = new String ("Java");
2 object : one in string pool and another in heap area
String str4. = new String ("Java");
str3 — Java
1 object in heap coz string pool does not support duplicate
str4 — Java
System.out.printin (str3
str4);
Output: false
Whenever we create a string using a new keyword two objects will be created inside the memory.
One inside string pool and another inside heap area. This happens when string st 3 is created and it
will start referring to a heap area object.
But when str4 js created, a new object is created inside the heap area but not in the string pool
because string pool does not support duplicates.
str3 and str4 will be referring to objects created inside the heap area.
‘As duplicates are allowed so both the references are referring to the different object inside the heap.
So the output is false because the
pointing.
operator will not compare the value but the references where it's
Linkedin | Git-Hub Document created by - Shirish JaiswalDifferent Methods to Compare String - (examples pg. 8)
1
Reference value will be compared
2. .equals() Actual value will be compared
S.ap (strLequals (str2)); output: true
3. .equallgnoreCose() Actual value will be compared ignoring case
4, .compareTo() Compare value lexicographically i.e., character by character
This will compare ASCII value return int value.
S.op (str3.compareto (str4)); output: 0
If any one of the letters is different it will stop and give the difference
of ASCII value between them.
Concatenation of the strings - Joining two string
String str1 = "Java"; str1 =
String str2 = "Program"; st2
‘System.out.printin (strl.coneat (str2) ); JavaProgram
Output: JavaProgram
JavaPzogzam object will be created but no one will refer to it because we are not storing it.
We have studied strings are immutable but what if e.g,
String st = —_new String ("Java");
String str4. = new String ("Program’y i
str3 = str3.coneat (str);
OR str3 = str3 + str4; Program
System.out.printin (str3); JavaProgram
Output: JavaProgram
ops, str3's value has changed..!!!! But strings are immutal
Nope, an object of value “JavaPzogram” has been created and stx3_has started referring to the
“JavaProgran” object.
Linkedin | Git-Hub Document created by - Shirish JaiswalString str
"Jove";
String str2 "Program; str2
What if we concat str1 and str2 using .concat() method
and these strings are created by not using new keyword, str|_ ————~ JavaProgram
strl = — strl.concat (str2);
Question : Where will the new string be stored inside the heap area or inside the String pool?
Answer : Inside the Heap area. Because whenever we are using any of the references or any of the
methods the abject will be stored inside the Heap area.
Note : Whenever we are using references with the methods or without methods, the memory
allocation will be inside the heap area
These will be resolved in Run time not in the Compile time.
But if we concate the string value :
strl
"Java" + "Program";
It will not create objects in heap area although it's performing concating operations, because it's not
concating any reference value, it's concating the actual value and no references are involved while
concating the actual value.
Note : The Concat method is a little slower than + operator.
System.out.printin (strl_+ str2 +9 + 10); Output: — JavaProgram910
Here the addition of 9 and 10 is not performed and concatenated to string as it is.
System.out.printin (9 + 10 + strl + str2); Output: 19JavaProgram
Here the adi
jon of 9 and 10 is performed and then concatenated to string.
Note : If string is first then all after values will be treated as string.
Linkedin | Git-Hub Document created by - Shirish JaiswalImpact of Immutability
© Space optimization
© Performance is slow
String s = "";
for (int i
Question : What is the Time Complexity of the above snippet? Why?
Answer: O(n’)
String s
for (int i
s = sti;
Heap Address
null 405
O 505
o1 605
012 705
2
So as operations of copying and concating another value to it makes TC to O(n’) as loop will run
n(n+1
2
Example if we have a String size 2GB and we want to concat a string “Apple” to it
It will first copy that 2GB of String to the new address and then add “Apple” to it
So it will take more time,
For this reason we have StringBuilder
Linkedin | Git-Hub Document created by - Shirish JaiswalString Methods
String methods
Output
String str = "hello "; //declaration by string literal
length of the string
S.o.p (str.length());
String to uppercase / lowercase
S.o.p (str.toUpperCase());
S.o.p (str.toLowerCase());
Check if string is empty
S.o.p (str.isEmpty());
Check specific char whether string contains it
S.o.p (str.contains("h"))7
Get index of the char
S.o.p (str.indexof("h"));
To replace any character inside string
S.o.p (str.replace("LL", "YY"));
To check whether a string starts/ends with char, generally used for
username
S.0.p (str.startsWith("#@") )s
S.o.p ( -endsWith("Lo "))%
To trim white spaces inside the string
S.o.p (str.trim());
S.o.p (str.strip());
To find out character at specific index
S.o.p (str.charAt(1));
To find out the character present between the specific range
S.o.p (str.substring(1, 4));
To separate every character from the string
S.o.p (Arrays. toString(str.toCharArray()));
To find out int value of every character
S.o.p (Arrays. toString(str.getBytes()));
To split the string by any specific string
S.0.p (Arrays. toString (str.split("©")));
HELLO
hello
false
true
heYYo
false
true
heLLo
Lo, hy e@, Ly by
[32, 104, 101,
76, 76, 111, 32)
{h, Llo ]
Linkedin | Git-Hub Document created by - Shirish JaiswalComparing two string - example
String methods and operators Output
String strl = "heLLo ";
String str2 = "heLlo ";
Compare stri and str2
S.o.p (strl
SEEQ); true
This happens because of String Pool. Java sees whether the same string is already declared or not.
Ifit’s already declared it will refer to the same object, else it will create a new one.
‘While we create using new keyword ew object is created in heap which support duplicates
String str3 = new String("hello");
String str4 = new String("hello");
Compare reference str3 and str4
S.o.p (stx3 == BEEM); false
Oops this gives false but the values of str3 and str4 are the same!
We need to use another method i-e.,
Obj 1.equals (obj2)
S.o.p (str3.equals(str4)); true
Now let’s create both types of String
String str5 = "hello"; String Pool
String stré = new String("hello"); Heap area
Now we will compare both the strings: In this stx6 reference is compared in the string pool
because such a value is already in it.
S.o.p (str5
stré,intern()); true
Now we will declare the same name to two strings but with different cases.
String fname = "tony'
String Iname = "Pony";
Compare fname to Iname
S.0.p (fname == Iname); false
false it's right. But we humans, for us it's the same so what to do? we can use
equalsIgnorcase () method
S.o.p (fname.equalsIgnoreCase (1name) ) ; true
Linkedin | Git-Hub Document created by - Shirish Jaiswal