Basic Java syntax - Day2

Posted by env-justin on Thu, 10 Feb 2022 08:43:45 +0100

1. Keywords and reserved words

1.1 definition of keyword

  • Definition: a string (word) with special meaning given by the Java language for special purposes

  • Features: all letters in the keyword are lowercase

1.2 reserved word

  • Java reserved word: the existing Java version has not been used, but the later version may be used as a keyword. Avoid using these reserved words when naming your own identifiers

    goto ,const

2. Identifier

  • Identifier:

    The character sequence used by Java when naming various variables, methods, classes and other elements is called identifier. For example: class name, variable name, method name, interface name, package name

    Tip: any place where you can name yourself is called an identifier.

2.1 rules for defining legal identifiers

  • It consists of 26 English letters in case, 0-9_ Or $composition

  • A number cannot begin.

  • Keywords and reserved words cannot be used, but they can be included.

  • Java is strictly case sensitive and has unlimited length.

  • The identifier cannot contain spaces.

2.2 Java Naming Conventions

  • Package name: multiple words, all letters are lowercase: xxxyyyzzz z

  • Class name and interface name: when composed of multiple words, the first letter of all words is capitalized xxyyyzz

  • Variable name and method name: when composed of multiple words, the first word is lowercase, and the first letter of each word is capitalized at the beginning of the second word: xxxyyyzz

  • Constant name: all letters are capitalized. When there are multiple words, each word is linked with an underscore: XXX_YYY_ZZZ

3. Variables

3.1 concept of variable

  • A storage area in memory

  • The data in this area can change continuously within the same type range

  • Variable is the most basic storage unit in the program, including variable type, variable name and stored value

3.2 function of variables

  • Used to save data in memory

3.3 notes on using variables

  • Each variable in Java must be declared before use

  • Use the variable name to access the data of this area

  • The scope of a variable, which is defined in a pair of {}

  • A variable is valid only within its scope

  • Variables with duplicate names cannot be defined within the same scope

3.4 use of variables

  • Java defines the format of variables: data type, variable name = variable value;

  • explain:

    • Variables need to be declared before assignment

    • Variables are defined in their scope. Within the scope, they are valid. In other words, out of the scope, they are invalid

    • Two variables with the same name cannot be declared in the same scope

4. Data types defined in Java

4.1 variables are classified by data type

