Notes on Java variables and data types

Notes on Java variables and data types

1. Basic concept of variables (two elements)

  • Variable name
    • When you need to record a single data content in the program, you can declare a variable. The essence of declaring a variable is to apply for a storage unit in memory. Because the data content in the storage unit can be changed, it is named "variable".
  • data type
    • Because the size of the stored data content is different, the size of the required storage unit is different. It is described by using the data type in the Java language. In order to facilitate the next access, you need to specify a name for the variable to record the storage unit corresponding to the variable.

2. Declaration of variables

  • # Common variable declaration
     Data type variable name = Initial value; 
    # It must end with a semicolon to identify the end of a line of code; Only variables can be defined without initial values
    
  • Variable declaration exercise

    public class VarTest{
    	
    	public static void main(String[] args){
    		// 1. Declare a variable and initialize it
    		int age = 21;
    		// 2. Print variable values
    		// +: string connector, connecting the contents of both sides, or a string
    		System.out.println("age = " + age);
    	}
    }
    
    PS E:\LaGou-Java\Class-Learning\Class-note\Module I Java Fundamentals of programming\02 Task 2 variables and data types\code> javac .\VarTest.java
    PS E:\LaGou-Java\Class-Learning\Class-note\Module I Java Fundamentals of programming\02 Task 2 variables and data types\code> java VarTest
    age = 21
    

3. Precautions for using variables

  • Before using variables, you need to declare and specify the data type
  • Variables need to be initialized before they can be used
  • Variable cannot be declared repeatedly

4. Identifier naming rules

  • It is composed of numbers, letters and underscores (and $, but it is not commonly used). Numbers cannot start

  • Java language keywords cannot be used

  • Case sensitive, unlimited length, but not too long

  • Try to see the name and meaning, support Chinese, but it is not recommended

  • Identifiers can name classes / variables / properties / methods / packages.

5.Scanner usage

  • Beginning of file

    • // Import the Scanner class in the util directory in the java directory
      import java.util.Scanner;
      
  • Implementation part of main function in file

    • // Create a scanner to scan the contents of keyboard input. System.in represents keyboard input
      Scanner sc = new Scanner(System.in);
      // Read a string data through the scanner and put it into the variable name
      name = sc.next();
      // Read an integer data through the scanner and put it into the variable name
      age = sc.nextInt();
      

6. Code optimization

  • Variable declaration
  • Combine multiple output sentences into one sentence

7. Data type

  • Basic data type
    • byte,short,int,long,float,double,boolean,char
  • Reference data type
    • Array, class, interface, enumeration, annotation, string

8. Common hexadecimal

  • Decimal: every decimal

  • Binary: every two into one

    • The highest bit (the leftmost bit) in binary is used to represent the sign bit. If the bit is 0, it represents a non negative number, and if the bit is 1, it represents a negative number
  • Octal and hexadecimal are actually short for binary

9. Conversion between hexadecimals

  • Convert positive decimal to binary:
    • Divide by two to get the remainder: use decimal integers to divide by two to get the remainder. When the quotient is zero, the remainder is sorted in reverse order
      • Example: the result of converting decimal 45 to binary is: 10 1101 (0b, 0b can be binary prefix, binary). The 64 bit operating system has 64 bits, and the 64 bits are filled with 0 in front of them. The real binary is 64 bits
    • Split method: split the decimal integer into the sum of several binary weights. Write 1 below the weight, otherwise write 0
  • Convert positive binary to decimal
    • Weighting method: use each number in the binary system multiplied by the weight of each bit to accumulate
  • The way negative decimal is converted to binary
    • First convert the absolute value of decimal system into binary, and then reverse it by bit and add one (complement)
      • Example: convert decimal - 45 to binary: 1101 0011
      • When decimal 45 and - 45 are converted to binary numbers, the result will be high-order overflow (the 65th bit 1 will be discarded)
  • Negative binary to decimal
    • First subtract the binary by one, then reverse it by bit, and then use the weighting method

10. Range represented by integer type

  • byte

    • Nonnegative number:
      • 0000 0000 - 0111 1111(0 ~ 127)
    • Negative number:
      • 1000 0000 - 1111 1111(-128 ~ -1)
    • One byte in memory space, - 2 ^ 7 ~ 2 ^ 7 - 1 (- 128 ~ 127)
  • short

    • Two bytes in memory space, - 2 ^ 15 ~ 2 ^ 15 - 1 (- 32768 ~ 32767)
  • Int * * (recommended, default to int)**

    • Four bytes in memory space, - 2 ^ 31 ~ 2 ^ 31 - 1 (- 2147483648 ~ 2147483647)
  • long

    • Eight bytes in memory space, - 2 ^ 63 ~ 2 ^ 63 - 1 ()

The integer data written out directly in Java programs is called direct quantity / literal quantity / constant, which is of type int by default. If you want to express a greater direct quantity than long, add "L" or "L" after the direct quantity, and "L" is recommended.

11. Written test sites of integer type

  • Why integers cannot be used as identifiers:

    • Unable to distinguish between identifier and direct quantity
    • If there is also a tail suffix, there can be no unified standard. It depends on the programmer's own level. Java officially stipulates that numbers cannot start
  • An error is reported when a variable of different integer types is used to assign a value to another variable:

    • This is a variable. It is unknown whether the value will change

    • When assigning a value, it is impossible to directly determine whether the current variable is within its own integer range. It can only be determined by continuing the calculation. Directly report an error and let the programmer check it by himself

    • // 6. Error code test
      int i2 = 25;
      byte b2 = i2; // Error: incompatible type: conversion from int to byte may be lost
      System.out.println("b2 = " + b2);
      
  • An integer larger than long indicates:

    • // 5. Declare a variable of type long and initialize it
      // If describing data larger than long type, use java.math.BigInteger type
      long L1 = 2147483650L;
      System.out.println("L1 = " + L1);
      

