day03_ Constant, literal, variable, data type

Literal

Literal quantity is data / value, for example: 1234, true, "abc", in ‟, 3.14. In real life, you will be exposed to data every day. For example, your weight today is 86Kg. You spent , 500 yuan and bought a watermelon. The weight is , 8.6Kg. It's sunny outside, but you say it's stormy and rainstorm. What you say is false. You clearly like her, but you say you don't like it and lie. Software is actually to solve the problems in real life. Solving the problems in life is actually to process the data in life. A programming language must be able to represent the data before it can process the data. Therefore, Java programs express the data by literal quantity. In programming languages, data is generally classified, so each data has a data type, and different data types will allocate different sizes of memory space to store it. Basic data types are divided into integer type, floating point type, character type, boolean type, string type, etc.

  • Integer type (number): 1, 2, 100, - 2
  • Floating point (number with decimal): 1.0, 2.0, 3.14
  • Character type (text, single character): ‟ a ‟, ‟ middle ‟
  • Boolean (true or false): true, false
  • String type (text, multiple characters): "Hello, children's shoes"

It should be noted that java , specifies that the character literal must be enclosed in half width single quotation marks, while the string literal must be enclosed in half width double quotation marks. This is a syntax rule, otherwise the compiler will report an error. Only the "literal" mechanism is not enough, because only literal memory can not be reused.

constant

Constant: the amount whose value cannot be changed during program operation. Its classification is generally as follows

                                                                                                                                                                                                                                                                                                                

Code example

/*
Constant: an amount that is fixed during program operation.
Classification of constants:
1. String constant: the part enclosed in double quotation marks is called string constant. For example: "abc", "Hello", "123"
2. Integer constant: a number written directly without a decimal point. For example: 100, 200, 0, - 250
3. Floating point constant: a number written directly with a decimal point. For example: 2.5, - 3.14, 0.0
4. Quotation marks are used as constants. Single character quotation marks are used as constants. For example: 'A', 'b', '9', 'medium'
5. Boolean constant: only value in quantity. true,false. 
6. Null constant: null. Means there is no data.
*/
public class Demo01Const {
    public static void main(String[] args) {
        // string constant 
        System.out.println("ABC");
        System.out.println(""); // The content between the two double quotes of the string is empty
        System.out.println("XYZ");
        
        // integer constant 
        System.out.println(30);
        System.out.println(-500);
        
        // Floating point constant (decimal)
        System.out.println(3.14);
        System.out.println(-2.5);
        
        // character constants 
        System.out.println('A');
        System.out.println('6');
        // System.out.println(''); //  There must be only one character in the middle of two single quotation marks. No.
        // System.out.println('AB'); //  There must be only one character between two single quotation marks, but not two.
        
        // Boolean Literals 
        System.out.println(true);
        System.out.println(false);
        
        // Null constant. Empty constants cannot be used directly for printout.
        // System.out.println(null);
    }
}

variable

Variable overview: variable is the most basic unit for storing data in memory. Put the data (literal) into memory and give this memory space a name, which is variable. Therefore, a variable is a space in memory. This space has name, type and value, which are also the three elements that a variable must have.

                                                                                                                                                                                                                                                                            

In the figure above, each abstract ellipse represents a variable, where ‟ a, c, pi and sex ‟ are the names of ‟ 4 variables (variable names can only be legal identifiers), 13, ‟ good ‟, 3.14 and true ‟ are the data (literal) stored in ‟ 4 variables respectively, int, char, double boolean ¢ is the data type corresponding to the four ¢ variables (int, char, double, boolean, etc. are all keywords of Java ¢ and are used to specify the data type of the variable when declaring the variable). Data type is very important in any programming language, because the program will allocate different sizes of space to data through different data types. Some data types take up less space, but some data types take up a lot of space. This is also in line with reality. In real life, some data are larger and some data are smaller. The variable requires that the "data type of the variable" and the "data (literal quantity)" stored in the variable must be the same type. In other words, the refrigerator is used to store small food, that is, the refrigerator can only store small food, and the elephant can't put it in the refrigerator. The reason is that it can't be put, and the space is inappropriate. For example, int , type can only store integers of , 4 , bytes in size, which can't be longer. For example, integers of long , type occupy , 8 , bytes. Such data can't be put into variables of , int , type. Variable: variable quantity. It means that the data stored in the variable is not invariable, but can be changed. Assuming that the data previously stored in the variable i ^ is ^ 10, we can change ^ 10 ^ into ^ 100. That's what the variable means. You need to know that a variable is composed of three elements: data type, variable name and stored value. The stored value is the literal value of. Java requires that a variable can only save one data at a time, and the data type to be saved must be specified. When a variable name is output in a java program, the value saved in the variable will be automatically output.

                                                                                                                                                                                                                                                      

