Introduction to JAVA

The data type

Basic data types -8

Integer byte short int long

Float double

The character type char

Boolean type Boolean

No. The data type Size/person Can represent the data range The default value
1 Byte (byte type) 8 – 128 ~ 127 0
2 Short (short) 16 – 32768 ~ 32767 0
3 Int (integer) 32 – 2147483648 ~ 2147483647 0
4 Long (long) 64 – 9223372036854775808 ~ 9223372036854775807 0
5 Float (single precision) 32 3.4 e38 ~ 3.4 e38 0.0
6 Double (double) 64 1.7 e308 ~ 1.7 e308 0.0
7 Char (character) 16 0 ~ 255 ‘\ u0000’
8 boolear True or false false

Numeric type extension

float a = 1000000000F;
float b = 1F;
float c = a + b;
System.out.println("c==a=>" + (c==a));

float a1 = 0.1 F;
double b1 = 1 / 10;
System.out.println(a1 == b1);

// The banking system needs exact numbers, using the class BigDecimal

// Cast, from high to low does not need to cast, vice versa
byte a2 = 127;
int b2 = a2;
System.out.println("b2=" + b2);
// Be aware of memory overflow
int c2 = 100;
long d2 = c2;
int e2 = (int) d2;
System.out.println("e2=" + e2);

int f2 = 10 _0000_0000;
int g2 = 1 _0000;
int h2 = f2 * g2;
double i2 = h2;
System.out.println("i2=" + i2);
i2 = f2 * g2;
System.out.println("i2=" + i2);
i2 = (long) f2 * g2;
System.out.println("i2=" + i2);
Copy the code

Automatic type conversion

Integer, real (constant), and character data can be mixed. In an operation, different types of data are first converted to the same type and then the operation is performed. Convert from low-level to high-level.

Low — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — – > high byte, short, char – > int – > long – > float – > double

Data type conversions must meet the following rules:

  • 1. Boolean types cannot be cast.
  • 2. Cannot convert an object type to an object of an unrelated class.
  • 3. A cast must be used to convert a large-capacity type to a small-capacity type.
  • 4. Overflow or loss of accuracy may occur during conversion, for example:
int i =128;   
byte b = (byte)i;
Copy the code

-5. Conversion of floating-point numbers to integers is obtained by abandoning decimals rather than rounding, for example:

(int)23.7= =23;        
(int) -45.89 f= = -45
Copy the code

Cast casting

    1. The condition is that the converted data types must be compatible.
    1. Format: (type)value type is an instance of the data type to be cast:
public class QiangZhiZhuanHuan{
    public static void main(String[] args){
        int i1 = 123;
        byte b = (byte)i1;// Cast to byte
        System.out.println("Int cast to byte is equal to"+b); }}Copy the code

Running results:

The value of the int cast to byte is 123

Implicit cast

  • 1. The default integer type is int.
  • 2. By default, decimals are double floating-point numbers. If a float is defined, it must be followed by F or F.