12. Floating point type

  • float

    • Four bytes in memory space are called single precision floating-point numbers, which generally represent seven significant digits

      • Seven significant digits: starting from the first digit on the left, the decimal point is not counted, and the seven digits are significant digits. The remaining part cannot be guaranteed to be valid, and precision loss may occur

      • If the overall length exceeds seven digits, "F" or "F" can be added at the end to indicate that the data is of float type, but the accuracy of the excess part still cannot be guaranteed
        // Float can add f/F at the end of the direct quantity to indicate that it is of float type, but because of the seven significant digits, the precision of the last decimal place cannot be guaranteed
        float f1 = 3.1415926F; // f1 = 3.1415925
        System.out.println("f1 = " + f1);
        
    • Range: - 3.403E38 ~ 3.403E38 (exponential representation)

    • int and float have the same number of bytes. Why do they represent different ranges?

      • It is related to the underlying binary structure
        • int: there is one sign bit and the remaining integer digits
        • float: in addition to the sign bit, there is also a part dedicated to the integer power (exponential part), and then the decimal part. Because there is an exponential part, the range is larger
  • Double * * (recommended, double by default)**

    • Eight bytes in memory are called double precision floating-point numbers, which generally represent fifteen significant digits
    • Range: - 1.798E308 ~ 1.798E308 (exponential representation)

13. Floating point written test site

  • Because the calculation of float and double is not accurate enough, how to achieve accurate calculation:

    • // 3. Written examination site
      System.out.println("0.1 + 0.2 = " + (0.1 + 0.2)); // 0.1 + 0.2 = 0.30000000000000004
      // There will be errors in float and double operations
      // If you want to achieve precise operation, use the java.math.BigDecimal type
      

14. Boolean type

  • boolean:
    • There are only two: true and false (there is no 0 or 1, which is different from C language)
    • Describes the type of true and false information
    • The memory space occupied is not clearly defined and can be considered as a byte (in fact, a bit and a binary bit are enough)

15. Character type

  • char:

    • Data type used to describe a single character (single character enclosed in single quotes)

    • It occupies two bytes in memory space and has no sign bits

    • Indicates that the range is (0 ~ 65535)

    • The bottom layer of the computer only recognizes the binary sequence composed of 0 and 1, which does not meet the rule for patterns such as character 'a', so the data cannot be directly stored in the computer, but in real life, such pattern data needs to be stored by the computer. In order to store the data, a number can be assigned to the data, Then store the number, which is called ASCII.

      • ASCSI:

        • The required ASCII characters are: '0' - 48 'a' - 65 'a' - 97 spaces - 32 line breaks - 10
        • // 4. Define a variable of char type and initialize it
          char c2 = 98;
          System.out.println("c2: " + c2);
          System.out.println("c2 number: " + (int)c2);
          

  • Unicode character set:

    • Contains characters from all over the world

    • Webmaster's home link: http://tool.chinaz.com/tools/unicode.aspx

    • // 5. Print name using Unicode character set
      // Yunmeng GUIYAO - \ u4e91\u68a6\u5f52\u9065
      char c3 = '\u4e91';
      char c4 = '\u68a6';
      char c5 = '\u5f52';
      char c6 = '\u9065';
      System.out.println("My name is: " + c3 + c4 + c5 + c6);
      
  • Special character types:

    • You can use '\' to escape characters

16. Conversion between basic data types

  • Automatic type conversion

    • Automatic type conversion mainly refers to the conversion from small type to large type

    • Reason for conversion from long type (8 bytes) to float type (4 bytes):

      • It is related to the structure of the underlying binary
      • Long can represent (- 2 ^ 63 ~ 2 ^ 63 - 1), while float can represent (1038), which can be approximately converted to ((23) 38 = 2114), so long can be automatically converted to float type
  • Cast type

    • Conversion from large type to small type

      • Target type variable name= (Target type)Source type variable name;
        
      • No loss of coercion (within the current value range):

        byte b1 = 10;
        short s1 = 20;
        // 3. Realize the conversion between mandatory types
        b1 = (byte)s1;
        System.out.println("b1 = " + b1 + ", " + "s1 = " + s1); // b1 = 20, s1 = 20
        
      • Loss of coercion (beyond the current value range):

        // 4. Intentionally exceeding the byte range
        s1 = 128;
        b1 = (byte)s1;
        // The binary number of s1:128 of short type: 0000, 1000 0000, and the lower eight bits are taken when it is forcibly converted to byte, 1000 0000,
        // However, the first bit of byte type is sign bit, which is converted to decimal number - 128
        System.out.println("b1 = " + b1 + ", " + "s1 = " + s1); // b1 = -128, s1 = 128
        
        // 4. Intentionally exceeding the byte range
        s1 = 128;
        b1 = (byte)s1;
        // The binary number of s1:128 of short type: 0000, 1000 0000, and the lower eight bits are taken when it is forcibly converted to byte, 1000 0000,
        // However, the first bit of byte type is sign bit, which is converted to decimal number - 128
        System.out.println("b1 = " + b1 + ", " + "s1 = " + s1); // b1 = -128, s1 = 128
        

Tags: Java

Posted on Sun, 21 Nov 2021 20:41:38 -0500 by yaron