Java basics (1)-keywords, variables, data types, operators, process control

First, let's first understand what a comment is

Comments are to describe and explain the code in easy-to-understand language for easy reading by yourself and others.
1.- Single line comment:
//注释内容
2.- Multi-line comments:
/*注释内容
注释内容
注释内容
*/
3.- Document notes:
/**注释内容
*注释内容
*注释内容
*/

2. Common keywords in Java:

The Java language pre-defined identifiers with specific meanings constitute the basic elements of the program.

1. Abstract means abstract

2, boolean basic data type

3. Break out of the loop

4. Byte basic data type

5. Use case and switch together

6. Catch and try are used together to indicate the catch exception

7, char basic data type

8. class represents a class

9, continue out of the loop

10. Do and while are used together to indicate a loop

11. Double basic data type

12. Else and if collocation, process control

13, enum enumeration type

14, extends inheritance

15, final modified constant

16. Float basic data types

17, if process control

18, implements implementation interface

19. Import introduces a certain class

20, int basic data type

21, interface means interface

22, long basic data type

23, native means local method

24, new create object

25, package means package

26, private description private

27, public

28, return return value

29, short basic data type

30, static means static

31, super means the parent class

32. Use switch and case together

33, synchronized means thread synchronization

34, this represents the current instance

35, throw throws an exception

36. Actively throw exceptions in the throws method

37, try and catch together

38. Void means that the method has no return value

39, volatile means that the thread is guaranteed to read the latest value

40, while means loop

Three, variables

Variables have three elements:

  • Data type (different data should be represented by different data types)
  • Variable name (you can choose your own name instead of memory address)
  • Variable value (data stored in memory)

Four, use variables

1. Declare the data type and variable name of the variable (including numbers, letters, underscores, $, no spaces, operators, no keywords, no beginning with a number), the upper and lower case can be mixed, the first word should be lowercase, and subsequent Capitalize the first letter of a word.

userId, studentName (camel case nomenclature)

2. Assign a value to the memory space, which is the value of the variable.

Five, Java data types

1. Basic data types (a total of 8 types)

byte、int 、short、long、float、double、char、boolean

(1) Numerical type (integer, decimal)

byte 1 byte (8 bits)

int 4 bytes (32 bits)

short 2 bytes (16 bits)

long 8 bytes (64 bits)

float 4 bytes (32 bits) single precision floating point

double 8 bytes (64 bits) double-precision floating-point type
(2) non-numeric type (text)

char character 2 bytes (16 bits)

boolean 1/8 bytes, whether the judgment logic holds true 1/false 0

2. Reference data types

(1) Class, (2) Interface, (3) Array
For example: String type, String is an essential and most used data type in the project, it belongs to the category of "class" in the reference data type .

        Java divides memory into two types, one is called stack memory and the other is called heap memory . Some basic types of variables defined in functions and reference variables of objects are allocated in the stack memory of the function. When a variable is defined in a code block, java allocates memory space for this variable in the stack. When the scope of the variable is exceeded, java will automatically release the memory space allocated for the variable, and the memory space can be immediately Use it for other purposes. Heap memory is used to store objects and arrays created by new. The memory allocated in the heap is managed by the automatic garbage collector of the java virtual machine. After an array or object is generated in the heap, a special variable can also be defined in the stack. The value of this variable is equal to the first address of the array or object in the heap memory, and the special variable in the stack becomes After the reference variable of the array or object, the reference variable in the stack memory can be used in the program to access the array or object in the heap. The reference variable is equivalent to an alias for the array or object.

      Reference variables are ordinary variables. Memory is allocated on the stack during definition, and reference variables are released outside the scope when the program runs. The array & object itself is allocated in the heap. Even if the program runs outside the code block where the statement that uses new to generate the array and object is located, the heap memory occupied by the array and the object itself will not be released. The array and the object are pointed to by the variable without reference. When it becomes garbage, it can no longer be used, but it still occupies memory, and is released by the garbage collector at an indefinite time. This is also the main reason why Java occupies more memory. In fact, variables in the stack point to variables in heap memory, which are pointers in Java!

3. The difference between basic data types and reference data types:

      (1) When the basic data type is created, a memory is divided on the stack, and the value is directly stored on the stack;

      (2) When a reference data type is created, a piece of memory must be allocated for its reference on the stack, and the specific information of the object is stored in the heap memory, and then the reference on the stack points to the address of the object in the heap.

