JavaSe - Fundamentals of syntax


Program: tells the computer the data to operate and the instructions to execute. (data + instruction)
Time slice: the operating system divides time into many small time slices. One time slice is used by one program and the other time slice is used by another program. It switches between programs frequently. On the surface, it makes people feel that multiple programs can be executed at the same time.

#Environmental preparation

Windows installation configuration Java
Linux Installation Configuration Java based on Dragonwell

#Java program development steps

Three steps: write = "javac compile =" java explain run

  1. Write HelloWorld, the source of all evil java
    The file name and class name must be the same.
public class HelloWorld {
   public static void main(String[] args){
  1. compile
    Execute javac HelloWorld Java to generate HelloWorld Class bytecode file.

  2. Explain operation
    Execute the java HelloWorld, and run HelloWorld on the JVM Class file.


// A single line comment, identified by a double slash "/ /", can only comment on one line

* multiline comment 
* It is contained between "/ Star" and "star /" and can annotate multiple lines of content

 * Documentation Comments 
 * It is contained between "/ Star" and "star /", and can annotate multiple lines of content. It is generally used on classes and methods

#Identifiers and keywords

  • identifier
    1) Hard requirements:
    Only letters, numbers, underscores () and dollar sign ($) can be used;
    Cannot start with a number;
    Keywords cannot be used.
    2) Soft requirements:
    Class name: all words are capitalized (big hump);
    Method and variable name: the first word is lowercase, and the other words are capitalized (small hump);
    Static constants: all uppercase, separated by underscores.

  • Keywords and reserved words
    Keyword: string with special meaning in java.
    Reserved word: a string reserved by java that has no meaning in the current version, but may have special meaning in later versions.

#Basic data type

8 bits, 1 byte, default value is 0
Example: byte a = 100;

Literal 100 is of type int, but when it does not exceed the byte value range, javac will automatically cast the type when compiling. short and char are similar

16 bits, 2 bytes, the default value is 0
Example: short s = 1000;

32-bit, 4-byte, integer digital face value is of type int by default, and the default value is 0
Example: int a = 100000;

64 bit, 8 bytes, the default value is 0L
Example: long a = 100000L;, L may not be added in the range of int

32-bit, 4-byte, single precision, IEEE 754 compliant floating-point number. Float and int have the same length, but because float adopts scientific counting method, the value range is larger than int, and the default value is 0.0F
Example: float f1 = 234.5F;, F must be added

64 bit, 8-byte, double precision, IEEE 754 compliant floating-point number. The small number is double by default, and the default value is 0.0D

double d1 = 7D ;
double d2 = 7.; 
double d3 = 8.0; 
double d4 = 8.D; 

7 is an int literal, and 7D, 7, 8.0 ,8.D is the double literal.

16 bits, 2 bytes, is a single Unicode character;
Char is essentially an unsigned positive integer with a fixed occupation of two bytes. It will be regarded as int during operation. The addition and subtraction of char is calculated according to its Unicode number, and the comparison of char type is the comparison of its Unicode number.
Example: char letter = 'A';
Escape character

\nLine feed
\0Null character
\'Single quotation mark
\"Double quotation mark

There are only two values: true and false. The default value is false;
Example: boolean flag = true;

All except the basic data type are reference data types, such as String

Basic data type conversion
java requires that the data involved in the calculation must have the same data type. If it is inconsistent, the data type conversion will be carried out automatically.

byte => short,char =>int =>long =>float =>double
The length of long is larger than that of float, but because float adopts scientific counting method, the value range is larger than that of long

Automatic type conversion: Boolean data types cannot be converted. The conversion from small value range to large range is automatic, and the conversion from large value range to small range is forced.
Cast: (dataType) value, strong conversion may cause precision loss and data overflow.

1,The literal 100 is of type int by default, but a is of type byte. If the literal does not exceed the value range of byte,
javac Forced type conversion will be performed automatically during compilation. If it exceeds the value range, an exception will be reported.
2,a + 1 During operation, a will be promoted to int type, but the assignment to b will not automatically carry out forced type conversion, and an error will be reported.

The same is true for short and char.
byte a = 100; 
byte b = a + 1; 

c + 1 Since c is a constant, if c+1 does not exceed the value range during assignment, javac will automatically perform forced conversion during compilation.
final byte c = 100;
byte d = c + 1;