Declare variable

We need to declare variables before using variables. The syntax format of declaring variables is as follows

  • Data type variable name;

The above is the syntax format of declaring variables, in which the data type will be explained in detail later. At present, we take the data type "int" as an example to learn, and int , represents the integer type. As long as the variable name complies with the identifier naming rules, of course, see the meaning of the name. The naming specification also requires that the first letter of the variable name is lowercase and the first letter of each word after it is uppercase. See the following code to declare a variable age of type int # to store age data:

//  Data type variable name;
    int age;
/*
  So how do you assign values to variables in the java language?
  In the Java language, the assignment operator "=" is required to assign a value to a variable,
  Please see the syntax format of assignment: variable name = value;
*/
age = 20; //Assign a value of 20 to age

java is a strongly typed language. To declare variables, you must specify the data type. The declaration of a variable is just a declaration and will not open up space in memory. When assigning a value to a variable name, a space will be opened up in memory, where the value assigned to the variable name will be saved. We can also assign values to variables while declaring them. The format is as follows:

  • Data type variable name = data value;
/*
The equal sign "=" is an operator, which is called assignment operator. The expression on the right of assignment operator has higher priority,
Therefore, the right side of the equal sign executes first and assigns the execution result to the variable on the left.
*/
int age = 20;

Precautions for using variables

  • Each variable in Java must be declared before use
  • Use the variable name to access the data of this area
  • The value of a variable needs to be declared once, and there is no need to indicate what type of variable to use this variable later. Variables can be manipulated directly through variable names.
public class Demo {
    public static void main(String[] args) {
        // The code in the method body is executed line by line from top to bottom. Variables must be declared before accessing
        // System.out.println(k);  Error: symbol not found
        // Only when this line of code is executed will the k variable open up space in memory.
        int k = 10;
 
        // Define a variable of type int, named age, which is used to store people's age.
        int age;
        // After the variable is declared, there is no manual assignment, direct access, compilation error: error: the variable age may not have been initialized
        //System.out.println(age);
 
        // Assign values to variables
        age = 45;
        // This is the access variable.
        System.out.println(age); //45
    }
}
  • Scope of variable: within a pair of parentheses where its definition is located, the variable is valid only within its scope
  • Within the same scope, variables with duplicate names cannot be defined, but variables can be re assigned.
  • Multiple variables can be declared on one line at the same time, but it is not recommended, which is not readable
// Can multiple variables be declared on a line at the same time?
// Answer: you can declare multiple variables on one line.
public class VarTest06{
    public static void main(String[] args){
        // Declare three variables, all of type int, named a,b,c
        // Through the test, it is concluded that a and B are not assigned, and c is assigned 100
        int a, b, c = 100;
 
        // Variables must be declared and assigned before they can be accessed. Have the two variables A and B been assigned?
        //Error: variable a may not have been initialized
        //System.out.println(a);
        //Error: variable b may not have been initialized
        //System.out.println(b);
        System.out.println(c);
 
        // Assign a value
        a = 200;
        // Assign a value to b
        b = 300;
        System.out.println(a);
        System.out.println(b); 
    }
}

There is a very important principle in java: the proximity principle. (not only in java, but also in other programming languages.) Visit whichever is close to me.

/*
    Scope of variable?
        1,What is scope?
            The valid range of the variable.
        2,As for the scope of variables, you can remember one sentence:
            We don't know each other without braces. (memorize this sentence.)
        3,java There is a very important principle in:
            Principle of proximity. (not only in java, but also in other programming languages.)
            Visit whichever is near me.
*/

public class VarTest{

    // Member variable
    int i = 10000;

    public static void main(String[] args){
        // local variable
        int i = 100; // The valid range of this i is the main method.
        System.out.println(i); // What is this i? one hundred

        // This is not allowed in the same domain.
        //int i = 90;

        for(int n = 0; n < 10; n++){ // The n variable declared here only belongs to the for field. After for, n is released.
            // No code is written here.
        }

        // After the execution of the for loop, can I access the n variable here?
        //System.out.println(n);  // Error: symbol not found

        int k; // Belongs to the main field.
        for(k = 0; k < 10; k++){

        }
        // Can I continue to visit k?
        System.out.println(k);//10
    }

