+ 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! šŸ™‚

14th May 2021, 10:54 AM
Surendra Sandun
Surendra Sandun - avatar
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++
14th May 2021, 11:38 AM
Hape
Hape - avatar
+ 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";
14th May 2021, 12:06 PM
Ciro Pellegrino
Ciro Pellegrino - avatar
+ 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
14th May 2021, 12:12 PM
Ciro Pellegrino
Ciro Pellegrino - avatar