[Shangsi Valley _java foundation] II. Basic syntax

Posted by cryp7 on Wed, 22 Dec 2021 23:24:32 +0100

reference material

  1. https://www.runoob.com/java
  2. https://www.bilibili.com/video/BV1Kb411W75N

1. Keywords and reserved words

1.1 definition and characteristics of keywords

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

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

2. Identifier

  • The character sequence used by Java when naming various variables, methods, classes and other elements is called an identifier
  • Tip: any place where you can name yourself is called an identifier.

It consists of 26 English letters in case, 0-9_ Or $composition
A number cannot begin.
The identifier cannot contain spaces.
Keywords and reserved words cannot be used, but they can be included.
Java is strictly case sensitive and has unlimited length

  • Naming conventions in Java

When compiling java files with VScode, if an error is reported: "unmapped characters encoding GBK", you can refer to This blog perhaps it.

3. Variables

3.1 basic concepts of variables

  1. Concept of variable

A storage area in memory
The data in this area can change continuously within the same type range
Variables are the most basic storage unit in a program. Contains the variable type, variable name, and stored value

  1. Role of variables

Used to save data in memory

  1. Notes on using variables

Each variable in Java must be declared before use;
Use the variable name to access the data of this area;
Scope of variable: within a pair of {} where its definition is located (for example, if it is a variable defined in a method, its scope is limited to this method);
Variables are valid only within their scope;
Variables with duplicate names cannot be defined within the same scope;

3.2 declaration and assignment of variables

  1. Declare variable

Syntax: < data type > < variable name >
example: int myNumber;

  1. assignment

Syntax: < variable name > = < value >
example: myNumber = 100;

  1. Declaration and assignment are performed simultaneously

Syntax: < data type > < variable name > = < initialization value >
int myNumber=100;

Note that semicolons (English symbols) should not be omitted when writing code.

3.3 variable type

For each kind of data, a specific data type (strongly typed language) is defined and divided in memory
With different sizes of memory space.

Note: String belongs to class and is a reference data type.

  • Outside the method, variables declared in the class are called member variables.
  • Variables declared inside a method body are called local variables.

3.3. 1 integer data type

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.
Integer constants in Java are of type int by default. Declaration of long constants must be followed by 'l' or 'l'. It is better to use 'l'. Lowercase is easy to confuse with 1.
Variables in Java programs are usually declared as int, and long is used unless it is insufficient to represent a large number

bit: the smallest storage unit in a computer. byte: the basic storage unit in a computer.

3.3. 2 floating point data type

Similar to integer types, Java floating-point types also have a fixed range of tables and field lengths, which are not affected by the specific operating system. Floating point constants can be expressed in two forms:

