About java.lang.String, why String is special in java – String tutorial

Java

Video is ready, Click Here to View ×


java.lang.String is a very special class in java. There are a lot of special characterstics associated with String. This makes it a favorite core java interview question topic. Here I discuss some interesting facts about java.lang.String

42 thoughts on “About java.lang.String, why String is special in java – String tutorial

  1. Thanks for this video. I had a question, given strings are cached in string pool I am correct in saying that those strings will not be garbage collected? Some people mention that only string literals and strings which are interned are cached in string pool is that true. Say String sFirstName = objUser.getFirstName() will the value of sFirstName be cached or not ?

  2. Thank you – for this. You mentioned how a String's hashCode is cached once it has been 'interned' – but you've not mentioned how a check is done for a String existing on the current string pool. Doesn't this involve calculating some hash code?

  3. Hi Ranjith,

    I have a doubt on one statement that you have made – String "Caches the hashcodes". also mentioned that it will be helpful in HashMaps.

    Consider the following:

    String s1 = "Hello";
    String s2 = "Hey";
    String s3 = "Hello";

    Map<String, Integer> m = new HashMap<>();

    m.put(s1, 1); // Here it computes the hashcode of s1 (lets say h1 ) and cached

    m.put(s2, 2); // Here it computes the hashcode of s2 (lets say h2) and cached

    now as per my understanding of your statement, if we try to do m.put(s3,3) it will not compute the hash code again. Instead, it will get it (h1) from "hashcode cache" as s1 and s3 are equal.

    My question is how does it know that the hashcode (h1) is of s1/s3?

    Will it maintain any map between String and hashcodes so that as s1.equals(s3), h1 is returned.

    Please clarify me if I am interpreting it wrong,

  4. your teaching was super amazing very clear and in depth …do make some videos on tricky java interview questions like
    1. FINDING WHITE SPACES IN A GIVEN SENTENCE
    2.FINDING NO OF DUPLICATE WORDS IN A SENTENCE
    3. AND SOME INTERSTING CONCEPTS USIGN ARRAYS..

Leave a Reply

Your email address will not be published. Required fields are marked *