4

In java it's possible to do that;

String a = "aaaa";
Integer b = 1;

and also that;

String a = new String("hello ");
Integer ad = new Integer(8);

first question : why is that possible and what's name of this standard ?

second question : explain how to work this special case ?

Third question : Is possible to do the same with my own object ? for example :

Person p = "Med"; in place to do that Person p = new Person("Med");

Med Elgarnaoui
  • 1,612
  • 1
  • 18
  • 35
  • 5
    `String` and primitives are special, you can initiialize them with literals. You can't do that with any other classes. – Arnaud Sep 25 '18 at 10:16
  • 4
    No, not really. This is a feature of the compiler. Note that a `Person` could be a complex object. In such cases, it makes no sense of using an assignment operator. The closest you could get in achieving this is using DSLs. New JVM languages provide these features. – Prashant Sep 25 '18 at 10:17
  • 2
    https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html The reason the first integer assignment works, provided you mean `Integer`. – matt Sep 25 '18 at 10:20
  • Thanks but why String don't have a primitive and works like that ? – Med Elgarnaoui Sep 25 '18 at 10:33
  • see also: [Is autoboxing possible for the classes I create?](https://stackoverflow.com/questions/17619724/is-autoboxing-possible-for-the-classes-i-create) – Jesper Sep 25 '18 at 10:34
  • @Jesper why String don't have a primitive type and works fine ? – Med Elgarnaoui Sep 25 '18 at 10:41
  • Because `String` is treated specially by the Java compiler. There is no way to do a similar thing with your own classes. – Jesper Sep 25 '18 at 10:43
  • Ok Thanks for your help ? – Med Elgarnaoui Sep 25 '18 at 10:44
  • Read about `String Pool` in Java : https://stackoverflow.com/questions/2486191/what-is-the-java-string-pool-and-how-is-s-different-from-new-strings – krpra Sep 25 '18 at 11:13

0 Answers0