    // How to define this method doesn't matter first, but will be learned later.
    public static void x(){
        // Can i be accessed from this location?
        // Error: symbol not found
        // System.out.println(i); // i is inaccessible.

        // Can i define a variable named i?
        // The valid range of this i is the x method.
        // local variable
        int i = 200; // Therefore, this i is not in the same domain as i in the main method. No conflict.
    }
}

Variables can be divided into:

  • Local variable: a variable declared in a method / code block / multi conditional branch or loop, which can only be used in the current method / code block / multi conditional branch or loop
  • Member variable: a variable declared outside the method. The access scope can be controlled by the access modifier, but it can at least be visible inside the current class

                                                                                                                                                                                                   

Code example

package demo;
 
public class Demo {
    int x = 20; // Instance variable
    static int y = 200; // Static variable
 
    public static void sum(int a, int b) { // Local variables a and b
        int firstNum = 100; // local variable
    }
}

Local variables are only valid in the method body. The memory of local variables will be allocated when the method starts executing. After the method is executed, the memory of local variables will be released. Therefore, the life cycle of local variables is very short. Each data in Java defines a specific data type (strongly typed language), and different sizes of memory space are allocated in memory according to different data types.

                                                                                                                                                                    

Define variables of all basic data types. The codes are as follows

public class Demo {
    public static void main(String[] args) {
        //Define byte type variables
        byte b = 100;
        System.out.println(b);
        //Define short integer variables
        short s = 1000;
        System.out.println(s);
        //Defining integer variables
        int i = 123456;
        System.out.println(i);
        //Define long integer variables
        long l = 12345678900L;
        System.out.println(l);
        //Define single precision floating point variables
        float f = 5.5F;
        System.out.println(f);
        //Define double precision floating point variables
        double d = 8.5;
        System.out.println(d);
        //Defining Boolean variables
        boolean bool = false;
        System.out.println(bool);
        //Define character variables
        char c = 'A';
        System.out.println(c);
    }
}

data type

Java language is a strongly typed language. It gives clear data types for each kind of data. Different data types have different space allocated in memory. Therefore, the data size they represent is also different.

                                                                                                                                                                                                   

From the above, we know that the eight basic data types refer to byte, short, int, long, float, double, boolean and char. Next, let's take a look at the details of the eight basic data types. Please see the following table:

                                                                                                                                                                                                     

The other is the reference data type, which is divided into class, interface and array. We will learn it later. Let's learn the basic data types in detail

Integer type: byte, short, int, long

  • Each integer type of Java has a fixed table number range and field length, which is not affected by the specific OS, so as to ensure the portability of Java programs.
  • The integer constant of java is of type "int" by default, and the declaration of a long constant must be followed by "L" or "L"
  • Variables in java programs are usually declared as int type, and long is used unless it is insufficient to represent a large number
  • If the integer literal does not exceed the value range of byte/short, this integer literal can be directly assigned to a byte/short variable. This syntax mechanism exists for the convenience of writing code.
  • bit: the smallest storage unit in a computer. byte: the basic storage unit in a computer.

Code example

/*
    There are four types of integer type in java language:
        byte    1 Maximum 127 bytes
        short    2 Maximum of 32767 bytes
        int    4 Bytes 2147483647 is the maximum value of int. if it exceeds this range, you can use long type.
        long    8 Bytes
        1 Bytes = 8 binary bits
        1byte = 8bit
        For the above four types, the most commonly used is int.
        When developing, you don't have to worry about everything. Just choose to use int.
    
    In java language, integer literal has four forms: decimal, binary, octal and hexadecimal
*/
public class IntTest{
    public static void main(String[] args){
        // The decimal system is the most commonly used.
        int a = 10;
        System.out.println(a); // 10
        int b = a; // Copy the value 100 saved in variable a to variable b.
        System.out.println(b);//10
 
        // octal number system
        int b = 010;
        System.out.println(b); // 8
 
        // hexadecimal
        int c = 0x10;
        System.out.println(c); // 16
 
        // Binary (a new feature of JDK8, which is not supported in lower versions.)
        int d = 0b10;
        System.out.println(d); // 2
 
        //1. Integer: byte(1 byte = 8bit) \ short(2 bytes) \ int(4 bytes) \ long(8 bytes)
        //① byte range: - 128 ~ 127
        //
        byte b1 = 12;
        byte b2 = -128;
        //b2 = 128;// Compilation failed
        System.out.println(b1);//12
        System.out.println(b2);//128
        // ② Declare a long variable, which must end with "L" or "L"
        // ③ In general, int is used when defining integer variables.
        short s = 128;
        int i = 1234;
        long l = 3414234324L;
    }
}

