-2

When learning about String literals vs String objects, I came across the fact that there are 2 possible ways to instantiate a variable of type String

//Using literals
String s1 = "text";

//Using constructor
String s2 = new String("text");

I was wondering if it is possible to somehow create an class and instead of instantiating it with a constructor, one could instantiate it using a literal

This is what I mean

class Value {
    int value;
    //Some methods
}

Value val = 10; //Program automatically sets val.value = 10
Dev Sharma
  • 21
  • 1
  • 3

3 Answers3

1

No, this isn't possible. The closest thing that Java has to this is autoboxing, where you can write something like:

Integer val = 10;

and the compiler automatically turns that assignment into one involving the primitives cache (there is a fixed set of primitive values that are guaranteed cached: boolean true/false, byte and char values 0-127, and int values -128 to 127, As per the spec. Although a JVM may, and almost always does, have a more extensive primitives cache than that).

Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
Richard Fearn
  • 25,073
  • 7
  • 56
  • 55
1

No. Although you can write String s1 = "text";, the java compiler automatically creates an object. This may be the reason to misguide you. But it happens inside.

dilanSachi
  • 562
  • 6
  • 14
1

Most of the scenarios its not possible. Creating a String like you have and assigning a int value both are using constructors even we can't see it directly.

How ever there are rare scenarios like this. Please read this. Will be good to add to your knowledge :)

Sandeepa
  • 3,457
  • 5
  • 25
  • 41