Use of the difference between Double and double, to avoid the pit

1. Description

If the code is not a problem yesterday, I probably would not notice the difference between Double and double use;

Question 1 : If an int data type of cast can turn into a double, but I accidentally wrote double Double (main problem is I do not understand the use of Double and double, confused) in the project;
then error: can not cast 'int' to 'java.lang.Double', examples are as follows:

The error can be seen that a Double java class: java.lang.Double; is the basic data type double

Question 2 : Item inspection found a type of double data can be converted into a Double, and not being given

        double smD = 2.22;
        System.out.println((Double)smD);
复制代码

Indeed, in jdk1.5 above, (automatic automatic packing and unpacking) Double double wrapper class is, if converted into double Double type data, then this data can be used in all methods Double ;

Auto-boxing and auto-unboxing:

Double d =new Double(dou)可将double基本数据类型装箱为Double包装类
double dou =d.doubleValue()可将Double的包装类拆箱为基本数据类型
复制代码

And double the difference 2.Double

  • Double is a class object is created, stored on the heap;
  • basic data type is a double, reference is created is stored in the stack;
  • Double is a double package type, built many ways to achieve String to double conversion, and acquires the attribute values (MAX_VALUE, SIZE, etc.) type double
  • Double basic methods:

3.java basic data types

Since the basic data type conversion is not familiar with, so look back, do a little summary.

3.1 automatic type conversion

Defined : small numbers indicate the type of data can be automatically converted into a wide range of data types;

Data overflow : multiplying two int, int result is outside the range expressed.
Solution : a first generally converts data into a wide range of data types and other data types and then calculates;

问题:
int count = 100000000;
int price = 1999;
long totalPrice = count * price;
输出结果为负数;

解决:
int count = 100000000;
int price = 1999;
long totalPrice = (long) count * price;

复制代码

3.2 Mandatory conversion

Conversion to a forced display data type to another data type, data overflow careful attention to :

int ii = 300;
byte b = (byte)ii;
复制代码

300 has exceeded the scope of the byte type represents, it will be converted into a digital meaningless.

3.3 type promotion

The so-called type promotion refers to data in a variety of different types of expressions, the type is automatically told of a large range of data types to enhance the value of

long count = 100000000;
int price = 1999;
long totalPrice = price * count;
price 为 int 型,count 为 long 型,运算结果为 long 型,运算结果正常,没有出现溢出的情况。
复制代码

Guess you like

Origin juejin.im/post/5d744e406fb9a06b1b19e55f