// Literal operation. If the assignment does not exceed the value range, javac will automatically perform forced conversion during compilation.
byte f = 100 + 1; 


First declare, then assign
 Data type variable 1;
Variable 1 = value 1;
int a;
a = 1;

Assignment upon declaration
 Data type variable 2 = value 2
int b = 2;

Variable: a data container that stores data of a specified type. Declaring a variable will request a piece of memory space to store the specified type of data. Variables must be assigned before they can be used.

Memory: it can be understood as a continuous space with address numbers. Declare a variable, such as int age;, In fact, a space is allocated in memory to store int type data. Age points to the address of this memory space, and this memory space can be operated by operating the variable age.

Constant: a variable with only one assignment opportunity. When declaring, add the final keyword and the final data type NAME;

Binary representation of negative integers
Binary uses the highest bit for sign bits, 1 for negative numbers, and 0 for positive numbers.
Complement representation: on the basis of the original code (binary representation of positive integers), the complement is obtained by taking the inverse plus 1. The complement takes the inverse plus 1 to obtain the original code of positive integers.
-2: The original code of 2 is 00000010, the reverse is 11111101, and then add 1 to 11111110.

Character coding and garbled code

  • ASCII (American Standard Code for information interchange)
    0: 48;A: 65;a: 97

  • ISO 8859-1

  • Windows-1252
    Basically, it can be considered that ISO 8859-1 has been replaced by Windows-1252. In many applications, even if the file states that it adopts ISO 8859-1 coding, it is still regarded as Windows-1252 coding when parsing.

  • GBK (national standard)

  • Unicode encoding
    All characters are assigned a unique Unicode number, which is usually written in hexadecimal and preceded by U +.
    The schemes of Unicode number corresponding to binary form mainly include UTF-32, UTF-16 and UTF-8.
    UTF-8 is ASCII compatible. For most Chinese characters, a Chinese character needs to be represented by three bytes.

  • Code conversion
    With Unicode, a mapping is established between each encoding method and Unicode (it can be considered as this), and different encoding methods can be converted through Unicode. For example, "Ma" changes from GB18030 to UTF-8. First check the GB18030 - > Unicode number table to get its number as 9A6C, and then check the Uncode number - > UTF-8 table to get its UTF-8 Code: E9 A9 AC.

  • Garbled code analysis
    Parsing error: those encoded with A are parsed with B.
    Parsing error plus code conversion: those encoded with A are parsed with B code, then converted with C code and parsed with A code.


Arithmetic operator
byte, short and char will be promoted to int type before arithmetic operation.

+Addition, string connection if there is a string
/Division, quotient rounding off decimal parts
%Modulus (remainder)
a++(–)Self increase (decrease), first use a, and then let a add (decrease) 1
++(–)aSelf increase (decrease), first let a add (decrease) 1, and then use a

Assignment Operators

+=The addition is equal to short s = 1. At this time, s += 1 is equivalent to s = (short)(s + 1), and strong rotation will be carried out automatically
-=Minus equals
*=Multiply equal
/=Division equals
%=Modulo equal

Comparison operator
It is generally used for conditional judgment

==If the values on both sides are equal, return true
>If the left is greater than the right, return true
<If the left is less than the right, return true
>=If the left is greater than or equal to the right, return true
<=If the left is less than or equal to the right, return true
!=Return true if both sides are not equal

Logical operation method
It is generally used for conditional judgment

&&If both short circuit and are true, it will be true, and if false is on the left, the operation will end
||Short circuit or, if one side is true, it is true, and if the left side is true, the operation ends
!Reverse,! true returns false

Ternary operator
Boolean expression? Result 1: result 2;
If the expression result is true, the result 1 is returned; otherwise, the result 2 is returned

Bitwise Operators

&And operation, if the corresponding bit bits are 1, it is 1
|Or operation, if the corresponding bit bit has 1, it is 1
^XOR. If the corresponding bit bits are different, it is 1
~Take the inverse, the corresponding bit bit, 0 becomes 1, 1 becomes 0
<<Move left, move left (binary), fill 0 in the low order on the right, and discard the high order
>>The sign moves to the right, moves to the right, discards the one on the right, and the high position on the left depends on what the original highest position is
>>>Move right without sign, move right, discard the one on the right, and fill 0 in the high position on the left