Six, data type conversion

1.-Automatic conversion

Java can automatically convert certain data types.

Rule : Only convert from low byte to high byte, and vice versa.

byte (1 byte) ->short (2 bytes) ->int (4 bytes) ->long (8 bytes) ->float (4 bytes) ->double (8 words) Section)

2.- Forced type conversion

For data types that cannot be automatically converted by Java, developers can convert them through coercive means.

double num = 10.0;
int num2 = (int)num;

Generally speaking, forced type conversion may cause a loss of precision.

Seven, operator

1.-Assignment operator

Data type variable name = value/variable; (assign the value on the right side of the equal sign to the left side)

//1、创建变量用来记录张三的体重
double weight1 = 70.5;
//2、创建变量表示李四的体重
double weight2 = 60.5;
System.out.println("交换之前:张三的体重是"+weight1+",李四的体重是"+weight2);
System.out.println("进行交换:");
double temp = weight1;
weight1 = weight2;
weight2 = temp;
System.out.println("交换之后:张三的体重是"+weight1+",李四的体重是"+weight2);
2.-Arithmetic operators

-Basic arithmetic operators

*+、-、*、/、%(取余运算)、++(自增1)、--(自减1)*

变量1 + 变量2

变量1 - 变量2

变量1 * 变量2

变量1 / 变量2

变量1 % 变量2

变量++、++变量

变量--、--变量

变量++:先操作,再运算。

++变量:先运算,再操作。

-Compound arithmetic operators

+=、-=、*=、/=、%=

变量1 += 变量2:先求出变量1和变量2之和,再把计算结果赋值给变量1,
相当于变量1 = 变量1 + 变量2
3.- Relational operators (usually used for comparison and judgment)

==,!=, >, <, >=, <=
(==, !=) These two can be used for non-numeric types; the last four digits can only be used for numerical type comparison

4.-Logical operators

Logical operators can only be used for boolean data operations to determine the logical relationship between boolean data, and, or, and not.

& (And), | (or),! (Not), && (short circuit and), || (short circuit or)

Note: The variables participating in logical operators are all boolean types

Variable 1 & Variable 2: Only when both variable 1 and variable 2 are true, the result is true, otherwise it is false.
Variable 1 | Variable 2: As long as one of variable 1 and variable 2 is true, the result is true, otherwise it is false.
! Variable 1: If variable 1 is true, the result is false, if variable 1 is false, the result is true.
Variable 1 && Variable 2: Only when both variable 1 and variable 2 are true, the result is true, otherwise it is false.
Variable 1 || Variable 2: As long as one of variable 1 and variable 2 is true, the result is true, otherwise it is false.

Note: && and || are more efficient than & and |

int num1 = 10;
int num2 = 11;
//先判断num1和num2是否相等,num1再++变成11
System.out.println(num1++==num2);
//num1++成12,再和num2比较
System.out.println(++num1==num2);
System.out.println((num1++==num2)&(++num1==num2));
System.out.println(num1);

int num1 = 10;
int num2 = 11;
//第一句已经是true了,不用走后一句了
System.out.println((++num1==num2)||(num1++==num2));
System.out.println(num1);

int num1 = 10;
int num2 = 11;
//第一句判断是true,走后一句,后一句也判断是true
System.out.println((++num1==num2)|(num1++==num2));
System.out.println(num1);

int num1 = 10;
int num2 = 11;
//第一句判断是false的,还要走后面的语句
System.out.println((num1++==num2)&(++num1==num2));
System.out.println(num1);

int num1 = 10;
int num2 = 11;
//第一句已经判断是false,就不用走后面的了
System.out.println((num1++==num2)&&(++num1==num2));
System.out.println(num1);
5.-Conditional operator

Ternary operator, ternary operator, ternary expression
** Assign different values ​​to the same variable according to different conditions, variable = condition? Value 1: Value 2 **
If the condition is true (true), put? on the left Assign the value of to the variable, otherwise (false) assign the value on the right to the variable

public class Test001 {
    
    
	public static void main(String[] args) {
    
    
		int num = 1<2?1:0;
		System.out.println(num);
	}
}

Because 1<2 holds, the output result is 1

