Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
}
like image 869
BenMansourNizar Avatar asked Dec 25 '13 12:12

BenMansourNizar


People also ask

What is the difference between long integer and double?

Long is for integer numbers. Double is for real numbers (i.e. numbers which have decimal points in them!).

Why are numbers sometimes stored as strings?

Telephone numbers need to be stored as a text/string data type because they often begin with a 0 and if they were stored as an integer then the leading zero would be discounted.

Is long double a primitive data type?

Primitive data types - includes byte , short , int , long , float , double , boolean and char.

Why do we use int instead of long?

Traditionally, the "int" type is the "natural" type for the processor - i.e., it's the size of the processor's registers. This can be 4, 8, 16, 32... bits, but usually the processor can handle it as fast as possible. Type "long" is for when you need more precision, even at the expense of slower code.


2 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.

like image 75
A4L Avatar answered Sep 18 '22 23:09

A4L


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.

like image 34
Mureinik Avatar answered Sep 18 '22 23:09

Mureinik