Interview Preparation (iv) Java basic data types

Source: Internet
Author: User
Tags float double oracle documentation

The Java language is a static type (statical typed), which means that all variables and expression types are fully determined when they are recompiled. Because it is statical typed, the Java language is also strongly typed (strong typed). Strong typing means that each variable has a type, each expression has one type, and each type is strictly defined, and the type restricts which values the variable can hold, and what value the expression ultimately produces. It also limits the types of operations these values can take and how they are manipulated. All assignment operations, whether explicit or passed by parameter in a method call, are checked for type compatibility.

1. Data type:

In the Java source code, each variable must declare a type. There are two types: primitive type and reference type. The reference type refers to the object (reference to object), and the base type directly contains the value (directly contain value). Therefore, the Java data type (type) can be divided into two main classes: the base type (primitive types) and the reference type (reference types). Primitive types includes a Boolean type and a numeric type (numeric types). Numeric types is also divided into integer (integer types) and floating-point (floating-point type). There are 5 types of integers: byte short int long char (char is essentially a special int). Floating-point types have float and double. The relationship is organized like this:

Objects are dynamically created instances of a class or dynamically created arrays. The value of reference types is references to objects, whereas references generally refer to memory addresses. All objects (including arrays) support the methods defined in the object class. String literals is presented by String object.

Java has two types (type), which correspond to the values of both data (two kinds of data values that can is stored in variable, pass as arguments and returned by M Ethods), these two data values are: primitive values,reference values. Perhaps this is easier to understand (though not rigorous), there are two types of Java variables: Primitive variable and reference variable, which store primitive value and reference value, respectively, in variables.

Null is a special type, but you cannot declare a variable to be a null type, and the only value for a null type is NULL. Null can be negative to any reference type or to any reference type. In practice, NULL is generally used as the literal value (literal), which is a literal reference type.

2. Basic type:

Java provides language-level support for basic types, which are already predefined in Java and are represented by corresponding reserved keywords. The base type is a single value, not a complex object, and the base type is not object-oriented, primarily out of efficiency considerations, but also provides the basic type of object version, the basic type of wrapper (wrapper). You can use these basic types directly, or you can construct arrays or other custom types using the base type. The base type has a definite range of values and mathematical behavior.

2.1 Integral type

Integer has a byte short int long char, denoted by 8, 16, 32, 64, 16bits, respectively. In some places, char may not be included in an integer category, but essentially a char type is a subset of Int. The width of an integral type should not be considered as the amount of memory space occupied by integers, but should be understood as the behavior of variables or expressions defined as integral types. The JVM is free to use the memory space of any size that they want, as long as the type behaves in accordance with the specification. A byte short int long is signed, denoted by the 2 complement (s-complement). Char, in 16-bit notation, is unsigned and represents the UTF-16 encoding set.

2.1.1 Byte

A byte is represented by a 1-byte 8-bit, which is the smallest integer type. Mainly used to save memory space key. The byte type is particularly useful when manipulating data flows from networks, files, or other IO. The values range from: [-128, 127]. The default value for byte is (byte) 0, and if we attempt to assign a value outside the range of values to a byte type variable, a compilation error occurs, such as byte B = 128; The statement cannot be compiled. An interesting question, if we have a method: public void Test (Byte b). Trying to call this method is wrong: Test (0); Compiler will error, type is not compatible!!! We remember byte B = 0; This is absolutely no problem, why is it wrong here?

Here comes a question called literal value (literal), which is the surface values, such as integer literals in the source code such as 5, 0, 200. If you add L or L to the integer face, the literal is a long type, for example: 1000L represents a Long value. If L or L is not added, it is of type int. The byte short int long in the base type can be created with an integer literal (which we would call int literals) without l, such as byte B = +, short s = 5, and for long, if the size exceeds the range that int can represent, You must use the L end to represent it. Integer literals can be represented in different ways: 16 binary "0X or 0x", 10 "nothing", octal "0" 2 "0B or 0b" and so on, binary literals are the function of JDK 7. In an assignment operation, an int literal can be assigned to a byte short int Long,java language to automatically handle this process. If the method call is not the same, it can match the method of test (int) when calling test (0), and of course it does not match the test (byte) method, as to why Java does not support the method invocation as it supports assignment operations. Note the difference between the wrapper and the original type of the automatic conversion (anto-boxing,auto-unboxing). byte d = ' A '; also legal, character literals can be automatically converted to 16-bit integers.

