+ 2
How does java create String object by just assigning a String?
How does java create String object by assigning a String. i.e. String str = "some string" (Instead of String str = new String("some string")) I know this way is also valid to create a string. But If I want to create Object I have to create it with new key word. Is it possible to create object with assigning number or a string. Like, MyObject obj = "this is my object"; I hope you can help me. Thank you! š
3 Answers
+ 2
No that is not possible. The Java language just handles strings in a special way. For example the + operator works for string concatenation and it is also not possible to use this for own classes as it is possible for example in C++
+ 1
I would add
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
"... All string literals in Java programs, such asĀ "abc", are implemented as instances of this class. ..."
so string literals in Java are String objects, so you can assign them to an object of type String which is what you do with String s = "hello";
+ 1
different speech for the wrapper classes for numbers in which there is a transparent boxing and unboxing activity. in this case you can directly assign a numeric literal to an object of a numeric class
Integer intObj=3;
https://docs.oracle.com/javase/tutorial/java/data/numberclasses.html