No video

Why String is Immutable and Final in Java?

  Рет қаралды 87,787

Naveen AutomationLabs

Naveen AutomationLabs

Күн бұрын

Why String is Immutable and Final?:
There is hardly any Java Interview, where no questions are asked from String, and Why String is Immutable in Java is I think most popular one. This question is also asked as Why String class is made final in Java or simply, Why String is final. In order to answer these questions, Java programmer must have a solid understanding of How String works, what are special features of this class and some key fundamentals.
5 Reasons of Why String is final or Immutable in Java:
1) String Pool
Java designer knows that String is going to be most used data type in all kind of Java applications and that's why they wanted to optimize from start. One of key step on that direction was idea of storing String literals in String pool. Goal was to reduce temporary String object by sharing them and in order to share, they must have to be from Immutable class. You can not share a mutable object with two parties which are unknown to each other. Let's take an hypothetical example, where two reference variable is pointing to same String object:
String s1 = "Java";
String s2 = "Java";
Now if s1 changes the object from "Java" to "C++", reference variable also got value s2="C++", which it doesn't even know about it. By making String immutable, this sharing of String literal was possible. In short, key idea of String pool can not be implemented without making String final or Immutable in Java.
2) Security:
Java has clear goal in terms of providing a secure environment at every level of service and String is critical in those whole security stuff. String has been widely used as parameter for many Java classes, e.g. for opening network connection, you can pass host and port as String, for reading files in Java you can pass path of files and directory as String and for opening database connection, you can pass database URL as String. If String was not immutable, a user might have granted to access a particular file in system, but after authentication he can change the PATH to something else, this could cause serious security issues. Similarly, while connecting to database or any other machine in network, mutating String value can pose security threats. Mutable strings could also cause security problem in Reflection as well, as the parameters are strings.
3) Use of String in Class Loading Mechanism
Another reason for making String final or Immutable was driven by the fact that it was heavily used in class loading mechanism. As String been not Immutable, an attacker can take advantage of this fact and a request to load standard Java classes e.g. java.io.Reader can be changed to malicious class com.unknown.DataStolenReader. By keeping String final and immutable, we can at least be sure that JVM is loading correct classes.
4) Multithreading Benefits
Since Concurrency and Multi-threading was Java's key offering, it made lot of sense to think about thread-safety of String objects. Since it was expected that String will be used widely, making it Immutable means no external synchronization, means much cleaner code involving sharing of String between multiple threads. This single feature, makes already complicate, confusing and error prone concurrency coding much easier. Because String is immutable and we just share it between threads, it result in more readable code.
5) Optimization and Performance
Now when you make a class Immutable, you know in advance that, this class is not going to change once created. This guarantee open path for many performance optimization e.g. caching. String itself know that, I am not going to change, so String cache its hashcode. It even calculate hashcode lazily and once created, just cache it. In simple world, when you first call hashCode() method of any String object, it calculate hash code and all subsequent call to hashCode() returns already calculated, cached value. This results in good performance gain, given String is heavily used in hash based Maps e.g. Hashtable and HashMap. Caching of hashcode was not possible without making it immutable and final, as it depends upon content of String itself.
~~~~Subscribe to this channel, and press bell icon to get some interesting videos on Selenium and Automation:
www.youtube.co...
Follow me on my Facebook Page:
/ naveenqtpexpert
Let's join our Automation community for some amazing knowledge sharing and group discussion on Telegram:
t.me/joinchat/...
vimeo.com/onde...