For more information about literals, refer to Oracle Documentation (HTTP://DOCS.ORACLE.COM/JAVASE/TUTORIAL/JAVA/NUTSANDBOLTS/DATATYPES.HTML).

When you perform a mathematical operation on a byte type, it is automatically promoted to type int, which is automatically promoted if there are types such as double or float in an expression. So the following code is wrong:

<span style= "Font-family:microsoft yahei;font-size:14px;" ><span style= "FONT-SIZE:14PX;" ><span style= "FONT-SIZE:14PX;" >byte t s1 = +;   byte s2 = ' a ';   byte sum = s1 + s2; // should cast by (byte) </span></span></span>  

2.1.2 Short

In 16, the range of values is: [-2^15, 2^15-1]. Short may be the least common type. You can assign values by integer literals or character literals, provided that the range is not exceeded. When the short type participates in the operation, it is promoted to an int or a higher type. (Order is a byte short int long float double).

2.1.3 Int

[-2^31, 2^31-1]. A signed binary complement represents an integer. Commonly used to control loops, note that byte and short are promoted to type int or higher in the operation. After Java 8, you can use the int type to represent unsigned 32-bit integers [0, 2^31-1].

2.1.4 Long

[-2^63, 2^63-1, default 0L]. When you need to calculate a very large number, you can use the long type if the int is not sufficient to accommodate the size. If long is not enough, you can use the BigInteger class.

2.1.5 Char

Bits, [0, 65535], [0, 2^16-1], from ' \u0000 ' to ' \uffff '. Unsigned, the default value is ' \u0000 '. Java uses a Unicode character set to represent characters, Unicode is a fully internationalized character set and can represent characters in all human languages. Unicode requires a 16-bit width, so the char type in Java is also represented by a-bit. The assignment might be something like this:

char ch1 = 88;

Char CH2 = ' A ';

The ASCII character set occupies the first 127 values of Unicode. Char is attributed to Integer because Java provides arithmetic operations support for Char, such as ch2++; then CH2 becomes Y. When Char is subtraction, it is also converted to an int type, which must be explicitly converted back.

2.2 Floating-point types

A double of float and double precision with single precision, expressed in 32, 64bits, followed by the IEEE 754 specification.

2.2.1 Float

With a single-precision floating-point number, the speed is faster than double and takes up less memory, but becomes imprecise when the value is very large or very small. When the accuracy requirement is not high, you can use the float type, declaring an assignment example:

[Java]View PlainCopy 
    1. <span style="Font-family:microsoft yahei;font-size:14px;" ><span style="FONT-SIZE:14PX;" ><span style="FONT-SIZE:14PX;"  >Float f1 =10;
    2. F1 = 10L;
    3. F1 = 10.0f;
    4. f1 = 10.0; default is Double</span></span></span>

You can assign a byte, short, int, long, char to the float type, and the Java auto-complete conversion.

2.2.2 Double

64 to indicate that when you assign a floating pip face to a variable, the default is double if you do not display the literal value followed by F or F. The functions in Java.lang.Math are in double type.

If both double and float cannot achieve the desired precision, you can use the BigDecimal class.

2.3 Boolean type

The Boolean type has only two values of true and false, and the default is False. The Boolean does not have any relationship with 0, but it can be converted according to the desired logic. A Boolean type is required in many places.

3. Literal value

In Java source code, literals are used to represent fixed values (fixed value). Numeric literals are the most common, and string literals can be considered as a type, and special nulls can also be used as literals. Literals can be broadly categorized as integer literals, floating-point literals, character and string literals, and special literals.

3.1. Integer literals

Formally, the literal value of an integer is categorized as an integer literal. For example: Ten, 100000L, ' B ', 0XFF these can all be called literal values. Integer literals can be expressed in decimal, 16, 8, and 2 notation. Decimal is very simple, 2, 8, 16 binary representation in the front plus 0B (0b), 0, 0X (0x) can, of course, the base can not go beyond the scope of the system, such as 09 is not legal, octal base only to 7. In general, literals create an int type, but int literals can be assigned to a byte short char long int, and as long as the literal value is within the target range, Java automatically completes the conversion. If you attempt to assign an out-of-range literal to a type (such as assigning 128 to a byte type), the compilation is not. If you want to create a long type that cannot be represented by an int type, you need to add either L or L to the literal value. It is generally recommended to use an easily distinguishable L. Therefore, integer literals include int literals and a long literal value of two.

3.2. Floating-point literals

A simple understanding of floating-point literals can be understood as decimals. is divided into float literal and double literal, if you add F or F after the decimal, it is a float literal, such as 11.8F. If the decimal is not followed by F (f), such as 10.4. Or a decimal followed by D (d) indicates that it is a double literal. In addition, floating-point literals support the representation of scientific and technical law. Here are some examples:

<span style= "Font-family:microsoft yahei;font-size:14px;" >double d1 = ten;  double d2  = 11.4;   double d3 = 1.23E3;   double d4 = 10D;   double d5 = 0.4D;   float f1 = ten;   float F2 = 11.1F;   float f3 = 1.23e-4f;   float
3.3 Characters and string literals

Character literals in Java are enclosed in single quotes, such as ' @ ' 1 '. All UTF-16 character sets are included in the character literal. Characters that cannot be entered directly can use escape characters, such as ' \ n ' for newline characters. You can also use octal or hexadecimal notation for characters, and octal to use backslashes with 3-digit digits, such as ' \141 ' for letter A. Hexadecimal uses \u plus 4 for 16 decimal digits, such as ' \u0061 ' to denote character a. That is, by using the escape character, you can represent all or none of the characters on the keyboard. A common sequence of escape characters is:

\DDD (octal), \uxxxx (hexadecimal Unicode character), \ ' (single quotation mark), \ "(double quote), \ \ (backslash) \ r (carriage return) \ n (newline character) \f (page break) \ t (tab) \b (Back to Geff)

String literals use double quotation marks, which in string literals can also contain sequences of escape characters in character literals. The string must be on the same line or use the + operator because Java does not have a continuation escape sequence.

3.4 Special literals

Null is a special type that can be assigned to any reference type variable, indicating that the variable does not refer to anything. If a reference type variable is NULL, it indicates that the variable is not available.

There is also a special class literal, denoted by the type name plus a. class, such as String.class. First, string is an instance (object) of Class Java.lang.Class, and "This is a string" is an object of class string. Class literal is then used to represent an object of class classes, such as the object string String.class used to represent class classes. To put it simply, class literal is a literal value such as String.class, Integer.class, which represents the tired string, the class Integer. If the output integer.class, you will get class Java.lang.Integer. The output of the List.class is interface java.util.List. In summary, class literal is used to represent the type itself!

3.5 using underscores in numeric literals

Beginning with JDK7, you can insert one or more underscores in numeric literals, including integer literals and floating-point literals. However, the underscore can only be used to separate numbers, cannot delimit characters and characters, and cannot delimit characters and numbers. For example, int x = 123_456_789. When compiling, the underscore is automatically removed. You can use underscores continuously, such as float f = 1.22___33__44. The literal value of binary or hexadecimal can also be underlined, remembering that underscores can only be used between numbers and numbers, and are illegal for the first time. For example, 1._23 is illegal, _123 and 11000_l are illegal.

4. Conversions between basic types

As we can see, it is common to assign one type of value to another type. In Java, it is clear that the Boolean type cannot be converted from all other 7 types. For other 7 numeric types, they can be converted between them, but there may be a loss of precision or some other change. Conversions are divided into automatic conversions and casts. For an automatic conversion (implicit), no action is required, and the coercion of type conversions requires an explicit conversion, that is, using the conversion operator (type). Start by arranging the 7 types in the following order:

byte < (SHORT=CHAR) < int < Long < float < double

If you convert from small to large, you can do it automatically, and from large to small, you must cast. The same type of short and char two must also be cast.

4.1 Automatic Conversion

Widening (widening conversion) occurs during automatic conversion. Because large types (such as int) want to hold smaller types (such as Byte), memory is always sufficient and does not require casting. If you save literals to Byte, short, char, long, type conversions are also done automatically. Note the difference, at this point, from int (integer literal with no l as int) to Byte/short/char is also auto-completed, although they are smaller than int. In automatic type conversion, the loss of precision can not occur in other conversions except in the following cases, which may result in loss of precision.

"Int--> float

"Long--> float

"Long--> Double

"Float-->double without STRICTFP

In addition to the possible loss of precision, automatic conversion does not occur with any runtime (run-time) exceptions.

4.2 Coercion of type conversions

If you want to turn large into small, or convert between short and char, you must cast, also known as narrowing conversions (narrowing conversion), because you must explicitly make the values smaller to fit the target type. The cast takes the conversion operator (). Strictly speaking, converting byte to char does not belong to narrowing conversion) because the process from byte to char is actually byte-->int-->char, so widening and narrowing have. In addition to the possible loss of precision, the cast can also cause the modulus (overall magnitude) to change. The cast format is as follows:

