Home » Java » Why it's possible to instantiate String and not possible for Number(Long,Double,Integer…)?

Why it's possible to instantiate String and not possible for Number(Long,Double,Integer…)?

Posted by: admin December 28, 2021 Leave a comment

Questions:

Hi why it’s possible to instantiate String and not possible for Numbers .I have made an example for that

public static void main(String[] args) throws InstantiationException,
        IllegalAccessException {
    String a = "s";
    String newInstance = a.getClass().newInstance();
    System.out.println(newInstance);
    Double b = 0d;
    Double newInstance2 = b.getClass().newInstance();
    System.out.println(newInstance2);
}
Answers:

Calling newInstace invokes the default constructor. Double does not have one.

If you want to instantiate using reflection then you have to get one of the Contructors of the class using Class.#getConstructor by passing it the appropriate argument types and then call its method Constructor#newInstance by passing it the appropriate arguments.

###

java.lang.String has an empty constructor (calling new String() is the same as calling new String("")).
Numbers, on the other hand, don’t have no-arg constructors (what would the value of a new Double() be anyway? there is no equivalent to an “empty number”), and thus can’t be invoked this way, even not by reflection.