This is why string is immutable in Java || String Hashcode caching internal || part 2

  Рет қаралды 49,856

Selenium Express

Selenium Express

Күн бұрын

Why string is immutable in java is one of the frequently asked interview questions.In the last video, we have covered why string is immutable in string pool point of view.In case you have missed that out you can watch this at the below link
Like string class, String class hashcode() is also special.String class hashcode method compute hashcode only one time and then cached in the string object header forever.In this video, we are going to see this in detail.
Well now a most important question, how is this hashcode caching of string helping us? Well, string is immutable in java, this confirms that the content of the object will not change.If so then there is no meaning of calculating the string hashcode again and again as JVM internally uses string characters to calculate the hashcode.So if the string content is not going to change as it’s immutable, then the hashcode is not going to change.
In this way String caching help us to perform a faster operation with a hash-based collection like hashmap, HashSet where there is need of calculating the hashcode again and again.So string used popularly as a key in the hashmap.
So a Note here: The hashcode method of string class in java run for only one time, calculate the hashcode then cached it in the string object header.
So when it comes to "string in java interview questions”, This topic has so much weight.So let’s explore more with this tutorial and the get the answers to the below questions :
1)What is string hashcode caching?
2)Why is String used as a key in hashmap?
3)What is the benefits string hashcode caching and how they help them hash-based collections.
4)And the most important question, Why string is immutable in java?
In case you might be wanted to know how the hashmap works internally, I have already videos available for this which will beneficial to understand this tutorial.Find it at the below link :
• Hashmap Internal working
subscribe to my channel by clicking on the link below.
/ @seleniumexpress
Stay tuned and like my Facebook page for more.
/ seleniumexpress
Music :
-----------
credits : -
(intro)
1)
Adventures by A Himitsu / a-himitsu
Creative Commons - Attribution 3.0 Unported- CC BY 3.0
creativecommons....
Music released by Argofox • A Himitsu - Adventures...
Music provided by Audio Library • Adventures - A Himitsu...
2)
Music by Kevin MacLeod. Available under the Creative Commons Attribution 3.0 Unported license: creativecommons.... Download link: incompetech.co....
-----
intro template :
wkzbin.info