Floating point type: float, double

Similar to integer type, Java floating-point type also has a fixed range of tables and field length, which is not affected by the specific operating system. Any floating-point type has more space than integer type. Floating point constants can be expressed in two forms:

  • Decimal number form: for example: 5.12 512.0f. 512 (must have decimal point)
  • Form of scientific counting method: e.g. 5.12e2 512E2 100E-2

Float: single precision, mantissa can be accurate to 7 significant digits. In many cases, the accuracy is difficult to meet the requirements. Double: double precision. The precision is twice that of float. This type is usually used. However, for the financial system, when it comes to money, the accuracy of double is far from enough. Later, the BigDecimal class in the java basic library can be used to represent ultra-high-precision data. It is more suitable for the development of financial system. However, BigDecimal does not belong to the category of basic data types. The floating-point constant of Java # is double by default. When declaring a floating-point constant, it must be followed by 'f' or 'f'.

Code example

/*
    Floating point data in java language
        Floating point types include:
            float        4 Bytes
            double        8 Bytes
        for instance:
            10.0 / 3 If float is used for storage, the result may be: 3.33333
            10.0 / 3 If double is used for storage, the result may be: 3.3333
        However, it should be noted that if it is used in banking or finance, double
        It is also far from enough. It provides a more accurate type in java, which is specialized in
        Used in financial software: Java math. BigDecimal (not a basic data type, belonging to
        Reference data type.)
        float And double are approximate values when storing data.
        Why?
            Because there is such wireless cyclic data in the real world, for example: 3.3333
            Data is actually an infinite loop, but the computer has limited memory and uses a limited resource
            Represents infinite data and can only store approximate values.
        long Type takes up 8 bytes.
        float 4 bytes occupied.
        Which has a large capacity?
            Note: any floating-point type has more space than integer type.
            float Capacity > long capacity.
    java It is specified in that any floating-point data is treated as double by default.
    If you want this floating-point literal to be treated as a float type, then
    Please add F/f after literal quantity.
        1.0 Then 1.0 is treated as double by default.
        1.0F This is the float type. (1.0f)
*/
public class FloatTest{
    public static void main(String[] args){
        // Floating point type: float(4 bytes) \ double(8 bytes)
        // Floating point type that represents a numeric value with a decimal point
        // float indicates that the range of values is larger than long
        double d1 = 123.3;
        System.out.println(d1 + 1);//124.3
        // When defining a float type variable, the variable should end with "F" or "F"
        float f1 = 12.3F;
        System.out.println(f1);//12.3
        // Usually, double is used when defining floating-point variables.
 
        //Scientific counting method
        f1 = 3.24E2F;
        d1 = 3.24E3;
        System.out.println(f1);//324.0
        System.out.println(d1);//3240.0
    }
}

Character type: char

  • char type data is used to represent "characters" (2 bytes) in the normal sense
  • All characters in Java are encoded in Unicode, so a character can store a letter, a Chinese character, or a character of other written languages.
  • When an integer is assigned to a char type variable, it will be automatically converted to char character type, and the final result is a character.
/*
    character:
        char
        1,char Occupy 2 bytes.
        2,char Value range of: [0-65535]
        3,char unicode encoding is adopted.
        4,char The literal of the type is enclosed in single quotes.
        5,char Can store a Chinese character.
*/
public class CharTest01{
    public static void main(String[] args){
        // Can char store 1 Chinese character?
        // Yes, Chinese characters take up 2 bytes, and char type in java takes up 2 bytes, just right.
        char c1 = 'in';
        System.out.println(c1);
 
        char c2 = 'a';
        System.out.println(c2);
 
        // 0 if you add single quotation marks, 0 is not the number 0, it is the text 0, it is 1 character.
        char c3 = '0';
        System.out.println(c3);
 
        // Error: incompatible type: String cannot be converted to char
        //char c4 = "a";
 
        // Error: open character text
        //char c5 = 'ab';
 
        // Error: open character text
        //char c6 = '1.08';
 
    }
}