public class Test001 {
    
    
	public static void main(String[] args) {
    
    
		int num = 1<2?1:0;
		System.out.println(num);
		int score = 90;
		System.out.println("本次答题的得分是:"+score);
		String str = score>80? "恭喜您获得优惠券一张":"很遗憾,您没有中奖";
	    System.out.println(str);
	}

}

The output result is:
The score of this answer is: 90
Congratulations on getting a coupon

6,-bit operator

(1) Conversion between decimal and binary:

Decimal to binary: Divide the target number by 2, if it can be divided, the bit is recorded as 0, if it cannot be divided, the bit is recorded as 1, and then continue to divide the quotient by 2, and so on, until the quotient is 0, then Combining the results of each bit in reverse order is the corresponding binary.

10:1010
17:10001

(2) Binary to decimal: Starting from the last side of the target number, the value of the local digit is multiplied by the weight of the local digit, and the weight is the number of digits of 2 minus one power, and the value of each digit is added to get The result is the corresponding decimal.

1010: 0 1 (2 to the power of 0) + 1 2 (2 to the power of 1) + 0 4 (2 to the power of 2) + 1 8 (2 to the power of 3) = 10

(3) Bit operator :

& (Bitwise AND), | (bitwise OR), ^ (bitwise exclusive OR), << (left shift), >> (right shift)

  • Variable 1 & Variable 2: First convert variable 1 and variable 2 to binary, and the digits of each digit correspond one-to-one, and compare and judge. If both are 1, the bit is recorded as 1, otherwise, it is recorded as 0.

  • Variable 1 | Variable 2: First convert variable 1 and variable 2 to binary, and each digit corresponds one to one for comparison and judgment. As long as one of them is 1, the bit is recorded as 1, otherwise it is recorded as 0.

  • Variable 1 ^ Variable 2: First convert variable 1 and variable 2 to binary, and each digit corresponds one to one for comparison and judgment. The same is recorded as 0, and the difference is recorded as 1.

  • Variable 1 << Variable 2: Variable 1 times 2 to the power of 2

    2 << 3 : 2 * 8 = 16

  • Variable 1 >> Variable 2: Variable 1 divided by 2 to the power of 2

    2 >> 3: 2/8 = 0

7.-Operator precedence

!>Arithmetic Operators>Relational Operators>Logical Operators (&&> ||)

8. Process control

(1)- if else

Used to judge whether a certain condition is true, and then perform different logical operations.

Basic syntax:

if(判断条件){
    
    
  //条件成立的代码
}else{
    
    
  //条件不成立的代码
}

(2) -Multiple if

int height = 176;
if(height < 173) {
    
    
   System.out.println("M码");
}else if(height > 173 && height <= 178) {
    
    
	System.out.println("L码");
}else {
    
    
	System.out.println("XL码");
}

The output result is: L code

  • condition must be followed by if
  • Else cannot be followed by conditions
  • else can be followed by {} or if

(3)- switch-case

Different from if, switch-case can only complete the equivalent judgment, but cannot complete the judgment size.

If you are judging whether two values ​​are equal, you can use switch-case. If you compare the magnitude of the two values, you cannot use switch-case.

The switch supports int, short, byte, char, enumeration, String type, but does not support boolean type.

Basic grammar

switch(变量){
    
    
	case1:
		//业务代码
	breakcase2:
		//业务代码
	break;
	...
	default:
		//业务代码
	break;
}
The case judges whether the variable is equal to a certain value, and the default represents the code to be executed when all the cases are invalid.
  • 1 Reward 2000
  • 2 Reward 1000
  • 3 Reward 500
  • Otherwise no reward
        int placing = 3;
		/*if(placing ==1 ) {
			System.out.println("奖励2000元");
		}else if(placing == 2) {
			System.out.println("奖励1000元");
		}else if(placing == 3) {
			System.out.println("奖励500元");
		}else {
			System.out.println("没有奖励");
		}*/
		switch(placing) {
    
    
		case 1:
			System.out.println("奖励2000元");
			break;
		case 2:
			System.out.println("奖励1000元");
			break;
		case 3:
			System.out.println("奖励500元");
			break;
		default:
			System.out.println("没有奖励");
			break;
		}
		

Reference link 1
Reference link 2

Guess you like

Origin blog.csdn.net/qq_40220309/article/details/104653214