Primitive Data Type
Primitive means “very basic”. It is simple and normal types. Value of primitive is stored in memory location or memory location is given to variable.
For example if you want to store 50 in memory location:
0 1 2 |
int value = 50; |
Primitive data types are further divided into Numeric and Non numeric data types. Under Numeric data types. Int and float. Under non Numeric data types Char and Boolean.
Type | Contains | Default | Size | Range |
---|---|---|---|---|
boolean | true or false | false | 1 bit | NA |
char | Unicode character | \u0000 | 16 bits | \u0000 to \uFFFF |
byte | Signed Integer | 0 | 8 bits | -128 to 127 |
short | Signed Integer | 0 | 16 bits | -32768 to 32767 |
int | Signed Integer | 0 | 32 bits | -2147483648 to 2147483647 |
long | Signed Integer | 0 | 64 bits | -9223372036854775808 to 9223372036854775807 |
float | IEEE 754 Floating Point | 0.0 | 32 bits | approximately ±3.40282347E+38F (6-7 significant decimal digits) Java implements IEEE 754 standard |
double | IEEE 754 Floating Point | 0.0 | 64 bits | approximately ±1.79769313486231570E+308 (15 significant decimal digits) |
Non Primitive Data Type
It is useful when using them as generic types(including Collection classes, such as lists and maps) or when you want to transform them to other type without implicit casting (for example Integer class has methods
Non Primitive data types are also known as Reference which is created by the user itself.
012
Integer value = new Integer(50);
Conclusion
In Item 5, of Effective Java, Joshua Bloch says
Prefer primitives to boxed primitives, and watch out for unintentional autoboxing.
012345678
public static void main(String[] args) { Long sum = 0L; for (long i = 0; i < Integer.MAX_VALUE; i++) { sum += i; } System.out.println(sum); }
0 1 2 |
Integer value = new Integer(50); |
0 1 2 3 4 5 6 7 8 |
public static void main(String[] args) { Long sum = 0L; for (long i = 0; i < Integer.MAX_VALUE; i++) { sum += i; } System.out.println(sum); } |
This program gets the right answer, but it is much slower than it should be, due to a one-character typographical error. The variable sum is declared as a Long instead of a long, which means that the program constructs about 2^31 unnecessary Long instances (roughly one for each time the long i is added to the Long sum). Changing the declaration of sum from Long to long reduces the run time from 43 seconds to 6.8 seconds on my machine.
The fact is it is slower to use the Object wrappers for primitives than just using the primitives. You’re adding the cost of object instantiation, method calls, etc. to things that you use all over the place. You use the wrappers when you need to add things to collections.