Java Fundamentals (i) deep parsing of basic types

Source: Internet
Author: User
Tags decimal to binary

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 bytes;
Char: 2 bytes;
Short : 2 bytes;
int: 4 bytes;
A long: 8 bytes;
float: 4 bytes; (6 decimal places, index: 10^-38~10^38; Range:)
Double: 8 bytes;

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 is literal constant   byte  b = 9 ;    //9 is literal constant  char  c = 9+5 ;    //constant expression  short  s = (short ) (C+10 ); //variable expression requires an explicit cast }  

?? The above code is compiled and is correct. B is a byte type, but b=9 does not require an explicit manual cast, because 9 is a literal constant and is done automatically by the JVM.
?? Let's take a look c=9+5 , C is the char type, and the 9+5 result is the int type, but there is no need to explicitly manually cast. This is because it 9+5 is a constant expression, so the result has been computed by the compiler during compilation, that is, after compilation, it c=14 is equivalent to literal constants, 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.

Limitations of shaping literal Chang conversions:

    • To manually force type conversions when the size of the shape literal constant exceeds the range that the target type can represent.
byte128;//编译错误,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 ); //compilation error  shortmethod  ((short ) 8 ); //compiled by  longmethod  (8 ); //is compiled through because this is a small type that becomes a large type and is not required to force the type conversion of } 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 compound operator (+ =,-=, *=,/=,%=) is a type that can be automatically cast to the left for the type of the right expression

publicstaticvoidmain(String[] args) {    int8;      short5;     s += a;    s += a+5;   }

s+=a s+=a+5; The 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; that the compiler is actually 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 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 of literal constants, including literal constant values, cannot exceed 2 bytes, and literal constant values cannot be negative.

byte2char2;//编译通过      100000000000;//编译不通过,超出char类型的范围char d = -2//字面常量为负数,编译不通过      d = (char)-100;//编译通过char f = (char//编译通过,必须显式的强制类型转换      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, the char 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);    //converted to type int with a value of 65531  System. out . println  ( "(short) c ="  + (short ) c);    //-5  System. out . println  (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. ==the 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 implicit conversions of literal constants.
    • 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:

char5;float0.6f+cc;//最高类型是float,运算结果是floatfloat ee = (float) (0.6d+cc);//最高类型是double,运算结果也是doubleint5+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.

byte2char5char c = (char) (a+b);//byte+char,运算结果的类型为int,需要强制类型转换int  e = a+b;//编译通过,不需要强制类型转换,可以证明是intchar d = (char) (a+c);//char+char,short5short6short s3 =(short

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
The valid bit field is unsigned;

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

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

publicstaticvoidmain(String[] args) {    double0.1;    double0.2;        System.out.println0.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 can not be accurately represented by floating point type, in fact, this is determined by the decimal to binary binary algorithm, decimal decimals to be multiplied 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 a infinite value , floating point type cannot be represented.

?? 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, there is no perfect surface shaping, and the loss of precision of floating-point types can cause some problems.

 Public Static void Main(string[] args) {intA =3000000;intb =30000000;floatF1 = A;floatF2 = b; System. out.println("3000000==3000001"+ (F1==F1+1)); System. out.println("30000000==30000001"+ (F2==F2+1)); System. out.println("Number of effective bits 3000000:"+ Integer.tobinarystring(a).length()); System. out.println("Number of effective bits 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.

Java Fundamentals (i) deep parsing of basic types

Related Article

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.