There are three forms of character variables:

  • A character constant is a single character enclosed in single quotation marks (''). For example: char c1 = 'a'; char c2 = 'medium'; char c3 = '9';
  • The escape character '\' is also allowed in Java to convert subsequent characters into special character constants. For example: char c3 = '\ n'; / / ' \N 'indicates a newline character
  • Directly use the Unicode value to represent the character constant: '\ uXXXX'. Where XXXX represents a hexadecimal integer. For example: \ u000a , indicates \ n.
class VariableTest1 {
    public static void main(String[] args) {
        // Normal't 'character
        char c1 = 't';
        System.out.println(c1);
 
        //char x = 'ab';. 
        // The following code is actually 1 character and is not a string
        // Two characters together represent one character, where \ t represents "tab"
        char c2 = '\t'; //Equivalent to the tab key on the keyboard
        
        // \The appearance of will escape the characters immediately following\ Touching t means tab key.
        System.out.println("abc\tdef");
        System.out.print("abc");
        //char c3 = 'n'; //  Normal n characters
        char c3 = '\n'; // Line feed
        //System.out.print(c3);
        System.out.println(c3);
        System.out.println("def");
 
        // Suppose you want to output a 'character on the console now?
        // Error: empty character text
        //System.out.println(''');
        // \'represents an ordinary single quotation mark character that can no longer be ordinary. (\ 'United represents an ordinary')
        System.out.println('\'');
 
        // Suppose you want to output a \ character on the console now?
        //Error: open character text
        //System.out.println('\');
        // In java, two backslashes represent a "normal backslash character"
        System.out.println('\\');
 
        // A string is enclosed in double quotation marks
        System.out.println("test");
        // The desired output is: "test"
        // Error: ')' expected
        //System.out.println(""test"");
        System.out.println(""test""); //Can I use Chinese double quotation marks inside? sure.
 
        System.out.println("");
        // Compilation error.
        //System.out.println(""");
        //System.out.println("\"");
        System.out.println("\"test\"");
 
        // Can this be output?
        // This does not require special escape.
        // This' is just an ordinary character here and has no special meaning.
        System.out.println("'");
 
        //There are questions below
        //System.out.println(''');
        //System.out.println(""");
 
        // tolerable.
        System.out.println("'So'");
 
        // Compilation error, because: 4e2d is a string
        // Error: open character text
        //char x = '4e2d';
 
        // The backslash u indicates that the unicode encoding of a character is followed.
        // unicode encoding is hexadecimal.
        char x = '\u4e2d';
        System.out.println(x); // 'medium '
    }
}

be careful:

  • char type can be operated. Because it all corresponds to Unicode code.
  • When an integer does not exceed the value range of byte short char, this integer can be directly assigned to a variable of type byte short char.
  • Character type char occupies 2 bytes in the Java language. The literal quantity of char type must be enclosed in half width single quotation marks, with the value range of [0-65535]. Both char and short occupy 2 bytes, but char can get a larger positive integer because there is no negative number in char type.

boolean type: boolean

boolean type data can only take values of true and false without null. You can't replace false and true with integers other than 0 or 0, which is different from C language. There is no bytecode instruction dedicated to boolean value in the Java virtual machine. The boolean value operated by the Java language is expressed and replaced by the int data type in the Java virtual machine after compilation: true is represented by 1 and false by 0 Java virtual machine specification (version 8). boolean type is used to judge logical conditions and is generally used for program flow control:

  • if conditional control statement
  • while loop control statement
  • Do while loop control statement
  • for loop control statement

Code example

/*
    1,In the java language, the boolean type has only two values and no other values:
        true And false.
        Unlike C or C + +, 1 and 0 in C language can also represent Boolean types.
    2,boolean Where are types used in actual development?
        Used in logical judgment, usually placed in the position of conditions (acting as conditions)
*/
public class VariableTest1{
    public static void main(String[] args){
        //Error: incompatible type: int cannot be converted to boolean
        //boolean xingBie = 1;
 
        // Requirement specification: if true, it means male; if false, it means female.
        //boolean sex = true;
        boolean sex = false;
        int a = 10;
        int b = 20;
        System.out.println(a < b); // true
        System.out.println(a > b); // false
 
        //boolean flag = a < b;
        boolean flag = (a < b); // Operators have priority. If you are not sure, you can add parentheses. If you add parentheses, it must be executed first.
        System.out.println(flag); // true
 
        // For example, if this Boolean value is true, it means male, and if it is false, it means female.
        if(sex){
            System.out.println("male");
        }else{
            System.out.println("female");
        }
    }
}

