For example the following is syntactically correct code
Double number = 10.0;
Is it possible to define my own class such as Price
Price myPrice = 10.0;
Actually compiles ?
Java User-defined data types are the customized data types created by the developers by exploiting the special features offered by the Java language. This customized data type combines data types of a group of data elements with homogenous or assorted data types.
What is a Primitive Data Type? The predefined data types of Java are known as primitive data types. The agenda of these data types is to determine the size and type of any values. It includes eight primitive data types: byte, long, short, int, double, float, char and boolean.
As the Java documentation explains: A primitive type is predefined by the language and is named by a reserved keyword. Show activity on this post. Simply No, You can not create primitive datatype. Primitive datatype means which are provided and existed in language feature.
The main reason primitive data type are there because, creating object, allocating heap is too costly and there is a performance penalty for it. As you may know primitive data types like int, float etc are most used, so making them as Objects would have been huge performance hit.
Auto-boxing and auto-unboxing only works with primitives. The concept you are talking about is similar to C++ conversions. Unfortunately, there is no such thing in Java. The best you can do is
Price myPrice = new Price(10.0);
No, you can't define your own primitive types for numerical quantities.
Declaring Price myPrice
means that the variable myPrice will be of type Price and will be used to as its instance.
You can have following valid.
Suppose you declare variable myPrice
of type Price
. Some instance variables can be accessed via that myPrice
reference.
Price myPrice = new Price();
myPrice.value = 10.0;
myPrice.currency = "Dollar";
etc ....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With