Why String is Immutable | Java Tutorial

Поділитися
Вставка
  • Опубліковано 26 гру 2024

КОМЕНТАРІ • 121

  • @NareshIT
    @NareshIT  5 років тому +2

    Please Comment, Subscribe and Click Bell🔔🔔🔔 Icon for More Updates. To learn software course from our experts please register here for online training: goo.gl/HIB0wL

    • @adaylightsmile7961
      @adaylightsmile7961 4 роки тому

      (wrong) --------------> ( not immutable 00:10:51 )
      [{there actually I confused}]
      in the previous diagram if the string is given as mutable
      then only we get NULL
      and only IM-MUTABLE WE GET 1 Value.
      [{ Finally whole Explanation is GOOD }]..
      :) i am here to help you by mentioning that and then concept will get helpful

  • @anudeepyendrapalli4356
    @anudeepyendrapalli4356 8 років тому +8

    Excellent sir.Good to see you on youtube. please do Keep posting videos like this to enjoy your lecture. 4 years back when I was a fresher I have learnt Java from you and now I am working for MNC. Thanks a lot for your dedicated teaching and inspiration.

  • @hireme3864
    @hireme3864 7 років тому +42

    Sorry, but your theory and example does not make any sense. Below is the reason for String being immutable
    Security: parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed.
    Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues.
    Caching: when compiler optimizes your String objects, it sees that if two objects have same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object).
    Class loading: String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).

    • @mani1697
      @mani1697 6 років тому +1

      I totally agree with you

    • @vinodkumar-tn9uy
      @vinodkumar-tn9uy 6 років тому +1

      Super explanation

    • @vinaysipayee8449
      @vinaysipayee8449 6 років тому

      Awesome buddy..! (y)

    • @smitapadhi7214
      @smitapadhi7214 6 років тому +3

      i have lots of doubt in String chapter can anyone help me go get best way to understand this chapter, i need in very urgently.

    • @sagarshekhar6296
      @sagarshekhar6296 6 років тому

      To the point....

  • @jvsnyc
    @jvsnyc 4 роки тому +3

    Watching this, I realize I once failed an interview by suggesting that a mutable object could be used as a key in a map!! The question wasn't posed in such an obvious way, I never would have gotten that wrong. While discussing a solution they asked "So, what else could we have used as a key here?" and might have suggested the mutable object as a possibility. I said "Yeah, sure" because I was nervous and wanted to get whatever else in. They had a lot of candidates and someone got to say "Yay, we just narrowed down." I really didn't realize it until just now watching this discussion. Knowing something well enough to answer a question phrased directly is different from knowing it well enough to see it and deal with it in the wild. I see how preparing one for these kinds of things that affect both ones code and interviews is being considered by these teachers.

  • @anandashok7301
    @anandashok7301 4 роки тому +2

    First of all the way you used toUpperCase() is wrong. It will change the value and create another object in String constant pool, but it will not return the converted value to s1. The basic String Class operation.

    • @nanavanalla10
      @nanavanalla10 10 місяців тому

      HK sir didn't mentioned that "HK" will store in s1, they just making us clear that s1.toUppercase(); will not change the already existing value "hk" in String constant pool.
      If you want to create an object in string constant pool then need to create an string again like String s2 = s1.toUpperCase();
      And then you can store in Hashtable as ht.put (s2, 4);
      If you perfect at Java then you will get it now atleast. Otherwise you can only do it from your side and execute it.
      String s2 = s1.toUpperCase(); this one HK sir didn't written so you confused I think, indirectly Sir telling that it should be stored in one more string and we can put in map.

  • @karunkausal9151
    @karunkausal9151 3 роки тому +3

    Hello sir Today in one interview i have said this answer for string immutable but then interviewer asked me how is it possible string introduced in java Early and hashmap introduced later. So is it possible

  • @amitclick99
    @amitclick99 6 років тому

    If you try to get Object obj= ht.get("HK"); means upper case then you will get null ..it means value 1 is not created for after making it s.toUpperCase();

  • @2singam
    @2singam 4 роки тому +4

    Really it's very good nd clearly explained, thank you sir.

  • @arunchalla5453
    @arunchalla5453 5 років тому

    One small correction,
    String s1 = "hk";
    Hashtable ht = new Hashtable();
    ht.put(s1, "1");
    ht.put("Ravi", "2");
    ht.put("Raju", "3");
    s1.toUpperCase();
    --> this should be s1 = s1.toUppercase(); to make s1 as HK
    System.out.println(ht.get("hk"));
    Your program has no effect on s1 as mentioned reason above.
    Moreover you need to pass ht.get(s1) instead of ht.get("hk") to see if calling s1.uppercase() has really changed the value from hk to HK.
    Just to make it clear, calling string methods on string value will not have affect untill you say s1 = s1.toUpperCase(); and observe that this is new object and that old object with s1 = hk is destroyed.

  • @himeshgupta6478
    @himeshgupta6478 3 роки тому

    I think string is a primitive so it should get passed by value in java( and all non- primitive obj are passed as references) and thus the map key shouldn't change.... Would be glad if you clarify me on this sir..

  • @lawanutech9977
    @lawanutech9977 7 років тому +1

    Hashmap uses generics HashMap.So,keys can be of different datatype too.It is not a strong reason for String Immutability.

    • @chrissmith2137
      @chrissmith2137 3 роки тому

      Other object equivalents of primitive datatypes like Integer, Long, Boolean, etc are also immutable.

  • @manishanker2488
    @manishanker2488 8 років тому +5

    string class introduced in Java 1.0 where as collection are introduced in 1.2 and what is the relation ship between string class and collection

    • @JavaHariKrishna
      @JavaHariKrishna 8 років тому +6

      In Java 1.0 we have a class called Hashtable collection, it will store objects in Key,Value pair format. So, for this class String and wrapper classes are created as immutable objects.
      In Java 1.2 more classes are added as alternative to Vector and Hashtable classes.
      I hope you got my point :-)

    • @karthikkasturi5780
      @karthikkasturi5780 8 років тому

      thankyou sir for your video..but i have a question that..we use integer also as a key in hastable but it is immutable..why?
      plz explan about this sir?

    • @JavaHariKrishna
      @JavaHariKrishna 8 років тому +2

      Reason is same
      Generally strings and numbers are used as keys hash table for maintaining values. So String object and Wrapper classes(Byte, Short, Integer, Long, Float, Double, Character, Boolean) classes are created as immutable object classes.

    • @unpopular123
      @unpopular123 6 років тому

      @@JavaHariKrishna when we use string as key in hashtable , value for that key is actually stored against hashcode of key not against key, so i think your explaination is wrong

  • @adaylightsmile7961
    @adaylightsmile7961 4 роки тому

    (wrong) --------------> ( not immutable 00:10:51 )
    [{there actually I confused}]
    in the previous diagram if the string is given as mutable
    then only we get NULL
    and only IM-MUTABLE WE GET 1 Value.
    [{ Finally whole Explanation is GOOD }]..
    :) i am here to help you by mentioning that and then concept will get helpful

  • @noth370
    @noth370 8 років тому

    After watching this video ...My soul is saying only one word awesome Hari sir............

    • @erucky21
      @erucky21 6 років тому

      your soul has malfunction

  • @umeshnadargi219
    @umeshnadargi219 5 років тому +1

    Great explaination

  • @prangshumaity9058
    @prangshumaity9058 6 років тому

    Super sir.no one can teach this point.this make your students unique from other.

  • @shekhar06sontakke
    @shekhar06sontakke 5 років тому +1

    Great explanation Sir!!

  • @manashranjan1267
    @manashranjan1267 5 років тому +1

    Thanks Sir Hari sir means Hari sir only whole team trying to convince that for pooling purpose string is immutable but Hari Krishna sir prove that why string is immutable

  • @hareesh17
    @hareesh17 8 років тому +8

    Hi Hari Krishna,
    This is a one good reasonfor String Immutability. I found few more good reasons for string immutability in StackOverflow thread.
    stackoverflow.com/questions/22397861/why-is-string-immutable-in-java
    String is immutable for several reasons, here is a summary:
    Security: parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed.
    Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues.
    Caching: when compiler optimizes your String objects, it sees that if two objects have same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object).
    Class loading: String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).
    That being said, immutability of String only means you cannot change it using its public API. You can in fact bypass the normal API using reflection. See the answer here.

    • @JavaHariKrishna
      @JavaHariKrishna 8 років тому +1

      Thank you for the valuable information Hareesh :-)

    • @AmitKumar-qh4ow
      @AmitKumar-qh4ow 7 років тому

      Dear Sir, Thanks for the Video, I want to know that if we will use s1.toUpperCase(), it will change to HK but this object will be lost because s1.toUpperCase() is not referenced by same reference s1 or some other new reference.

    • @gadaakhil
      @gadaakhil 7 років тому

      Hi Amit, That's not the case since the HashTable will still hold the reference to the lower case "hk" when we call hashTable.put("hk", 1), so it won't be garbage collected. Best Wishes.

  • @finetechie5550
    @finetechie5550 6 років тому

    Sir, since String is final and immutable, why we allowed to modified with its new object,even though we can't use previous data

  • @rajeshchalla6085
    @rajeshchalla6085 7 років тому

    good explain sir
    i u dont mind why hashcode()method and equals() override andsuppose not overriding what is problam.please explain sir

  • @meenakumari-ov9tx
    @meenakumari-ov9tx 8 років тому

    Thanq sir..your explained very neatly..it is easy to understand non IT students...please add collection videos also..

    • @JavaHariKrishna
      @JavaHariKrishna 8 років тому +4

      I will release Collection videos very soon. Actually these string concept videos are the prerequisites to Collection concept.
      In collection programming I will use all these String concepts, so first I recoded these concepts videos.

    • @135sudeep1
      @135sudeep1 8 років тому

      thanks Sir, I face this question in interview, now i can give the answer, I forget this answer because of long time. Ultimate video. eagerly waiting for your next videos.

    • @erucky21
      @erucky21 6 років тому

      i need to say your conscious is very neat

  • @rajeshgupta2413
    @rajeshgupta2413 6 років тому +1

    Great explanation sir. Thank you sir for deep explanation

  • @chrissmith2137
    @chrissmith2137 3 роки тому

    Very nice explanation. You sound like that funny Indian Guru, Mr. Nithyananda.

  • @ashoknuthalapati6727
    @ashoknuthalapati6727 8 років тому

    HI Sir, Other than string we can also use all wrapper classes as key for storing in hashmap.

  • @lastminutejava8277
    @lastminutejava8277 6 років тому

    but we always do string x="raju"; than raju is a key but where is the value to stored in hash-table can you please explain me this

  • @akhilraj5751
    @akhilraj5751 5 років тому

    very clear explanation. thanku!

  • @kuldeeptiwari-mm2cp
    @kuldeeptiwari-mm2cp 8 років тому

    sir plz once talk about singlton and its creation, uses and importance...............thank you sir

  • @kalam4868
    @kalam4868 4 роки тому

    Excellent

  • @gadaakhil
    @gadaakhil 7 років тому

    Very well explained.

  • @manmathkumarbehera4153
    @manmathkumarbehera4153 6 років тому

    superb explanation Sir..

  • @saicharan9230
    @saicharan9230 8 років тому

    proud to be your student sir

  • @georgemichael2572
    @georgemichael2572 6 років тому

    Thanks a lot ..one doubt. Can we modify string by +=operator ??

  • @ervikassharma3825
    @ervikassharma3825 8 років тому

    This is Gud way to learn Java but sir Can u plz upload MultiThreading Videos plzz Sir

  • @ganeshgulhane8814
    @ganeshgulhane8814 7 років тому

    Sir can you please make the videos on threading concept in java

  • @shaileshsaxena1587
    @shaileshsaxena1587 7 років тому

    Thanks for explanations - why string is immutable -by HasMap.Please see belwo code
    import java.util.HashMap;
    public class MutableDemo {
    public static void main(String[] args) {
    HashMap m = new HashMap();
    StringBuffer sb1 = new StringBuffer("jj");
    StringBuffer sb2 = new StringBuffer("kk");
    m.put(sb1, 1);
    m.put(sb2, 5);
    System.out.println(m);
    sb1.append('u');//performing operation on sb1
    System.out.println(sb1);//it will print jju
    System.out.println(m.get(sb1));// it is giving output as=1 which initially inserted in map
    }
    }
    out put = {jj=1, kk=5}
    jju
    1
    Note = i am able to print value of key sb1 after performing operation on it. StringBuffer is mutable.

    • @damjandjordjevic1994
      @damjandjordjevic1994 6 років тому

      haha. did you figure it out, or did you forget about this comment?

  • @pravinkottawar
    @pravinkottawar 7 років тому

    Sir,
    Integer i = 20;
    i = 30;
    System.out.println(i);
    Output is 30 so how can Integer is immutable ?

    • @richcohen5936
      @richcohen5936 7 років тому +1

      wrapper classes represent primitive types, and primitive types are mutable. No they're not (and String isn't a primitive). But since primitive types aren't objects anyway, they can't really be called mutable / immutable in the first place.

  • @digitallearning-29
    @digitallearning-29 7 років тому

    thanku so much sir....plz make these type of videos,..all the best sir...

  • @challarajesh1815
    @challarajesh1815 7 років тому

    good explanation. thank u sir
    please can provide the why eaquals() and hashcode() method and why override both methods

  • @girinani435
    @girinani435 7 років тому +1

    you are one of the best in Ameerpet Institutes, Nice explanation , not only explanation, also you are trying to motivate

  • @piyush12121
    @piyush12121 7 років тому

    We can create our custom class and use it as a key by overriding hashCode() and equals() method. What you said might be part of the reason but I don't believe it's true. Do you have any reference to SUN Micro systems claiming what you're saying?
    Did you even google the answer to this question ?

    • @JavaHariKrishna
      @JavaHariKrishna 7 років тому

      Dear Piyush Chaudhary,
      you are talking about custom object, I am talking about String object. Did you find is there any wrong in my explanation or did you find any explanation from sun docs about why strong is immutable, pls share us we are ready to learn😊

    • @piyush12121
      @piyush12121 7 років тому

      @Hari Krishna By that logic "Integer" class is also mutable because of this reason. But wait, there is no Integer pool like String. I think your explanation is hilarious. Try putting your logic for this answer on StackOverflow and see how many up-votes you get.

    • @JavaHariKrishna
      @JavaHariKrishna 7 років тому

      Hi Piyush Chaudhary,
      I did not say Sting is immutable because for supporting String pooling. I gave different explanation. And thanks for referring stackoverflow site, pls check other comments one of the viewer also given comment on this video by supporting my explanation is correct with proof from stackoverflow site
      in this video I want to address pooling is not the main reason for making objects immutable, if so other objects wrapper classes and File class, no need to be created as immutable.

    • @piyush12121
      @piyush12121 7 років тому +1

      Perhaps you did not understand what I said. I know you said String pooling is there because String is immutable. So by that logic they should have also implemented Integer pooling because Integer class is also immutable.
      Please read that guy's comment again. That guy never gave any proof. He just gave a URL which contains good reasons for string being immutable.

    • @jvsnyc
      @jvsnyc 4 роки тому +1

      @@piyush12121 I don't think it is just a coincidence, but it is funny. The reason that Integer io = new Integer( intValue ); is deprecated in modern versions of Java, in favor of Integer io = Integer.valueOf( intValue ); is precisely because they now implement.....INTEGER POOLING!

  • @divyangshah99
    @divyangshah99 5 років тому

    this is absurd , cant we directly pass s1 while getting the value , that way even if it has changed , will give the correct value ,

  • @Dyslexic_Neuron
    @Dyslexic_Neuron 5 років тому

    what if we write s1=s1.toUpperCase() ??

  • @skajharuddin6810
    @skajharuddin6810 2 роки тому

    He is best

  • @manjug1559
    @manjug1559 7 років тому

    Good Explanation sir..

  • @kalyankumar2843
    @kalyankumar2843 7 років тому

    Superb explanations sir

  • @naseemahmad7897
    @naseemahmad7897 8 років тому

    thanks sir plz upload collection class video

  • @ankittiwary3712
    @ankittiwary3712 8 років тому

    great explanation!!

  • @kunalvarade29
    @kunalvarade29 6 років тому

    How can we use object as key in Map?

  • @arjunganesan4991
    @arjunganesan4991 6 років тому

    thank you so much.. you are awesome sir..

  • @subrahmanyampenkey1126
    @subrahmanyampenkey1126 8 років тому

    Perfect explanation

  • @supriyasingh763
    @supriyasingh763 7 років тому

    But we can pass s1 in the get() method

  • @jvsnyc
    @jvsnyc 4 роки тому

    A few people seem to be confused by the fact that he is showing "Here's what would happen if String wasn't immutable and .concat() or .toUpperCase() worked in place, instead of the world we do live in where String IS immutable and those methods make a new string somewhere else and give you back a reference to it (unless it already existed in String Pool of course)." On television and in movies, when they show something different from reality they make the screen all blurry or wavy to show it is just imagination, then clear it away when they come back to reality. Java Strings are immutable, functions that work on them make and return new objects. All kinds of weird and bad things that never happen to us in Java would happen otherwise. You should be very careful when using Maps to use keys that make sense. This little video is pretty important, and the fact that people came up with a few additional reasons is good but doesn't detract from this presentation.

  • @Rakeshkumar-fn1sv
    @Rakeshkumar-fn1sv 8 років тому

    Thank you sir provide this video

  • @ArunraajSingh
    @ArunraajSingh 7 років тому

    *your theory is wrong sir,*
    get () method can pass only key type parameter. Even if string is immutable, get() method will return always null value until it passes a key-integer type value.
    get(2) = this will print "Ravi"
    get("hk") = will always print null

    • @anulearntech
      @anulearntech 7 років тому

      what is key type parameter?
      but key doesn't need to be integer only, it can be of any type including string, in fact you could even have a user defined object as a key.

    • @ArunraajSingh
      @ArunraajSingh 7 років тому

      i didnt say that key can only be integer type. I said
      "get() method will return always null value unless it passes a key-integer type value."

    • @anulearntech
      @anulearntech 7 років тому

      Arun Singh how can get method pass, you will jave to pass na.
      and ill have to only pass a string to it if at declaration of collection is made in such a way
      hashmap a = new hashmap();
      a.put("aap",1);
      a.put("bjp",2);
      a.put("cong",3);
      sysout(a.get("aap")); //should print 1

    • @sandyrockz823
      @sandyrockz823 7 років тому

      your logic right but its different in MAP INTERFACE.. instead of commenting straight away you should check it once.. in map if you are using get () method you need to give KEY which will give the value of the key.. Mr Hari krishna is very experienced java trainer in naresh it

  • @nagabhushanamgaddam6292
    @nagabhushanamgaddam6292 8 років тому

    Nice explanation sirr

  • @akhileshkumarbhagat9319
    @akhileshkumarbhagat9319 7 років тому

    Amazing explanation

  • @sureshg8326
    @sureshg8326 6 років тому

    You are discussed only one point of string class Immutable. there are other reasons also like

    • @yuvrajkthorat
      @yuvrajkthorat 6 років тому

      Yes...agree to many of you....this is only adavatage of string being Immutable.....string class did not become due to Hashmap

    • @harikrishnahkb
      @harikrishnahkb 5 років тому

      Yes Suresh, I agreed with you, but in all cases you addressing are internally uses (key,value) only. So for easy understanding I just took Hashtable as an example.

  • @sagarikadas1196
    @sagarikadas1196 8 років тому

    Thank you so much sir

  • @sunkararamarao3254
    @sunkararamarao3254 6 років тому

    Super sir.....vvvvvvvnice.....

  • @saikrishnahari
    @saikrishnahari 8 років тому

    Nice sir good explanation

  • @yuvanagasai3339
    @yuvanagasai3339 7 років тому

    Sir plzz upload video on java.util.regex

  • @Ravikumar-gj6qw
    @Ravikumar-gj6qw 6 років тому

    Super explanation Sir tq

  • @tunikisandeep7086
    @tunikisandeep7086 8 років тому

    Awesome !!

  • @devireddyfavreddy4785
    @devireddyfavreddy4785 7 років тому

    What about int

  • @rubenflores2318
    @rubenflores2318 7 років тому +1

    Muy bueno, gracias (Y)

  • @NaveenKumar-bn5ov
    @NaveenKumar-bn5ov 7 років тому +1

    Nice explanation sir :)
    We want you to upload all core java tutorials.

  • @arpitmandlik1312
    @arpitmandlik1312 7 років тому

    Thank you sir ji

  • @UserShivaNice
    @UserShivaNice 6 років тому

    You rocks sir.never expected this kind of superb explanation..Great..

  • @srikanth29
    @srikanth29 6 років тому

    Thank u sir. Very helpful

  • @mallikarjun100
    @mallikarjun100 7 років тому

    nice sir

  • @meghathakur7660
    @meghathakur7660 6 років тому

    Before attending core Java I were hate with core Java BT now I m fan of u sir

  • @KrishnaGangaraju
    @KrishnaGangaraju 7 років тому

    because of u guys lot of scrap in it from Hyderabad

    • @JavaHariKrishna
      @JavaHariKrishna 7 років тому

      Krishna Gangaraju
      can you pls share your thought on this topic, so that all we will learn from your ideas too. Just leaving one comment may not justify, try to correct my mistake if any and Help others to learn 😊

  • @faheemahmadofficial7701
    @faheemahmadofficial7701 5 років тому

    everything ends with a with this person ... personA stringA...etc

  • @erucky21
    @erucky21 6 років тому

    no offence but why dont you teach in your native tongue or in a language you are good

  • @maheshagga9438
    @maheshagga9438 3 роки тому

    Nice explanation sir

  • @niteeshchandanshire4381
    @niteeshchandanshire4381 5 років тому

    Awesome explanation sir

  • @manojkumar-ul6ey
    @manojkumar-ul6ey 5 років тому

    Awesome explanation

  • @divyangshah99
    @divyangshah99 5 років тому

    this is absurd , cant we directly pass s1 while getting the value , that way even if it has changed , will give the correct value ,

  • @akhileshkumarbhagat9319
    @akhileshkumarbhagat9319 7 років тому

    Unique explanation.