If a constructor is the only way to create the object of a class then how String name = "Java"; is able to create an object of String class even without using constructor.
-
Please check this and see it helps. https://stackoverflow.com/questions/19941825/purpose-of-a-constructor-in-java – LearningEveryday Apr 24 '20 at 19:45
-
1The compiler built one and put it in the .class constants pool. – David Zimmerman Apr 24 '20 at 19:46
4 Answers
No. Constructor is not the only way.
There are at least two more ways:
Though in case with your example - neither of these is used.
In this case Java uses string pool

- 2,775
- 4
- 18
- 33
There is another way of creating objects via
Class.forName("fully.qualified.class.name.here").newInstance()
Class.forName("fully.qualified.class.name.here").getConstuctor().newInstance()
but they call constructor under the hood.
Other ways to create objects are cloning via clone()
method and deserialization.

- 19,170
- 9
- 17
- 42
I suppose in a loop-hole type of way you could use the class object too:
// Get the class object using an object you already have
Class<?> clazz = object.getClass();
// or get class object using the type
Class<?> clazz = Object.class;
// Get the constructor object (give arguments
// of Class objects of types if the constructor takes arguments)
Constructor<?> constructor = clazz.getConstructor();
// then invoke it (and pass arguments if need be)
Object o = constructor.newInstance();
I mean you still use the constructor so it probably doesn't really count. But hey, its there!

- 313
- 2
- 8
YES, each time a new object is created, at least one constructor will be invoked.
Look at this tutorial, this will explain all with objects, classes and constructors.

- 4,222
- 8
- 24
- 34
-
1That is only correct for the "regular" ways. Neither cloning nor deserialization actually go through a constructor. They use Java black magic to bypass all of those mechanisms and they use mechanisms built directly into the language instead. – Zabuzard Apr 24 '20 at 19:53