#Select structure

  • if
if(Conditional expression){
  // When the expression is true, the code block is executed
  • if ... else
if(Conditional expression){
  // When the expression is true, the code block is executed
} else {
  // When the expression is false, the code block is executed
  • if ... else if ... else
    Pay attention to the order of judgment. The latter judgment is executed only when the previous condition is false
if(Conditional expression 1){
  // When expression 1 is true, the code block is executed
} else if((Conditional expression 2)  {
  // When expression 2 is true, the code block is executed
} else {
  // When the above expressions are false, the code block is executed
  • switch
    Case statements will be executed until break statements are encountered or all subsequent statements in case are executed. Generally, break must be added after case statements.
    The value types of switch can be: byte, short, int, char (converted to an integer when judging), enumeration, String (after 1.7, convert to an integer through hashcode. If hashcode is the same, judge through content)
  case Case 1:
    Statement 1;
  • Implementation principle
    Finally, programs are instructions one by one. The CPU has an instruction indicator to point to the next instruction to be executed. The CPU will load and execute the instructions according to the instructions of the instruction indicator. After the CPU executes an instruction, the instruction indicator will automatically point to the next instruction to be executed.
    There are some special instructions in the instructions, which are called jump instructions. The jump instructions will modify the value of the instruction indicator, so as to make the CPU jump to the specified place for execution.
    There are two types of jump: conditional jump (jump if conditions are met) and unconditional jump (direct jump)
    For switch, if there are fewer branches, it may be converted to jump instruction. If there are more branches, a more efficient method may be used. Jump table is a mapping table that stores possible values and addresses to jump.
Condition valueJump address
Condition 1Address of code block 1
Condition 2Address of code block 2

#Cyclic structure

  • while
while(Conditional expression){
 // When the expression is true, the code block is executed
  • do while
do {
  // Code block
} while(Conditional expression)
  • for
[name:]for(Initialization statement;Judge cycle conditions;Change loop variable){
  // When the loop condition is true, the loop body is executed
  • Cycle control
    continue: skip this cycle
    break [name]: jump out of [name] loop
    return: end method

The implementation principle is similar to the selection structure, but also through conditional jump and unconditional jump.


Method can reduce repeated code and decompose complex operations.
Define format

Modifier return value type method name (parameter list){
  return Return value;

1) Modifiers: there are many modifiers for methods in Java, such as public, staic, private
2) Return value type: basic data type and reference data type. If there is no return value, the type is written as void
3) Method name: indicates the meaning of the method. The naming shall be in accordance with the naming specification of symbol identifier
4) Parameters: there are 0 to more. Each parameter consists of the data type and parameter name of the parameter. When defining a method, declaring parameters is actually defining variables (formal parameters). When calling a method, passing parameters is actually assigning values (arguments) to variables in the method.
5) Return value: the data type of the return value must be consistent with the declared return value type

give an example:

public static void method() {
  System.out.println("Self defined methods need to be main Call run");

Method call process

Method overloading
In the same class, the method name is the same and the parameter list is different (number, type and type order).

Matching procedure for method calls
When a method is called, the parameters passed are required to match, but they are not required to be completely consistent, because javac will automatically perform type conversion when compiling and find the most matching method.

Recursive Method
Call your own methods. May cause memory overflow, use with caution.

public class TestRecurve {

    public static void main(String[] args) {
        int res = recurve(3);

    public static int recurve(int num){
            return 1;
        return num * recurve(num-1);

Value passing and reference passing of method calls
Value Passing: the parameter is a basic data type. Modifying parameter (c) in the method has no effect on the incoming parameter (c1)

public class TestVal {

    public static void main(String[] args) {
        char c1 = '1';

    public static void resetVal(char c){
        c = '3';

Reference passing: the parameter is a reference data type. Modifying parameter (c) in the method may affect the incoming parameter (c1), because it points to the same heap space address.

public class TestOne {

    public static void main(String[] args) {
        char[] c1 = {'1','2'};

    public static void resetVal(char[] c){
        c[0] = '3';

Method calling principle
Java memory partitioning

StackIt stores the variables defined in the method
HeapAll the new ones are put in the pile
Method AreaStorage class related information
Native Method Stack Operating system method stack
registercpu related

When calling a method, the method information will be loaded from the method area, and a stack space will be opened in the method stack to store information related to method call, such as method parameters, variables defined in the method, instruction address at the calling method
After the method is called, it will move out of the stack space, return to the address of the calling method, and continue to execute until the main method is out of the stack and the program is executed.
Every time a recursive method recurses, it will open up a space in the stack memory, so it is likely to lead to stack space memory overflow.

Stack: it's like a bucket, first in and last out. The main method is the entrance of java programs, so it's at the bottom of the stack.


Array: a fixed length (immutable length) data container that stores fixed type data.

Array initialization

  • dynamic initialization
    When creating an array, only the type and length are specified, and no assignment is given to the elements in the array. The elements in the array use the default value, the value is 0 by default, char is' \ u0000 'by default, and the reference type is null by default
int[] intArr1 = new int[3];
  • initiate static
int[] intArr2 = new int[]{1,2,3};

int[] intArr3 = {4,5,6};

Accessing elements in an array and considerations
The elements in the array (arr[index]) can be accessed through the subscript index.

  • subscript out of bounds
    The subscript value starts from 0 and cannot exceed the array length (which can be obtained through the. Length attribute) - 1. Otherwise, an array subscript out of bounds exception (java.lang.Array Index out of bounds exception) will be reported.

  • Null pointer exception
    When creating an array, it can be assigned null. If there is no subsequent assignment, a null pointer exception (java.lang.NullPointerException) will be reported when accessing the array properties and elements.
    When the value of a reference type is null, it indicates a null null pointer. If you access its properties or call its methods, you will report a null pointer exception.

Array traversal

  • for loop traversal
for(int i = 0; i<arr.length;i++){
 // Accessing array elements through arr[i]
  • Enhanced for loop
for(int ele:arr){
  // ele is an element in an array

Array memory analysis

  • Array value is null
  • Array value is not empty
int[] arr = {1,2,3};

As shown in the above figure, when creating an array, the variable arr in the stack memory points to the address of the array content in the heap memory.
If you create another array int[] arrB;, Then assign arr to arrB. In fact, assign the address of array arr to arrB. arrB and arr point to the same array address. At this time, modifying arr or arrB is the same array in the operation heap memory.

Array operation

  • Array sorting
// Bubble sorting
int[] arr = {3,11,5,7,2,1,9,6,12,1};
int temp;
for(int i = 0;i <arr.length-1; i++){
  for(int j = 0; j<arr.length-i-1;j++){
     temp = arr[j+1];
     arr[j+1] = arr[j];
     arr[j] = temp;
// Select sort
int[] arr = {3,11,5,7,2,1,9,6,12,1};
int temp;
for(int i = 0,k = 0;i < arr.length-1; i++){
  for(int j = i+1; j<arr.length;j++){
      k = j;
    temp = arr[i];
    arr[i] = arr[k];
    arr[k] = temp;			
  • Binary search
// Binary search
int[] arr = {1,3,4,5,8,9};
int len = arr.length;
int min = 0;
int max = len-1;
int mid;
int find =  5;
int index = -1;
  mid = (min+max)/2;
    max = mid -1;
  } else if(arr[mid]<find){
    min = mid +1;
  } else if(arr[mid]==find){
    index = mid;
  • Arrays tool class

Arrays.toString. When a multidimensional array is encountered, you need to use deepToString to completely convert the array into a string.

int[] arr = {3,1,5,4,2,8,9};


int[] arr = {3,11,5,7,2,1,9,6,12,1};


int[] arr = {3,11,5,7,2,1,9,6,12,1};
int[] arrB = Arrays.copyOf(arr,arr.length);


int[] arr1= {0,2,3,4,10};
List<int[]> arrList1 =  Arrays.asList(arr1);
for (int[] is : arrList1) {
Integer[] arr2 = {0,2,3,4,10};
List<Integer> arrList2 =  Arrays.asList(arr2);
for (Integer is : arrList2) {

For binary search, the array must be orderly. If you search for non-existent elements, add 1 to the obtained subscript, and then take the absolute value, it is the position of the elements in the array if they are in the array.

int[] arr = {0,2,3,4,10};

Keywords: Java

Added by fr@nkie on Wed, 05 Jan 2022 04:40:41 +0200