Java Strings: “String s = new String(”silly“);”

前端 未结 23 2391

I\'m a C++ guy learning Java. I\'m reading Effective Java and something confused me. It says never to write code like this:

String s = new String(\"silly\");         


        
23条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 14:47

    If I understood it correctly, your question means why we cannot create an object by directly assigning it a value, lets not restrict it to a Wrapper of String class in java.

    To answer that I would just say, purely Object Oriented Programming languages have some constructs and it says, that all the literals when written alone can be directly transformed into an object of the given type.

    That precisely means, if the interpreter sees 3 it will be converted into an Integer object because integer is the type defined for such literals.

    If the interpreter sees any thing in single quotes like 'a' it will directly create an object of type character, you do not need to specify it as the language defines the default object of type character for it.

    Similarly if the interpreter sees something in "" it will be considered as an object of its default type i.e. string. This is some native code working in the background.

    Thanks to MIT video lecture course 6.00 where I got the hint for this answer.

提交回复
热议问题