Пікірлер: 46
@punitdixit8268
@punitdixit8268 4 жыл бұрын
Note: From Java 7 onwards, the Java String Pool is stored in the Heap space.
@anilleo18
@anilleo18 6 жыл бұрын
thanks for your time naveen...we r very much thankful towards your work
@ashishgoswami3784
@ashishgoswami3784 5 ай бұрын
Important note: Java String Constant Pool is created inside Heap area.
@jagadeeshbaskaran4881
@jagadeeshbaskaran4881 2 жыл бұрын
This is the best explanation. Nobody can match you. Thanks
@k.ravichandra1049
@k.ravichandra1049 2 жыл бұрын
Excellent explanation Naveen bro
@astuteacerbic
@astuteacerbic 4 жыл бұрын
Thanks Naveen for sharing. God bless you.
@lamberto6405
@lamberto6405 4 жыл бұрын
It would be great to see more code examples, specially tricky ones. There is 20 minutes of explanation with simple examples but some questions on tests are much trickier and students still fall into the trap.
@user-rx8pz4rm9o
@user-rx8pz4rm9o 3 жыл бұрын
Hi Naveen, Thanks for spending so much time while creating the knowledge. I am still in doubt on immutability, to me, it seems every variable is immutable: String s1 = "Java"; String s2 = "Java"; String s3 = s1; s3 = "NewJava"; System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(s1); int i1 = 10; int i2 = i1; i2=20; System.out.println(i1); Integer i3 = 30; int i4 = i3; i4 = 40; System.out.println(i3);
@nitish915
@nitish915 5 жыл бұрын
String constant pool is in heap area.
@qwertkeys30
@qwertkeys30 3 жыл бұрын
Hi, I doubt Why strings are called immutable, because if give like this String s="hi" and in the next line, we give s="hello" the value of s will change right please help me to understand anyone.
@USP7
@USP7 6 жыл бұрын
Hi Naveen , Can you make video on Role & Responsibility of tester in AWS cloud computing. much needed
@jvsnyc
@jvsnyc 4 жыл бұрын
I don't want to start some East-Coast/West-Coast Gangster Rap War here, but I did notice something. On the answer given by Naresh i Technologies channel here on KZfaq, they emphasize very much something that you don't, and mention these only in passing. Some viewers angrily suggested that the "Real Reasons" were what you show here. However, while everything in here is true, I think there is a second reason that was there from the very beginning and became even more important over time and is what is emphasized by Hari Krishna in his video: Suitability of the very common data types of Sting/Integer/other wrapper classes as keys in Hashtable objects, and later HashMap objects, and also later members of SortedSet/NavigableSet or keys of SortedMap objects. His presentation suggests that this was primary and the other things all good, but came later. Anyway, you do highlight why final is necessary for these classes even tho there are plenty of times one wishes one could subclass them for legitimate and honorable purposes, the security danger is too great. Cheers.
@gunaykhalilbayli1786
@gunaykhalilbayli1786 5 жыл бұрын
great explanation as always.
@naveenautomationlabs
@naveenautomationlabs 5 жыл бұрын
Thanks Gunay
@sparshpandey2878
@sparshpandey2878 6 жыл бұрын
Awesome Video , Can you please make one video on this program -> "You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array. Traverse array only once". I encountered this question in of the interviews I gave. Thanks in Advance
@truthlover3522
@truthlover3522 6 жыл бұрын
public class segregate { public static void main(String[] args) { // TODO Auto-generSated method stub int arr[] = {1,0,0,1,0,1,0,0,1,0,1}; System.out.println(arr.length); int j = -1; for (int i = 0; i < arr.length; i++) { // if number is smaller than 1 // then swap it with j-th number if (arr[i] < 1) { j++; int temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } } System.out.println(""); for(int m=0;m
@jarvisfriday7452
@jarvisfriday7452 3 жыл бұрын
By using this method we can segregate as per ur question Arrays.sort(a[]);
@simplyajith1
@simplyajith1 2 жыл бұрын
arr = [1,0,0,0,1,1] d = {} for i in arr: d[i] = d.get(i,[]) + [i] new_arr = [] if 0 in d: for i in range(len(d[0])): new_arr +=[0] if 1 in d: for i in range(len(d[1])): new_arr+=[1] print(new_arr)
@tejastoley6714
@tejastoley6714 5 жыл бұрын
what happen when we declare like String s = new String("tejas"); String s1 = new String("toley"); is the ref. stored in heap memory?
@bharatvarshney2666
@bharatvarshney2666 6 жыл бұрын
nicely explanation , thanks naveen
@gnsc
@gnsc 6 жыл бұрын
awsome naveen bro.nice way of telling....👌
@bikashdeuja9015
@bikashdeuja9015 6 жыл бұрын
Can you please give me the Java tutor for Selenium that you have in your video. Couldn't find the right link. Thanks
@vivekkurhe9881
@vivekkurhe9881 6 жыл бұрын
Hi naveen please make some videos on protractor, it will be very helpful
@timetogrow1306
@timetogrow1306 2 жыл бұрын
I need ur full videos of java
@HH_Linkmusic
@HH_Linkmusic 4 жыл бұрын
Thank you so much! Very detailed explanation.
@winstoncorey2023
@winstoncorey2023 3 жыл бұрын
sorry to be so offtopic but does anybody know of a way to get back into an Instagram account? I was dumb forgot the login password. I would appreciate any tricks you can offer me.
@randallwilliam2869
@randallwilliam2869 3 жыл бұрын
@Winston Corey Instablaster :)
@winstoncorey2023
@winstoncorey2023 3 жыл бұрын
@Randall William thanks for your reply. I got to the site through google and im trying it out now. I see it takes a while so I will reply here later with my results.
@winstoncorey2023
@winstoncorey2023 3 жыл бұрын
@Randall William It worked and I actually got access to my account again. I am so happy! Thanks so much, you really help me out :D
@randallwilliam2869
@randallwilliam2869 3 жыл бұрын
@Winston Corey glad I could help :)
@nukalasagar7078
@nukalasagar7078 6 жыл бұрын
hi bro, if we create strings in non-constant loop like String s1=new String("java"); then how string is immutable,please kindly explain it
@virtexamit
@virtexamit 5 жыл бұрын
When we create String using new operator 2 things happened 1st object created on heap and also same string also create on pool. Hope this help.
@venkateshandea1767
@venkateshandea1767 6 жыл бұрын
Hi naveen anna, can u make any videos on selenium with c# atleast some advanced videos like framework level
@shanthikandasamy
@shanthikandasamy 5 жыл бұрын
How can I have live chat with you to discuss about selenium/java If I became the member of this?
@mayurkhare1928
@mayurkhare1928 6 жыл бұрын
Hi Naveen My question is how to add firepath, firebug in latest mozila 'Quantum'
@vandanadhiman5532
@vandanadhiman5532 6 жыл бұрын
I dont think there is a way except downgrading your firefox to the 46-49 versions.
@srihari4827
@srihari4827 5 жыл бұрын
I think chropath for Firefox would help you if you are working with latest version
@omashete3800
@omashete3800 3 жыл бұрын
one confusion sir immutable String value are change value or not change
@gayathrik8569
@gayathrik8569 4 жыл бұрын
Since immutable string is sharing memory, how this can provide high security?
@jvsnyc
@jvsnyc 4 жыл бұрын
Because there is no easy way to write to that shared memory, unlike the Wild, Wild West of the C++ heap where pointers roam wild and free like tigers.
@nikitagade8193
@nikitagade8193 3 жыл бұрын
Hi Naveen, thanks for your helpful videos. If for an example String s="abc"; s=s.concat("def"); System.out.println(s); O/p: abc def So string value got changed. Could you please explain string is immutable concept using the above example
@uk7826
@uk7826 2 жыл бұрын
After concatenate new object("abcdef") is created. Now s will refer to new object rather than old object("abc"). Old object is not changed and is no more referred by reference(s).
@nikitagade8193
@nikitagade8193 2 жыл бұрын
@@uk7826 thank you
@priya-vf3jc
@priya-vf3jc 6 жыл бұрын
my question is regarding Xpath ... as u said in drop down session like By.id() in main()... but wen v separately save xpaths in .propertiesfile and wen v want to automate that through keywords.java class den how to use it ... public void choose(String objectname, String data) { Select select = new Select(driver.findElement(By.xpath(prop.getProperty(objectname)))); select.selectByVisibleText("working"); // ??? } leadstatus= //*[@id='23:3372;a']/div/a dis is how i saved in objectrepository.propertiesfile ???
@vamsim9671
@vamsim9671 6 жыл бұрын
Hi naveen, please nake videos on protractor ...
@sivakumar-mu3wj
@sivakumar-mu3wj 3 жыл бұрын
S1 will not change if S2 value is changed package com.basics.packageone; public class pkg_1_n12_stringTest { public static void main(String[] args) { // TODO Auto-generated method stub String v1 = "Hai"; System.out.println("V1 is " + v1); String v2 = "Hai"; System.out.println("v2 is " + v2); v2 = "Bye"; System.out.println("V2 after change is " + v2); System.out.println("V1 after change is " + v1); } }
Constructor Concept and This Keyword in Java
45:04
Naveen AutomationLabs
Рет қаралды 60 М.
How to find Prime Number || Basic Programming Questions Series
20:37
Naveen AutomationLabs
Рет қаралды 81 М.
Unveiling my winning secret to defeating Maxim!😎| Free Fire Official
00:14
Garena Free Fire Global
Рет қаралды 10 МЛН
Мы сделали гигантские сухарики!  #большаяеда
00:44
女孩妒忌小丑女? #小丑#shorts
00:34
好人小丑
Рет қаралды 84 МЛН
What is String Immutable || Why String Object Is Immutable In Java (Hindi)
17:36
13. Java Singleton and Immutable Class Explained with Examples | Java Classes in Depth - Part4
28:26
Coding Was Hard Until I Learned THESE 5 Things!
7:40
Pooja Dutt
Рет қаралды 1 МЛН
Exception Handling in Java
59:14
Naveen AutomationLabs
Рет қаралды 65 М.
Why string is immutable in java || The 4 reasons you must know || part 1
20:53
Difference between Interface and Absract Class
30:52
Naveen AutomationLabs
Рет қаралды 180 М.
Java Strings are Immutable - Here's What That Actually Means
7:06
Coding with John
Рет қаралды 612 М.