Character encoding

For the above eight basic data types, seven types of byte, short, int, long, float, double and Boolean are easy to represent by computer, because the bottom layer of these seven types is directly numbers, and there are fixed conversion rules between decimal numbers and binary, so the computer can represent and process them directly. But don't forget that in addition to the above seven data types, there is another type called character char, which is not so easy for computers to express, because characters are words in the real world after all, and words are different in each country. How do computers express words? We need computers to support characters in the real world. Some standard setting associations have formulated character codes (character sets). Character codes are actually a comparison table, which describes the corresponding relationship between a character and binary.

ASCII code:

In the 1960s, the United States formulated a set of character codes, which made unified provisions on the relationship between English characters and binary bits. This is called ASCII code. ASCII code specifies a total of 128 characters. For example, the SPACE "SPACE" is 32 (binary 00100000), and the uppercase letter A is 65 (binary 01000001). These 128 symbols (including 32 control symbols that cannot be printed) only occupy the last 7 bits of a byte, and the first 1 bit is uniformly specified as 0.

Existence and causes of garbled code

  • There are many coding methods in the world, and the same binary number can be interpreted as different symbols. Therefore, if you want to open a text file, you must know its coding method, otherwise it will be garbled if you interpret it in the wrong coding method.

Unicode:

  • A code that incorporates all the symbols in the world. Each symbol is given a unique and unique code, and there is no problem of garbled code when using Unicode. In order to internationalize Java and support the languages of all countries, the encoding method adopted by Java is Unicode encoding.

UTF-8

  • UTF-8 is the most widely used Unicode implementation on the Internet. UTF-8 # is a variable length encoding method. It can use {1-6} bytes to represent a symbol, and the byte length varies according to different symbols.

Basic data type conversion

Automatic type conversion: assign a value or variable representing a small data range to another variable representing a large data range. The data types are sorted by capacity:

                                                                                                                                                                                          

  • When there are multiple types of data mixed operation, the system will first automatically convert all data into the data type with the largest capacity, and then calculate.
  • Byte, short and char will not be converted to each other. They are first converted to int type during calculation.
  • boolean type cannot operate with other data types.
  • When the value of any basic data type is connected with the string (+), the value of the basic data type will be automatically converted to the string type.

Code example

/*
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 type)
*/
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 the assignment. Give the int constant on the right 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 on the left and float type on the 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
        
        // On the left is the float type, on the right is the long type, which is different from the left and right
        // 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: assign a value or variable representing a small data range to another variable representing a large data range. Cast character: () should be added when cast is used, but it may cause precision reduction or overflow, so pay special attention.

  • Generally, a string cannot be directly converted to a basic type, but it can be converted to a basic type through the wrapper class corresponding to the basic type. For example: String a = "43"; int i = Integer.parseInt(a);
  • boolean type cannot be converted to other data types.

Code example

/*
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;
*/
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);
        
        // long cast to int type
        int num2 = (int) 6000000000L;
        System.out.println(num2); // 1705032704
        
        // Double -- > int, cast type
        int num3 = (int) 3.99;
        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 + 1); // 66, that is, the capital letter A is treated as 65
        // The bottom layer 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 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
    }
}

There are fixed conversion rules between basic data types. Now we summarize the following six rules. No matter which program, apply these six} rules to solve the problem:

  1. Among the eight basic data types, except the boolean type, which cannot be converted, the other seven types can be converted;
  2. If the integer literal does not exceed the value range of , byte, short and char , it can be directly assigned to variables of type byte, short and char;
  3. The conversion from small capacity to large capacity is called automatic type conversion. The order of capacity from small to large is: byte < short (char) < int < long < float < double, where "short" and "char" occupy two bytes, but "char" can represent a larger positive integer;
  4. Conversion from large capacity to small capacity is called forced type conversion, and "forced type converter" must be added when writing, but precision loss may occur during operation, so use it with caution;
  5. When byte, short and char , types are mixed, they are converted to , int , type respectively before operation;
  6. The mixed operation of multiple data types shall be converted to the one with the largest capacity before operation;

Added by mbbout on Sun, 20 Feb 2022 06:26:54 +0200