06_ Data type conversion

Keywords: Java Programming JavaEE Back-end JavaSE

Chapter 6 data type conversion

Author: Zhang Zimo

Java programs require that the data involved in calculation must be consistent in data types. If the data types are inconsistent, type conversion will occur.

1, Automatic conversion

What data type will result from the addition of an int variable and a byte variable?

 int i = 1;
 byte b = 2;

As a result of the operation, the type of the variable will be int, which is the phenomenon of automatic type conversion of data types.

1. Automatic conversion

Automatic conversion automatically promotes a type with a small value range to a type with a large value range.

 public static void main(String[] args) {
     int i = 1;
     byte b = 2;
     // byte x = b + i; //  report errors
     //Int type and byte type operation, and the result is int type
     int j = b + i;
     System.out.println(j);
 }

2. Schematic diagram of conversion principle

Byte type memory occupies one byte, which will be promoted to int type during operation with int type, and three bytes will be automatically supplemented. Therefore, the calculated result is still int type.

Similarly, when an int variable and a double variable operate, the int type will be automatically promoted to double type for operation.

public static void main(String[] args) {
     int i = 1;
     double d = 2.5;
     //int type and double type operation, and the result is double type
     //int type is promoted to double type
     double e = d+i;
     System.out.println(e);
 }

3. Conversion rules

Types with a small range are promoted to types with a large range. byte, short and char operations are directly promoted to int.

byte,short,char --> int --> long --> float --> double

2, Force conversion

What happens when 1.5 is assigned to a variable of type int? Failed to generate compilation. It must be unable to assign value.

int i = 1.5; // error

Double type takes up 8 bytes of memory and int type takes up 4 bytes of memory. 1.5 is double type, and the value range is greater than int. It can be understood that double is an 8-liter kettle and int is a 4-liter kettle. You can't put the water in the big kettle directly into the small kettle.

If you want to copy successfully, you can assign a value only by casting double type to int type.

1. Cast type

Cast type converts a type with a large value range into a type with a small value range.

In comparison, automatic conversion is performed automatically by Java, and forced conversion needs to be performed manually by ourselves.

Conversion format

Data type variable name = (data type) Transferred data value;

Assign 1.5 to int type, and modify the code to:

// double type data is forcibly converted to int type, and the decimal point is directly removed.
int i = (int) 1.5;

Similarly, when a short type is added to 1, we know that the type will be promoted, but when we want to assign the result to a short type variable, we need to cast.

public static void main(String[] args) {
     //short type variable, 2 bytes in memory
     short s = 1;
     /*
     Compilation failure occurred
     s When doing operations with 1, 1 is of type int, and s will be promoted to type int
     s+1 The result after is of type int, and an error occurs when assigning the result to type short
     short Memory 2 bytes, int type 4 bytes
     int must be forced to short to complete the assignment
     */
     s = s + 1;//Compilation failed
     s = (short)(s+1);//Compilation succeeded
 }

2. Schematic diagram of conversion principle

Strong attention

  • Converting a floating-point number to an integer directly cancels the decimal point, which may cause loss of data accuracy.

  • Strong conversion of int to short and cutting off 2 bytes may cause data loss.

// Define s as the maximum value in the short range
short s = 32767;
// After the operation, it is forced to convert. After cutting off 2 bytes, there will be uncertain results
s = (short)(s + 10);

3, ASCII code table

public static void main(String[] args) {
    //Character type variable
    char c = 'a';
    int i = 1;
    //Character type and int type calculations
    System.out.println(c+i);//The output is 98
}

There are binary 0 and 1 data inside the computer. How can the computer directly recognize human characters? The concept of coding table is generated.

Coding table

A coding table is a table formed by matching human words with a decimal number.

It is stipulated that:

characternumerical value
048
957
A65
Z90
a97
z122
  • All English letters, numbers and symbols are corresponding to the decimal system, so the world's first coding table ASCII(American Standard Code for Information Interchange) is generated.

Tips

During the calculation of char type and int type, char type characters first query the coding table to get 97, and then sum with 1 to get 98. Char type promoted to int type. Char type takes up 2 bytes of memory and int type takes up 4 bytes of memory.

4, Instance

  • Automatic type conversion

package com.zzm.day02;

/**
 * Purpose:
 * Time: 21:20, May 12, 2021
 * Created by: Zhang Zimo
 */