Decimal number form: e.g.: 5.12 512.0f .512 ((must have decimal point)
Scientific counting form:For example: 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 constant, it must be followed by 'f' or 'f'

3.3.3 char type

char data is used to represent "characters" (2 bytes) in the usual 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'. Where XXXX represents a hexadecimal integer. For example: \ u000a means \ n.

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

Supplement: ASCII code, Unicode code, UTF-8



3.3. 4. Boolean type

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

    • Different from C language, false and true cannot be replaced by 0 or non-0 integers.
    • 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

3.4 basic data type conversion

  1. Automatic type conversion
  • Types with small capacity are automatically converted to data types with large capacity. For example, if the number of bits of short data type is 16 bits, the int type with 32 bits can be automatically converted. Similarly, if the number of bits of float data type is 32, it can be automatically converted to 64 bit double type.
  • The data types are sorted by capacity:
  • When there are multiple types of data mixed operation, the system will automatically convert all data into the data type with the largest capacity first, and then calculate.
  • Byte, short and char are not 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.
  1. Cast type
    • The condition is that the converted data types must be compatible.

    • The reverse process of automatic type conversion, which converts data types with large capacity into data types with small capacity. Cast character shall be added when using: (type), but it may cause precision reduction or overflow. Pay special attention.

    • boolean type cannot be converted to other data types.

    • Format: (type)value type is the data type instance to be cast:

public class ForceConvert{
    public static void main(String[] args){
        int i1 = 128;
        byte b = (byte)i1;//Cast type to byte
        System.out.println("int Cast type to byte The value after is equal to"+b); //-128, accuracy loss
        short s= 5;
        s = (short)(s-1); //right
        // s = s-1; //wrong
        System.out.println(s); 
        char c = 'a';
        int i = 5;
        float d = .314F;
        double result = c+i+d; //Judgment: yes
        System.out.println(result); // Output: 102.31400299072266
    }
}

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"; inti= Integer.parseInt(a);

3.5 string type: String

String is not a basic data type, but a reference data type (class)
Use double quotation marks, char type is single quotation mark. The usage method is consistent with the basic data type. For example: String str = "abcd";
If there is a String on the left and right sides of the '+' sign, the '+' sign will automatically become splicing, otherwise it is simple addition.
char type addition is automatically converted to ASCII operation.
A string can be concatenated with another string, or other types of data can be directly concatenated. For example:

public class Grammar {
    public static void main(String[] args) {
        // string convert test
        ConvertTest convert = new ConvertTest();
        convert.printString();
    }
}
class ConvertTest{
    static String str = "523213haha";
    public void printString(){
        int a = 10000;
        str = str+a;
        System.out.println(str);
        System.out .println(3+4+"Hello!"); //Output: 7Hello!
        System.out.println("Hello!"+3+4); //Output: Hello! thirty-four
        System.out.println('a'+1+"Hello!"); //Output: 98Hello!
        System.out.println("Hello"+'a'+1); //Output: Helloa1
        System.out.println('*'+'\t'+'*'); // Output: 93
        System.out.println('*'+'\t'+"*"); // Output: 51*
        System.out.println('*'+('\t'+"*")); // Output: **
        System.out.println(123+""); // Output: String 123 is equivalent to "123"  
    }
}

4. Hexadecimal

  • 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, starting with 0b or 0b.
    • Decimal: 0-9, full 10 into 1.
    • Octal: 0-7, full 8 into 1, starting with the number 0.
    • Hexadecimal (hex): 0-9 and A-F, full 16 into 1, starting with 0x or 0x. A-F here is not case sensitive. For example: 0x21AF +1= 0X21B0


4.1 binary: original code, inverse code and complement code

  • 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 replace a numeric value with a binary number. The highest bit is the sign bit
      -  Negative**Inverse code**: It reverses the original code by bit, but the highest bit (symbol bit) is determined as 1.
      - Negative**Complement**: 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**,The complement of a negative number is its inverse+1
    
  • Why use the representation of original code, inverse code and complement code?

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


about**Positive number**In terms of: original code, inverse code and complement code are the same: three codes in one.
The bottom of the computer is used**Binary**Represents the value of the.
The bottom of the computer is used**Complement of values**To save data.

4.2 inter binary conversion

  • Binary to octal
    Every three bits are converted to a number
  • Binary to hexadecimal
    Every four bits are converted to a number

  • Octal to binary
    Each digit of an octal number becomes a 3-bit binary and then combined.
  • Hexadecimal to binary
    Each digit of a hexadecimal number becomes a 4-bit binary and then combined.

5.Test

  • Can a Chinese character be stored in a char variable? Why?

A: it can be defined as a Chinese character, because Java is encoded in Unicode, and a char accounts for 16 bytes, so it is no problem to put a Chinese character (a Java character is 2 bytes, and each character is represented by Unicode encoding)

  • Define float f=3.4; Is it correct?

Answer: incorrect. If the precision is not accurate, cast should be used as follows: float f=(float)3.4 or: float f = 3.4f

  • Is String the most basic data type

Answer: basic data types include byte, int, char, long, float, double, boolean and short. java.la
ng.String is a class defined in java. All classes belong to reference data type.

  • Does Java have goto

A: reserved words in java are not used in java now

6. Operator

  • Operator is a special symbol used to represent the operation, assignment and comparison of data.

Arithmetic operator
Assignment Operators
Comparison operator (relational operator)
Logical operator
Bitwise Operators
Ternary operator

6.1 arithmetic operators

  • Self increasing and self decreasing test
class AriTest{
    public void ariPrint(){
        int a=2;
        System.out.println(++a);//3
        System.out.println(a++);//3
        System.out.println(a--);//4
        System.out.println(--a);//2
    }
}
  • matters needing attention

If a negative number is taken as a module, the negative sign of the module can be ignored, such as 5% - 2 = 1. However, if the modulus is negative, it cannot be ignored. In addition, the result of modular operation is not always an integer.
For the division sign "/", there is a difference between integer division and decimal division: * * when dividing between integers, only the integer part is retained and the decimal part is discarded** For example: intx = 3510; x=x/1000*1000; The result of X is 3000
In addition to the string addition function, the "+" can also convert non strings into strings For example: system out. println("5+5="+5+5); // 5+5=55

6.2 assignment operator

  • Symbol:=
    -When the data types on both sides of "=" are inconsistent, you can use automatic type conversion or forced type conversion principle for processing.
    -Continuous assignment is supported.

  • Extended assignment operators: + =, - =, * =, / =,%=

  • test

			//test1
			 short s = 3;
        s+=2;
        System.out.println(s);  //Compile correctly: 5
        //test2
        int i = 1;
        i *= 0.1;
        System.out.println(i);// 0
        i++;
        System.out.println(i);// 1
        //test3
        int m = 2;
        int n = 3;
        n *= m++;
        System.out.println("m=" + m); //3
        System.out.println("n=" + n); //6
        //test4
        int n1 = 10;
        n1 += (n1++) + (++n1);
        System.out.println(n1); //32

6.3 comparison operators

The results of comparison operators are boolean, that is, they are either true or false.
The comparison operator "= =" is easy to be written as "=".

6.4 logical operators

`&`—Logic and
`|`—Logical or
`!`—Logical non
`&&` —Short circuit and
`||`—Short circuit or
`^ `—Logical XOR

  • Logical operators are used to connect Boolean expressions. They cannot be written as 3 < x < 6 in Java, but should be written as x > 3 & x < 6.

  • &Difference between & & and &:

    • &When, whether the left side is true or false, the right side is calculated;
    • &&If the left is true, the right participates in the operation. If the left is false, the right does not participate in the operation.
  • |In the same way as the difference between 𞓜 and |, |: when the left is true, the right does not participate in the operation.

  • The difference between XOR (^) and or (|) is that when both left and right are true, the result is false. Understanding: XOR pursues "difference"!

  • test

				//test1
        int x = 1;
        int y = 1;
        if (x++ == 2 & ++y == 2) {
            x = 7;
        }
        System.out.println("x=" + x + ",y=" + y); //2,2
        //test2
        int x2 = 1, y2 = 1;
        if (x2++ == 2 && ++y2 == 2) {
            x2 = 7;
        }
        System.out.println("x=" + x2 + ",y=" + y2); //2,1
        //test3
        int x3 = 1, y3 = 1;
        if (x3++ == 1 | ++y3 == 1) {
            x3 = 7;
        }
        System.out.println("x=" + x3 + ",y=" + y3); //7,2
        //test4
        int x4 = 1, y4 = 1;
        if (x4++ == 1 || ++y4 == 1) {
            x4 = 7;
        }
        System.out.println("x=" + x4 + ",y=" + y4); //7,1
       
        boolean x=true;
        boolean y =false;
        short z=42;
        if((z++==42)&&(y=true))z++;  //y=true as assignment
        if((x==false)||(++z==45))z++;
        System.out.println("z="+z); //z=46

6.5 bit operators

  • Bit operation is an operation directly on the binary of an integer

1. Bitwise operators operate on integer data variables
2. < <: within a certain range, every shift to the left is equivalent to * 2
>>: within a certain range, each shift to the right is equivalent to / 2

			 int a = 60; /* 60 = 0011 1100 */
        int b = 13; /* 13 = 0000 1101 */
        int c = 0;
        c = a & b; 
        System.out.println("a & b = " + c);/* 12 = 0000 1100 */

        c = a | b; 
        System.out.println("a | b = " + c);/* 61 = 0011 1101 */

        c = a ^ b; 
        System.out.println("a ^ b = " + c);/* 49 = 0011 0001 */

        c = ~a; 
        System.out.println("~a = " + c);/*-61 = 1100 0011 */

        c = a << 2;
        System.out.println("a << 2 = " + c); /* 240 = 1111 0000 */

        c = a >> 2; 
        System.out.println("a >> 2  = " + c);/* 15 = 1111 */

        c = a >>> 2; 
        System.out.println("a >>> 2 = " + c);/* 15 = 0000 1111 */
  • Exchange variable method
class BitTest{
	public static void main(String[] args){
		//Exercise: exchanging the values of two variables
		int num1 = 10;
		int num2 = 20;

		//Mode 1:
	//	int tent = num1;
	//	num1 = num2;
	//	num2 = tent;

		//Mode 2:
		//Benefit: no need to define temporary variables
		//Disadvantages: ① addition may exceed the storage range ② limitations: it is only applicable to numerical types
//		num1 = num1 + num2;
//		num2 = num1 - num2;
//		num1 = num1 - num2;

		//Mode 3: use bit operation
		num1 = num1 ^ num2;
		num2 = num1 ^ num2;
		num1 = num1 ^ num2;

		System.out.println("num1 = " + num1 + ",num2 = " + num2);
	}
}

6.6 ternary operator (conditional operator)

  • Ternary operators can be nested
  • Where ternary operations can be used, if else can be rewritten.
    Otherwise, it may not be true!!!

6.7 instanceof operator

  • This operator is used to manipulate an object instance to check whether the object is a specific type (class type or interface type).

  • The instanceof operator uses the following format:

( Object reference variable ) instanceof  (class/interface type) 
  • If the object referred to by the variable on the left side of the operator is an object of the class or interface on the right side of the operator, the result is true.
String name = "James";
boolean result = name instanceof String; // Because name is a String type, it returns true
  • If the object being compared is compatible with the right type, the operator still returns true.
class Vehicle {}
 
public class Car extends Vehicle {
   public static void main(String[] args){
      Vehicle a = new Car();
      boolean result =  a instanceof Car;
      System.out.println( result); //true
   }
}

6.8 operator priority

  • Operators have different priorities. The so-called priority is the operation order in expression operation. As in the right table, the operator in the previous row always takes precedence over the operator in the next row.
  • Only unary operator, ternary operator and assignment operator operate from right to left.

Topics: Java Back-end