(target-type) value

<span style= "Font-family:microsoft yahei;font-size:14px;" >int a=257;    byte b;    = (byte) A; // 1</span>  

If the value of an integer exceeds the range that byte can represent, the result will be the remainder of the range of type Byte. For example, the a=256 exceeds the range of byte [-128,127], so dividing 257 by the range of Byte (256) takes the remainder to get b=1; it should be noted that, when a=200, the remainder of this time except 256 should be 56, not 200.

A truncated (truncation) occurs when a floating-point type is assigned to an integer type. That is, the fractional part is removed, leaving only the integer part. At this point, if the integer exceeds the target type range, the range of the target type will be the remainder.

The basic type conversions in 7 are summarized as:

4.3 Assignment and type conversion in an expression: 4.3.1 literal value Assignment

You can assign an int literal to a byte short char int in the process of assigning a value to an integer using literal values, as long as the range is not exceeded. This process is done automatically when the type is converted, but if you try to assign a long literal to byte, you must also force the type conversion, even if you are not out of range. For example, byte B = 10L; it is wrong to make a cast.

4.3.2 Automatic type promotion in an expression

In addition to assignment, some type conversions can occur during expression evaluation. In an expression, the type promotion rule is as follows:

"All Byte/short/char are promoted to int.

"If there is an operand of long, the entire expression is promoted to long. The same is true for float and double.

Interview Preparation (iv) Java basic data 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.