Java Fundamentals (i) deep parsing of basic types

Source: Internet
Author: User

I. Introduction to BASIC Types

Two guidelines for basic types:

    • In Java, if you do not specify a type for an integer, the default is int, the type is not specified on a decimal, and the double type is the default.
    • Basic types are small to large and can be converted automatically, but from large to small, you need to force type conversions.

The number of bytes taken:

Byte:1 a byte;
Char:2 a byte;
Short:2 a byte;
Int:4 a byte;
Long:8 a byte;
Float:4 bytes; (6 decimal places, exponent: 10^-38~10^38; Range:)
Double:8 a byte;

Char:java with "\u four-bit hexadecimal digits (even if \u appears in the note, after
followed by not 4 16 digits, also error) "means converting characters to their corresponding Unicode encoding, or you can assign values such as Char c=" \u0000 ", the default initialization value of char, the null character of Unicode

Suffix of the base type:

Long:l or L
Float:f or F;
Double:d or D

Second, type conversion

?? As mentioned earlier, the type is large to small and is required to be cast. This does not mean that the user is forced to cast manually-that is, implicit conversions. The explicit point of implicit conversion is that the compiler does the casting and does not require the user to write the code for the cast. The first two dots below are the special implicit type conversions.

The type conversions discussed in this section do not include conversions of types from small to large, and other confusing type conversions are discussed.

1. Literal constants of type int are converted to variable types lower than int type

?? The so-called literal constants are the values themselves, such as 5, 7, "AA" and so on. Let's look at an example:

public static void main(String[] args) {    int a = 8;  //8是字面常量    byte b = 9;  //9是字面常量    char c = 9+5;//常量表达式    short s = (short) (c+10); //变量表达式,需要显式强制转换}

?? The above code is compiled and is correct. B is a byte type, but b=9 does not need to be explicitly manually cast, because 9 is a literal constant and is done automatically by the JVM.
?? Let's take a look again c=9+5 , C is a char type, 9+5 gets the result is the int type, but also does not need to explicitly manually cast. This is because 9+5 is a constant expression, so the result has been computed by the compiler during compilation, that is, after compilation, the equivalent of C=14, which is also a literal constant, so it can be implicitly converted. Similarly, the short s = (short) (c+10); child cannot be implicitly converted, because the expression is not a constant expression, contains a variable and can only be completed during run time, so it is necessary to manually cast.

xxx literal Chang-type conversion Restrictions:

    • The type conversion is forced manually when the size of the XXX literal constant exceeds the range that the target type can represent.
byte b = 128;//编译错误,128超出byte类型所能表示的范围byte c = (byte)128;//编译通过
    • For arguments to be passed, you must explicitly type-cast, explicitly cast

Compiler sub So this requirement, in fact, in order to avoid the implicit conversion of the method overload and the small type auto-turn large type conflict.

public static void main(String[] args) {    shortMethod(8);//编译错误    shortMethod((short)8); //编译通过    longMethod(8);//编译通过,因为这是小类型变成大类型,是不需要强制类型转换的}public static void shortMethod(short c){    System.out.println(c);}public static void longMethod(short l){    System.out.println(l);}
    • Special case for Char type: The following is a fine story.
2. Implicit conversion of composite operators

?? * The composite operator (+ =,-=, =,/=,%=) is a type that can be automatically cast to the left for the type of the right expression * *

public static void main(String[] args) {    int a = 8;      short s = 5;     s += a;    s += a+5;   }

??s+=a、s+=a+5; expression evaluates to an int type, but does not require a manual cast. In fact, if it is an anti-compilation of the code of the class file, you will find s+=a, in fact, is the compiler processed into a

s=(short)(s+a)

That is, the implicit type conversion of all composite operations is actually the code that the compiler automatically adds type conversions to.

Therefore, the implicit conversion of the compound operator is not limited by the implicit conversion of the XXX literal constant, because the former can only occur during the compiler, and the latter is the code that the compiler actually complements the type conversion.

3. Special types of Char

?? The char type is a relatively special presence in the base class. This peculiarity is that the char type is an unsigned type, so the char type and other base types are not the relationships between the subset and the parent set (the other types are signed types). That is, the conversion between the char type and byte, short requires an explicit coercion of type conversions (small types are automatically converted to large type failures).

?? Also, because the char type is an unsigned type, the limit for implicit conversions for XXX literal constants, including not only literal constant values, cannot exceed 2 bytes, but also literal constant values cannot be negative

 byte b = 2; char c = 2;//编译通过      c = 100000000000;//编译不通过,超出char类型的范围 char d = -2//字面常量为负数,编译不通过      d = (char)-100;//编译通过 char f = (char)b; //编译通过,必须显式的强制类型转换      f = b;//编译不通过,不能隐式转换 int  i = c;//编译通过,可以不需要强制类型转换 short s = (short) c;//编译通过,必须显式地强制类型转换

?? The char type is an unsigned type, which is also represented when it is converted to an int type, that is, thechar type is expanded in an unsigned manner, and the extension is filled with 0. Let's look at an example:

public static void main(String[] args) {    short s = -5;    char c = (char)s;     System.out.println(c==s);  //false    System.out.println("(int)c = "+(int)c); //转换成int类型,值为65531    System.out.println("(short)c = "+(short)c); //-5    System.out.println("(int)s = "+(int)s);//-5}

Operation Result:

False
(int) c?=?65531
(short) c?=?-5
(int) s?=?-5

?? from the above results, it is found that the char type C and the short class s actually store bytecode content is the same, but because the former is unsigned, so the result of expanding into int type is 65531, instead of-5. operator = = Compares the values that they extend to the int type, so it is fasle.

For type conversion of char types, you can summarize the following points:

    • The conversion of char type to byte and short requires explicit strong-type conversion.
    • For numeric values that are negative, you need to explicitly force type conversions, especially in the case of an implicit conversion of the XXX literal constant.
    • The char type is converted to int, and long is a rule that conforms to the small type to large type, that is, there is no need to force type conversions.
4. Type of the result of the operation

?? In Java, the type of an operation result is the highest type of equality in an expression, such as:

char cc = 5;float dd = 0.6f+cc;//最高类型是float,运算结果是floatfloat ee = (float) (0.6d+cc);//最高类型是double,运算结果也是doubleint aa = 5+cc;//最高类型是int,运算结果也为int

?? However, for operations with the highest type of byte, short, and char, the run result is not the highest type, but the int type . In the following example, the highest type of the C and D operations is char, but the result of the operation is int, so you need to force the type conversion.

 byte b = 2; char a = 5; char c = (char) (a+b);//byte+char,运算结果的类型为int,需要强制类型转换 int  

In summary, there are two properties of the type of operation results in Java:

    • The type of the result of the operation must be of type int or int type.
    • The highest type is lower than the int type, and the result of the operation is int. Otherwise, the result of the operation is the same as the highest type in an expression.
Three, floating-point number type 1. Introduction to floating-point types

?? As we all know, the conversion of a long type to a float type does not require coercion of type conversions, that is, a long type is a small type and has a smaller range than the Flaot type. However, the flaot accounted for only 4 bytes, while long accounted for 8 bytes, and the long storage space was larger than the float type. What this is all about, we will analyze it carefully.

?? Floating point numbers are used in the IEEE (Institute of Electrical and Electronics Engineers) format. A floating-point type is represented by a sign bit, exponent, and significant number of digits (mantissa). Be aware that the mantissa is the highest

In Java, the structure of float and double is as follows:

type sign Bit exponential field valid bit fields
Float 1 guests 8 Guests 23 Guests
Double 1 guests 11 Guests 52 Guests

sign bit: 0 is positive, 1 is negative;
exponential field: unsigned, float has an offset of 127 (that is, float has an exponential range of -126~127,), double
valid bit field: unsigned;

2. Two areas of floating-point types that need attention

1) The value of the stored decimal may be a fuzzy value

public static void main(String[] args) {    double d1 = 0.1;    double d2 = 0.2;    System.out.println(d1+d2 == 0.3);    System.out.println(d1+d2);}

Operation Result:

False
0.30000000000000004

?? The result of this operation is not an error. This is because the binary can not be used to accurately store 0.3, which is an infinite loop value, similar to the 10 binary 1/3. Not only 0.3, a lot of decimals are not accurate to use floating point type, in fact, this is determined by decimal to binary binary algorithm, decimal decimals to multiply by 2, know that the final result is an integer is the last binary value, but this may not get an integer, So the final result may be an infinite value, and the floating-point type cannot represent the

?? but for integers, within the valid range of floating-point numbers, they are accurate. Also, because of the conversion algorithm: decimal integer to binary algorithm is constantly on 2 to find the remainder, so there is no infinite value of the case;

2) The effective bit and precision of floating-point number

?? A floating-point type can represent a finite number of valid bits, so even integers, as long as they exceed the valid digits, can only store similar values, that is, the value of the least significant bits will be lost, resulting in loss of precision.
?? the binary valid bits of type float are 24 bits, corresponding to the decimal 7 to 8 digits, and the binary 53 bits of the double type, corresponding to the decimal 10 to 11 digits.

A double, float type can represent a wider range than an int, a long type, or a floating-point type to a large type. However, does not perfect the surface of xxx, floating-point type of precision loss will cause some problems.

public static void main(String[] args) {    int a = 3000000;    int b = 30000000;    float f1 = a;    float f2 = b;    System.out.println("3000000==3000001 "+(f1==f1+1));    System.out.println("30000000==30000001 "+(f2==f2+1));    System.out.println("3000000的有效二进制位数:"+ Integer.toBinaryString(a).length());    System.out.println("30000000的有效二进制位数:"+ Integer.toBinaryString(b).length());}

Operation Result:

3000000 = = 3000001? false
30000000 = = 30000001? True
3000000 Effective bits number:? 22
30000000 Effective bits number:? 25

?? The above example is a good illustration of the consequences of the loss of precision: 30000000==30000001 The comparison is actually true. The reason for this result is that 30000000 of the effective bits number is 25, more than the effective bit of float can be expressed 24 bits, the last one is abandoned, so that the 1 is also abandoned in the first add, so 30000000 plus one operation before and after the floating point is the same.

?? Of course, is not beyond the floating point of the effective bit can not be accurately expressed, in fact, the main thing is the most effective bit and the lowest non-0 effective bit between the "gap", if the gap in the floating point of the significant number of digits, the natural can be accurately expressed, because the lower effective bit of the shed is 0, naturally does not matter if the floating-point type of the above example uses a double, the precision is not lost because the double has a precision of 52 bits.

3) solve the problem of floating-point precision loss

?? Floating-point type brings the problem of loss of precision is very painful, so in general, in the program is not used in the float, double to store the larger data. And business computing often requires accurate results. There is a sentence in the effactive Java book:

The main design objectives for float and double types are for scientific calculations and engineering calculations

The JDK provides two high-precision large-number operation classes for us: BigInteger, BigDecimal.

Source: http://www.cnblogs.com/jinggod/p/8424583.html
The article is inappropriate, please correct me, you can also pay attention to my public number: 好好学java , access to high-quality resources.

Java Fundamentals (i) deep parsing of basic types

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.