/*
When the data types are different, data type conversion will occur.

Automatic type conversion (implicit)
    1.Features: the code does not need special processing and is completed automatically.
    2.Rule: data range from small to large.

Cast (explicit)
 */
public class Demo01DataType {
    public static void main(String[] args) {
        System.out.println(1024); // This is an integer. The default is int
        System.out.println(3.14); // This is a floating point number. The default is double

        // On the left is the long type, and on the right is the default int type. The left and right are different
        // An equal sign represents assignment, and the int constant on the right is given to the long variable on the left for storage
        // Int -- > long, which meets the requirements of data range from small to large
        //This line of code has automatic type conversion
        long num1 = 100;
        System.out.println(num1); // 100

        // double type is on the left and float type is on the right. The left and right are different
        // Float -- > double, which conforms to the rule from small to large
        // Automatic type conversion also occurred
        double num2 = 2.5F;
        System.out.println(num2); // 2.5

        // The float type is on the left and the long type is on the right. The left and right are different
        // Long -- > float, the range is larger, which conforms to the rule from small to large
        // Automatic type conversion also occurred
        float num3 = 30L;
        System.out.println(num3); // 30.0
    }
}
  • Cast type

package com.zzm.day02;

/**
 * Purpose:
 * Time: 21:39, May 12, 2021
 * Created by: Zhang Zimo
 */
/*
Cast type
    1.Features: the code needs special format processing and cannot be completed automatically.
    2.Format: type with small range variable name with small range = (type with small range) data with large range;

matters needing attention:
    1.Cast is generally not recommended because it may cause precision loss and data overflow
    2.byte/short/char Mathematical operations can occur in all three types, such as addition "+".
    3.byte/short/char When these three types are operated, they will be promoted to int type first, and then calculated.
    4.boolean Data type conversion cannot occur for type

 */
public class Demo02DataType {
    public static void main(String[] args) {
        // Type int on the left and type long on the right are different
        // Long -- > int, not from small to large
        // Automatic type conversion cannot occur
        // Format: type with small range variable name with small range = (type with small range) data with large range;
        int num = (int) 100L;
        System.out.println(num); // 100

        //long cast to int type
        int num2 = (int) 6000000000L;
        System.out.println(num2); // 1705032704

        // Double -- > int, cast type
        int num3 = (int) 3.5;
        System.out.println(num3); // 3. This is not rounding. All decimal places will be discarded

        char zifu1 = 'A'; // This is A character variable with the capital letter A inside
        System.out.println(zifu1); // A
        System.out.println(zifu1 + 1); // 66, the capital letter A, is treated as 65
        // The bottom of the computer will use A number (binary) to represent the character A, which is 65
        // Once the char type is mathematically operated, the character will be translated into a number according to certain rules

        byte num4 = 40; // be careful! The value size on the right cannot exceed the type range on the left
        byte num5 = 50;
        // byte + byte --> int + int --> int
        int result1 = num4 + num5;
        System.out.println(result1); // 90

        short num6 = 60;
        // byte + short -->int + int --> int
        // Cast int to short: note that the logical real size must not exceed the short range, otherwise data overflow will occur
        short result2 = (short) (num4 + num6);
        System.out.println(result2); // 100
    }
}
  • ASCII code table

package com.zzm.day02;

/**
 * Purpose:
 * Time: May 13, 2021 13:38
 * Created by: Zhang Zimo
 */

/*
Cross reference table of numbers and characters (coding table):

ASCII Code table: American Standard Code for Information Interchange.
Unicode Code table: universal code, which is also the comparison between numbers and symbols. The beginning 0-127 is exactly the same as ASCII, but it contains more characters from 128.
48 - '0'
65 - 'A'
97 - 'a'
 */
public class Demo03DataTypeChar {
    public static void main(String[] args) {
        char zifu1 = '1';
        System.out.println(zifu1 + 0); // 49

        char zifu2 = 'A'; // In fact, the bottom layer stores the number 65

        char zifu3 = 'c';

        // Type int on the left and type char on the right
        // Char -- > int is really from small to large
        // Automatic type conversion occurred
        int num = zifu3;
        System.out.println(num); // 99

        char zifu4 = 'in'; // Correct writing
        System.out.println(zifu4 + 0); // 20013
    }
}

Posted by sparq on Mon, 20 Sep 2021 10:39:43 -0700