Пікірлер: 81
@raghuakuthota4900
@raghuakuthota4900 6 жыл бұрын
Please come up with Singleton class in java - if possible - lot's of people is confusion with the this topic - your all videos are awesome
@soumyamogullapalli
@soumyamogullapalli 3 жыл бұрын
Splendid Explanation, Best video so far about why Strings are immutable. Thank you for sharing! Please keep doing more videos.
@kiranware444
@kiranware444 4 жыл бұрын
amazing explanation and showing practically step by step what exactly happening.And I saw your Internal working of HashMap that was also amazing and you show each and everything practically by debugging. Thanks a lots. God bless you always.
@rajneeshraikwar8352
@rajneeshraikwar8352 3 жыл бұрын
Awesome, Too depth explanation.
@pallavigoel5810
@pallavigoel5810 4 жыл бұрын
Contents of your videos are very good and explanation is great. I t has clarified many of my concepts. Thanks a lot Abi!
@danceayush8128
@danceayush8128 3 жыл бұрын
Great job brother 👍👍
@Dyslexic_Neuron
@Dyslexic_Neuron 5 жыл бұрын
Your videos are so exhaustive ....thanks man !!
@satheeshguru6080
@satheeshguru6080 6 жыл бұрын
Awesome, Clear explanation.
@SeleniumExpress
@SeleniumExpress 6 жыл бұрын
Thank you, Satheesh 👍
@yashwanthraj.8125
@yashwanthraj.8125 6 жыл бұрын
The explanation was really awesome
@zippy.gaurav
@zippy.gaurav 6 жыл бұрын
Really great content. Thanks
@SeleniumExpress
@SeleniumExpress 6 жыл бұрын
Thanks, Gaurav.
@pankajlee6408
@pankajlee6408 4 жыл бұрын
Awesome tutorial 🙂
@thirumaniraj5988
@thirumaniraj5988 4 жыл бұрын
Amazing explanation! Thanks!!
@shikharchaudhary6984
@shikharchaudhary6984 5 жыл бұрын
Your videos are amazing bro
@vimalsubha
@vimalsubha 6 жыл бұрын
Very good explanation
@jvsnyc
@jvsnyc 4 жыл бұрын
Interesting. At ~8:56 we see something I'd been wondering about. We say that String is immutable, but we also see hashcode() method writing a value to private member variable hash. So it is immutable to the user, and the character array never changes, but the hash value is only lazily computed the first time the user or system calls hashcode(), not in the constructor. Just a detail, but I was wondering about this until I got to the end of the video and went back to look more closely. To me, a strict, uptight definition of immutable would mean as soon as the constructor returns, the object is fully baked and done, no more writing to it. I guess the hash code and locks don't count. Not that there is any necessity to lock an immutable object, but it still inherits from Object.
@arijitdas2282
@arijitdas2282 5 жыл бұрын
I am a fan of your tutorials :)
@sanjeevkumar-et8rw
@sanjeevkumar-et8rw 6 жыл бұрын
Hi Avilash if we have two variable namely String str="Avi"; String str1="Avi"; only one object is created in String constant pool (Avi) str and st1 have reference of it.how many time hashcode will be calculated. whether hashcode will be calculated for two times one for str and one for str1.please clarify it
@cinsuthomas8593
@cinsuthomas8593 6 жыл бұрын
Hi Sanjeev, hashcode will not be calculated at all. Only if you give str.hashCode(), the hashCode will be calculated. Otherwise it will be 0.So if you give String str="Avi"; str.hashCode(); String str1="Avi"; str1.hashCode(); then the above code will calculate hashCode at line no 2 and cache it. line no 4 will take cached value from line 2 and so it will not be calculated again. However, what I observed is that caching takes place only if we calculate the hashCode using the constant pool object reference. See below code example: 1 String s=new String("test"); 2 s.hashCode(); 3 String s1=new String("test"); 4 s1.hashCode(); 5 String s2="test"; 6 s2.hashCode(); 7 String s3=new String("test"); 8 s3.hashCode(); 9 String s4="test"; 10 s4.hashCode(); For the above piece of code Line 2, and Line 4 has string object reference created in heap. So the hash is not cached and is calculated again and again. At line 6, the hash is again calculated but is cached for the first time as s2 is object reference from string constant pool. At line 8, the hashCode is not calculated because we get the cached value from line 6. So to conclude the above code calculates hashcode 3 times (at line 2,4 and 6), cache it at after line 6 execution, and uses cached value at line 8 and line 10
@ramp4409
@ramp4409 5 жыл бұрын
Hi Avilash ..... Its a great video ... There is a small correction in it .... It will call the hashcode method but the calculation will not happen again and again since it is > 0....
@ashokmandadi
@ashokmandadi 6 жыл бұрын
very good explanation,I did not get this type of information in any online tutorials
@SeleniumExpress
@SeleniumExpress 6 жыл бұрын
Thanks, Ashok..
@muralimohan7097
@muralimohan7097 3 жыл бұрын
the way of ur's teaching is awesome. Could you please do Hibernate and design pattern videos
@RiteshKumar-lm9yt
@RiteshKumar-lm9yt 6 жыл бұрын
Nice explanation
@manoganesan7618
@manoganesan7618 6 жыл бұрын
Awesome bro.. really helpful..
@aayushmehta5359
@aayushmehta5359 3 жыл бұрын
Your all videos are awesome, thanks for such great work. It's worth subscribing...
@jvsnyc
@jvsnyc 4 жыл бұрын
Agreed with the people who found the acoustics of the room you filmed the first part in to be making it harder to understand you. Not impossible, for sure, but definitely less easy to hear clearly.
@rikkimalik7354
@rikkimalik7354 2 жыл бұрын
my debuger not going into the String class implementaion. What im missing in debugging?
@kranthisingh1749
@kranthisingh1749 6 жыл бұрын
When exactly does a String literal gets garbage collected ?? I heard like string constant pool objects are never garbage collected. Can you help me out on that
@SeleniumExpress
@SeleniumExpress 6 жыл бұрын
Hi Kranthi, It's a good question. You are right, the garbage collector is not allowed to scp. When the application got shut down the string pool cleaned up.
@kranthisingh1749
@kranthisingh1749 6 жыл бұрын
Thank you for your reply.... Just a add up question so what if scp get full before app shutdown.. Is there any chance for such happenings?? Bz prod apps doesnt go down frequently so in that case how scp is managed from over flow? Sorry to bother vth such big question
@siddaroodanellure7521
@siddaroodanellure7521 6 жыл бұрын
@@kranthisingh1749 i think ..there is a cluster concept if one server down another server will be up...and there will be scheduled restart server concept like weekly once or monthly once in that time scp unreferenced object will be removed.
@amitgala1990
@amitgala1990 5 жыл бұрын
Before Java 7, the JVM placed the Java String Pool in the PermGen space, which has a fixed size - it can’t be expanded at runtime and is not eligible for garbage collection. The risk of interning Strings in the PermGen (instead of the Heap) is that we can get an OutOfMemory error from the JVM if we intern too many Strings. From Java 7 onwards, the Java String Pool is stored in the Heap space, which is garbage collected by the JVM. The advantage of this approach is the reduced risk of OutOfMemory error because unreferenced Strings will be removed from the pool, thereby releasing memory.
@Dziki8332
@Dziki8332 2 жыл бұрын
What if we make MyDemo class immutable? Is JVM going to run hashCode() each time or it gets cached as String? I didn't find answer in the video.
@youaretrend
@youaretrend 6 жыл бұрын
good explanation buddy.... keep it up
@SeleniumExpress
@SeleniumExpress 6 жыл бұрын
michsandeep Thank you!!
@youaretrend
@youaretrend 6 жыл бұрын
have u created some video on Java threads? i could not locate any. If yes plz share the link.
@SeleniumExpress
@SeleniumExpress 6 жыл бұрын
michsandeep I have not upload one yet.. I will keep you posted when I will upload one. Thanks for watching!!
@prabhakarreddy9180
@prabhakarreddy9180 5 жыл бұрын
Hi avi In my eclipse step into not working The cursor will not goes into the string class hash code method its goes step over Why this will happen please reply me
@georgemichael2572
@georgemichael2572 6 жыл бұрын
Thanks a lot.i hav a doubt Can I use shorthand += operator to add string.if in that case the string content will change then how it will immutable .can u please explain
@meghaladevi6411
@meghaladevi6411 5 жыл бұрын
Amazing. Thank you :)
@tarunbhatt6385
@tarunbhatt6385 6 жыл бұрын
good.
@nivethithanivetha921
@nivethithanivetha921 5 жыл бұрын
Hi tutor... Your videos are easy to understand thank you for that. In above hashcode calc how 31* h+val[I] -----> why 31 Val[I]= val[0]=h if takes h or asci of that h Can you plzzzzz explain
@ESudarshan
@ESudarshan 5 жыл бұрын
String object "aa" is not assigned to any reference. Where will be the hash code stored and reused without the hash code being recalculated?
@shivakamlikar2144
@shivakamlikar2144 6 жыл бұрын
Awesome teaching
@SeleniumExpress
@SeleniumExpress 6 жыл бұрын
shiva kamlikar Thanks, Shiva..
@tabishrizwan9137
@tabishrizwan9137 7 ай бұрын
Hi Abhilash, In Java 8 implementation is changed in String Class.
@adityatattva
@adityatattva 6 жыл бұрын
thank you
@SeleniumExpress
@SeleniumExpress 6 жыл бұрын
Tattva Puvvada you are welcome!!
@petitexplorer23
@petitexplorer23 5 жыл бұрын
Hi Abhilash, can you please make videos on Collection Framework. Your concepts are Fab and really easy to understand so it would be great if you make videos on Collection. We want to be strong in Collections ☹️
@priyankatiwari3193
@priyankatiwari3193 3 жыл бұрын
When we create two strings String str1 = "Avi"; and String str2 = "Avi"; how is the comparison made to make str2 point to same reference(str1) in SCP, its on the basis of value that is stored in SCP or the hashcode for the string.
@saikrish1176
@saikrish1176 6 жыл бұрын
sir please explain about control statements with examples.......
@SeleniumExpress
@SeleniumExpress 6 жыл бұрын
Sure Sai.I will upload soon.
@rajasekharbolla6360
@rajasekharbolla6360 6 жыл бұрын
Avilash please provide collection framework with examples if possible
@aparnashimpi6253
@aparnashimpi6253 4 жыл бұрын
what is race conditions on HashMap and how HashMap resize in Java? What are ConsurrentHashMap and the Synchronized map in java with example in detail? can you please answer these questions in detail with example
@ibrahimshaikh3642
@ibrahimshaikh3642 5 жыл бұрын
Really nice explanation. Could you please make same debug operations for LinkedHashMap or hashMap with explanation. Because there r so many videos but no one coverd it yet like that Thanks in advance
@brankoblesicjr.5792
@brankoblesicjr.5792 4 жыл бұрын
wow man
@jahid4874
@jahid4874 6 жыл бұрын
when i am running app in debug mode it shows Class.getDeclaredMethods0(boolean) line: not available [native method] plz help me
@sharathtn5336
@sharathtn5336 5 жыл бұрын
Why Hashcode is zero for the String?? Please explain
@NrAquaSpace
@NrAquaSpace 4 жыл бұрын
bro ur videos are very good, but audio is horrible after seeing one or two videos we are getting headache because of the audio, try to change the mic so that you will get more views.....................
@vishalgaikwad873
@vishalgaikwad873 6 жыл бұрын
Sir can u tell me, HoW ho calculate index number by using hashcode... Today i got how to calculate hashcode, but one thing is remaining...
@SeleniumExpress
@SeleniumExpress 6 жыл бұрын
Hi Vishal,I have video lined up for Hashcode and equals method.I will publish them soon.We will discuss the hashcode calculation and a lot of other information about hashcode method.Once I publish the video I will put the link here.Thank you.
@vishalgaikwad873
@vishalgaikwad873 6 жыл бұрын
Ok sir, Nop
@manjulakt2401
@manjulakt2401 6 жыл бұрын
Hi sir, Please send the Why String is immutable in java ||Part 3
@manjulakt2401
@manjulakt2401 6 жыл бұрын
Please send the part 3 video link of "why string is immutable in java".
@SeleniumExpress
@SeleniumExpress 6 жыл бұрын
Hi Manjula, The next video will be how String being immutable helping us on the thread safety and How string is providing high-level security to us. This video is on recording stage right now.Once it's published, I will post the link here. I am really sorry for the delay.
@vaibhavgondralwar1025
@vaibhavgondralwar1025 6 жыл бұрын
One question asked me in the interview that why password is stored inside char array not in the string?
@SeleniumExpress
@SeleniumExpress 6 жыл бұрын
Vaibhav Gondralwar Hi Vaibhav, Yes,what I think char[] is a batter option to be used for password in encrypted format. I remember even Java deprecated couple of methods in Swing class which used to return string when we ask for password and they have introduced new methods for getting password which returns a char array. (I don't remember the method exactly) As string is immutable,it's stored inside the string pool for longer time as we reuse them pretty much.in that case any wrong access to the Memory dump can put your password in threat. Even if we try changing the password the older one will still be there as string is immutable and any changes over a existing string will create a new string. So the password still lay on memory in clear text. An argument can be made that the char array will also stay in memory before the garbage collector runs and clears it. But we can explicitly change all the index to zero for immediate effect which will secure our password because char array is mutable and it's object content can be changed. Eg Char[] password = {'p','a', 's', 's'}; Arrays. fill(password, '\0'); I guess, char array will also reduce the risk as they can't be accessed in ram but storig the password in char array can also complicate things. Let me know your view on this question as well. Thank you for posting this question. Have a nice time Vaibhav.
@bacon37460
@bacon37460 4 жыл бұрын
I found this answer in stackoverflow. Since Strings are immutable there is no way the contents of Strings can be changed because any change will produce a new String, while if you use a char[] you can still set all the elements as blank or zero. So storing a password in a character array clearly mitigates the security risk of stealing a password.
@sivasreekanthkotapati3585
@sivasreekanthkotapati3585 6 жыл бұрын
Hi, very good explanation I want to know aboutexecutor f/w, please send me link.
@arunteltia7888
@arunteltia7888 5 жыл бұрын
plz dont use the song within the video its annoying anyway the video is a masterpeice i have a question can u tell me how do you get this knowledge do you red documentation
@SeleniumExpress
@SeleniumExpress 5 жыл бұрын
Sure, Arun. I will try not to use songs in videos. I know it's annoying and realized the same with time. Thank you for letting me know that 😊
@arunteltia7888
@arunteltia7888 5 жыл бұрын
@@SeleniumExpress thanks for being so humble sir can u tell me the question as well it would be great help
@RiyazParasara
@RiyazParasara 5 жыл бұрын
Video is too good. But your voice is not clear. Eco voice getting because you are in room
@mani1697
@mani1697 6 жыл бұрын
Disclaimer: This is just my suggestion. Bro, You have real content in your brain but I have just one suggestion. This video makes me feel like you are acting throughout the video. Please improve your voice modulation, try to be yourself.
@SeleniumExpress
@SeleniumExpress 6 жыл бұрын
Thanks, Mani for the feedback.. I will work on myself for sure. Have a nice time!! 😊
@jvsnyc
@jvsnyc 4 жыл бұрын
Sure, the probability is I guess zero, but if after all of the long hard work of computing the hash code for a very long string, if it happens to be zero then caching it does nothing, we will see the zero and re-compute it again every time. Of course, that is only as likely as someone being named "Abhilash Trout Superman" or something -- but I don't see a reason it couldn't happen. So the caching is broken for 1 out of 2 ^ 32 possible objects.
@chittranjankumar5769
@chittranjankumar5769 6 жыл бұрын
totally confused please be very specific and don't repeat same things many times please
@SeleniumExpress
@SeleniumExpress 6 жыл бұрын
I am sorry to hear that this doesn't help. Could you please let me know where you got confused? We both can work together to let your confusion go.
@vishnunarayan6775
@vishnunarayan6775 2 жыл бұрын
Good explanation
Why string is immutable in java || The 4 reasons you must know || part 1
20:53
I Sent a Subscriber to Disneyland
0:27
MrBeast
Рет қаралды 104 МЛН
진짜✅ 아님 가짜❌???
0:21
승비니 Seungbini
Рет қаралды 10 МЛН
Java Strings are Immutable - What That Actually Means?
5:39
Daily Code Buffer
Рет қаралды 14 М.
Why String is Immutable and Final in Java?
19:59
Naveen AutomationLabs
Рет қаралды 89 М.
String Constant Pool in Java || String Object Creation in Java
23:51
Smart Programming
Рет қаралды 227 М.