Home > other >  In Java Solution class and now we create object Solution s=new Solution(); Why we can not do Solutio
In Java Solution class and now we create object Solution s=new Solution(); Why we can not do Solutio

Time:01-21

I want an explanation of my question.

class Solution {

    public static void main(String []args) {
        String str = "Ankdg";
        Solution s = "dsads"; //is it possible
    }
}

CodePudding user response:

Refer to Java Language Specification for Java 17, section 3.10.5 (String Literals)

A string literal consists of zero or more characters enclosed in double quotes.

A string literal is always of type String

Note also that String is a final class so you can't extend it.

CodePudding user response:

String str = "Ankdg"; Here we are assigning the string object as literals. This feature is present in java to make memory efficient. If we assign string object as literals, it will be stored in String pool memory (A part of java heap memory) and only unique values will be stored. So when another variable is assigned with same value, it still points to same object in string pool

i.e

String str2= "Ankdg" String str="Ankdg" Both str2 and str will poins to same location in string pool.

String str = new String("Ankdg") [If an object is assigned in this way, it leads to create the object in memory irrespective of whether it is present in memory or not. Also, it will stored in heap memory and not in string pool]

And coming to your question, Solution s = "dsads"; //is it possible

It is not possible, because the feature is not applicable for User defined classes

Hope that answers your question :)

  •  Tags:  
  • java
  • Related