4.1.1 basic data type:

  • Integer: byte (1 byte = 8bit) \ short (2 bytes) \ int (4 bytes) \ long (8 bytes)

    byte range: - 128 ~ 127

    Declaration: long variable, which must end with "L" or "L"

    Type  storage space occupied  table number range

    Byte = 1 byte = 8bit bit - 128 ~ 127

    short 2 bytes - 2 ^ 15 ~ 2 ^ 15-1

    int 4 bytes - 2 ^ 31 ~ 2 ^ 31-1 (about 2.1 billion)

    long 8 bytes - 2 ^ 63 ~ 2 ^ 63-1

  • 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.

    • 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.

    • The floating-point constant of Java is double by default. When declaring a floating-point constant, it must be followed by 'f' or 'f'.

    typeOccupied storage spaceTable number range
    Single precision float4 bytes-3.403E38 ~ 3.403E38
    Double precision double8 bytes-1.798E308 ~ 1.798E308

  • Character type: char

    • char data is used to represent "characters" (2 bytes) in the general 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.

    • 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

      • Use Unicode values directly to represent character constants: '\ uXXXX'. Among them,

      XXXX represents a hexadecimal integer. For example: \ u000a means \ n.

    • char type can be operated. Because it all corresponds to Unicode code.

    Java Defined data type
    1, Variables are classified by data type:
        Basic data type:
            Integer: byte \ short \ int \ long
            Floating point type: float \ double
            Character type: char
            boolean: boolean
        Reference data type:
            class: class
            interface: interface
            Array: array
    2, Where the variable is declared in the class:
            Member variable vs local variable
    class VariableTest1{
        public static void main(String[] args) {
            //2. 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 = 12.3;
            System.out.println(d1 +1);
            //When defining a float type variable, the variable should end with "F" or "F"
            float f1 = 12.3F;
            //② Usually, when defining floating-point variables, use the double variable
            //3. Character type: char(1 character = 2 bytes)
            //① Define char type variables, usually using a pair of '' 
            char c1 = 'a';
            //Compilation failed
            //c1 = 'AB';
            char c2 = '1';
            char c3 = 'in';
            char c4 = '&';
            //② Representation: 1 Declare a character; 2. Escape character; 3. Use Unicode values directly to represent character constants
            char c5 = '\n'; //Line feed
            c5 = '\t';  //Tab
            System.out.print("hello" + c5);
            char c6 = '\u0123';
            char c7 = '\u0043';
  • boolean: boolean

    • 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;

    • boolean type data can only take values of true and false without null.

      • You can't use 0 or non-0 integers instead of false and true, 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

class VariableTest1{
    public static void main(String[] args) {
        //4. boolean
        //① You can only take one of two values: true and false
        //② It is often used in condition judgment and loop structure
        boolean bb1 = true;
        boolean isMarried = true;
            System.out.println("No Entry!");
            System.out.println("You can visit!");

4.1.2 reference data type:

  • class

  • interface

  • array

4.2 position of variable declaration in class

Member variable vs local variable

  • Understanding: ASCII code

    • Inside the computer, all data is represented in binary. Each bit has two states of 0 and 1, so eight bits can be combined into 256 States, which is called a byte. A byte can be used to represent 256 different states. Each state corresponds to a symbol, that is, 256 symbols, from 0000000 to 11111111.

    • 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. The binary encoding of "00100001" is 128 characters (for example, the binary encoding of "00001 A"). 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.

    • Disadvantages: cannot represent all characters. The same code represents different characters: for example, 130 represents é in French code and Gimel in Hebrew code( ג).

  • Understanding: Unicode encoding

    • Garbled Code: there are many coding methods in the world. 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 includes all the symbols in the world. Each symbol is given a unique code, and there is no problem of garbled code when using Unicode.

    • Disadvantages of unicode: unicode only specifies the binary code of the symbol, but does not specify how the binary code should be stored: unicode and ASCII cannot be distinguished: the computer cannot distinguish whether three bytes represent one symbol or three symbols respectively. In addition, we know that only one byte is enough for English letters. If unicode uniformly stipulates that each symbol is represented by three or four bytes, then two or three bytes in front of each English letter must be 0, which is a great waste of storage space.

  • Understanding: UTF-8

    • UTF-8 is the most widely used Unicode implementation on the Internet.

    • UTF-8 is a variable length coding method. It can use 1-6 bytes to represent a symbol, and the byte length varies according to different symbols.

    • Coding rules of UTF-8:

      • For single byte UTF-8 encoding, the highest bit of the byte is 0, and the other 7 bits are used to encode characters (equivalent to ASCII code).

      • For multi byte UTF-8 encoding, if the encoding contains n bytes, the first n bits of the first byte are 1, and the n+1 bits of the first byte are 0. The remaining bits of the byte are used to encode characters. All bytes after the first byte have the highest two bits of "10", and the other six bits are used to encode characters.

4.3 basic data type conversion

  • Automatic type conversion: types with small capacity are automatically converted to data types with large capacity. 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.

Operation rules between basic data types:
Premise: only the operation of basic data type variables in 7 is discussed here. Does not contain boolean type.
1. Automatic type lifting:
    When the variables of the data type with small capacity and the variables of the data type with large capacity are calculated, the result will be automatically promoted to the data type with large capacity.
    Special: when byte, char and short variables are operated, the result is int
2. Cast type:
Note: at this time, the capacity refers to the large and small range of numbers. For example, the capacity of float should be greater than that of long
class VariableTest2{
    public static void main(String[] args) {
        byte b1 = 2;
        int i1 = 129;
        //Compilation failed
//      byte b2 = b1 + i1;
        int i2 = b1 + i1;
        long l1 = b1 + i1;
        float f = b1 + i1;
        char c1 = 'a';  //97
        int i3 = 10;
        int i4 = c1 + i3;
        short s2 = 10;
        //Compilation error
//      char c3 = c1 + s2;
        byte b2 = 10;
//      char c3 = c1 + b2;  // Compilation failed
//      short s3 = b2 + s2; // Compilation failed
//      short s4 = b1 + b2; // Compilation failed
class VariableTest4{
    public static void main(String[] args){
        //1. Coding
        long l = 123456;
        //Compilation failure: too large integer
        //long l1 = 452367894586235;
        long l1 = 452367894586235L;
        //Compilation failed
//      float f1 = 12.3;
        //2. Coding
        //Integer variable. The default type is int
        //Floating point variable. The default type is double
        byte b = 12;
    //  byte b1 = b + 1;    // Compilation failed
    //  float f1 = b + 12.3;    // Compilation failed

4.4 string type: String

  • String is not a basic data type, but a reference data type

  • The usage method is consistent with the basic data type. For example: String str = "abcd";

  • A string can be concatenated with another string, or other types of data can be directly concatenated. For example:

String Use of type variables
1. String It belongs to the reference data type
2. Use a pair of '' when declaring a variable of type String
3. String It can operate with 8 basic data type variables, and the operation can only be connection operation+
4. The result of the operation is still of type String
class StringTest{
    public static void main(String[] args){
        String s1 = "Good Moon!";
        String s2 = "a";
        String s3 = "";
//      char c = '';    // Compilation failed
        int number = 1001;
        String numberStr = "Student number:";
        String info = numberStr + number;   //Join operation
        boolean b1 = true;
        String info1 = info + true;

5. Conversion between base and base

5.1 about binary

  • All numbers exist in binary form at the bottom of the computer.

  • For integers, there are four representations:

    • Binary: 0,1, full 2 into 1 Start with 0b or 0b.

    • Decimal: 0-9, full 10 into 1.

    • Octal: 0-7, full 8 into 1 Start with the number 0.

    • Hexadecimal (hex): 0-9 and A-F, full 16 into 1 It starts with 0x or 0x. A-F here is not case sensitive. For example: 0x21AF +1= 0X21B0

class BinaryTest{
    public static void main(String[] args){
        int num1 = 0b110;
        int num2 = 110;
        int num3 = 0127;
        int num4 = 0x110A;
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);
        System.out.println("num3 = " + num3);
        System.out.println("num4 = " + num4);

5.2 binary

Java integer constant is of type int by default. When an integer is defined in binary, its 32nd bit is the sign bit; When it is a long type, binary occupies 64 bits by default, and the 64th bit is the sign bit. Binary integers have the following three forms:

  • Original code: directly change a numerical value into a binary number. The highest bit is the inverse code of negative sign bit: it reverses the original code by bit, but the highest bit (sign bit) is determined as 1.

  • Complement of negative number: its inverse code plus 1. The computer saves all integers in the form of binary complement.

  • The original code, inverse code and complement of positive numbers are the same, while the complement of negative numbers is its inverse code + 1

Why use original code, inverse code and complement?

Computer identification of "symbol bit" will obviously make the basic circuit design of computer very complex! So people came up with a method to involve symbol bits in operation We know that according to the algorithm, subtracting a positive number is equal to adding a negative number, that is, 1-1 = 1 + (- 1) = 0, so the machine can only add without subtraction, so the design of computer operation is simpler.

Binary to decimal



Decimal to binary

  • For positive numbers, the original code, inverse code and complement code are the same: three codes in one.

  • At the bottom of the computer are numerical values expressed in binary.

  • The bottom layer of the computer uses the complement of the value to save the data

5.3 inter binary conversion



Topics: Java Back-end