2.1 keywords and reserved words
2.1. 1 Definition and characteristics of keywords
Definition: a string given special meaning by the Java language and used for special purposes
Features: all letters in the keyword are lowercase
Keywords in Java:
2.1. 2 reserved words
The existing Java version has not been used, but later versions may be used as keywords. Avoid using these reserved words when naming identifiers yourself, such as goto and const.
2.2 identifier
Identifier:
- The character sequence used by Java when specifying various variables, methods, classes and other elements is called an identifier.
- Any place where you can name yourself is an identifier.
Rules for defining legal identifiers:
- It consists of 26 English letters in case, 0-9_ Or $composition
- Number cannot start
- Keywords and reserved words cannot be used, but they can be included
- Java is strictly case sensitive and has unlimited length
- Identifiers cannot contain spaces
Naming conventions in Java:
- Package name: all letters are lowercase when composed of multiple words: xxxyyyzzz z
- Class name and interface name: when composed of multiple words, the first character of all words is capitalized: xxxyyyzz
- Variable name and method name: when composed of multiple words, the first word is lowercase, and the second starting word is uppercase: xxyyyzz
- Constant name: all letters are capitalized. In case of multiple words, each word is underlined: XXX_YYY_ZZZ
Note: ① when naming, in order to improve the reading ability, try to be meaningful, "see the name and know the meaning"; ② Java adopts unicode character set, so identifiers can also be declared in Chinese characters, but it is not recommended.
2.3 variables
Variable is the most basic storage unit in the program, including variable type, variable name and stored value.
Use variables note:
- Each variable in Java must be declared before use
- Use the variable name to access the data of this area
- Scope of variable: the pair of {} in which it is defined
- A variable is valid only within its scope
- Variables with the same scope cannot be defined with the same name
2.3. 1 declaration and assignment of variables
Declare variables:
- Syntax: < data type > < variable name >
- Example: int var;
Variable assignment:
- Syntax: < variable name > = < value >
- Example: var = 10;
You can also assign values directly when declaring:
- Syntax: < data type > < variable name > = < initialization value >
- Example: int var = 10;
Another Chestnut:
class VariableTest { public static void main(String[] args) { //Variable declaration int myNumber; //Variable assignment myNumber = 10; //Variable use System.out.println(myNumber); //Direct assignment on variable declaration int myAge = 12; //Use of variables System.out.println(myAge); } }
2.3. 2 data type
-
Basic data type
- Numerical type
- Integer type byte / short / int / long
- Floating point type float / double
- Character char
- boolean
- Numerical type
-
Reference data type
- Class (string belongs to class)
- Interface interface
- Array array
2.3. 3 integer type byte / short / int / long
Space occupied by each type and representation range:
type | Occupied storage space | Representation range |
---|---|---|
byte | 1 byte = 8 bits | − 128 -128 −128 ~ 127 127 127 |
short | 2 bytes | − 2 15 -2^{15} −215 ~ 2 15 − 1 2^{15} - 1 215−1 |
int | 4 bytes | − 2 31 -2^{31} −231 ~ 2 31 − 1 2^{31} - 1 231−1 |
long | 8 bytes | − 2 63 -2^{63} −263 ~ 2 63 − 1 2^{63} - 1 263−1 |
be careful:
- bit: the smallest storage unit in a computer; byte: the basic storage unit in a computer
- Integer constants in Java are often of type int. to declare a long constant, you need to add "L" or "L" after it
- Variables in Java programs are usually declared as int, and long is used unless it is insufficient to represent a large number
2.3. 4 floating point type float / double
Space occupied by each type and representation range:
type | Occupied storage space | Representation range |
---|---|---|
Single precision float | 4 bytes | − 3.403 E 38 -3.403E38 −3.403E38 ~ 3.403 E 38 3.403E38 3.403E38 |
Double precision double | 8 bytes | − 1.798 E 308 -1.798E308 −1.798E308 ~ 1.798 E 308 1.798E308 1.798E308 |
be careful:
- Floating point constants can be expressed in two forms:
- Decimal form, such as 5.12512.0f,. 512 (must have decimal point)
- Form of scientific counting method: e.g. 5.12e2512E2100E-3
- float: single precision. Mantissa can be accurate to seven significant digits. In many cases, it is difficult to meet the demand
- Double: double precision. The precision is twice that of float. This type is usually used
- Floating point constants in Java are double by default. To declare a float ing constant, you need to add "F" or "F" after it
2.3. 5 character type
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 quotes. For example, char c1 = 'a'; char c2 = 'medium'; char c3 = ‘2’
- The escape character '' is also allowed in Java to convert subsequent characters into special character constants. For example, char c1 = '\ n'; Indicates a newline character
- Use Unicode values directly to represent character constants: '\ uXXXX'. Where XXXX represents a hexadecimal integer, for example '\ u000a' represents' n '
Note: char type can be operated
2.3. 6 Boolean
Boolean data can only be taken as true and false without null, and 0 or non-0 can not be used to replace false and true respectively, which is different from C language.
Boolean is usually used to judge logical conditions and process control statements:
- if conditional control statement
- while loop control statement
- Do while loop control statement
- for loop control statement
2.3. 7 basic data type conversion
1. Automatic type conversion
When a variable of a data type with a small capacity is calculated with a variable of a data type with a large capacity, the result is automatically promoted to a data type with a large capacity. (capacity refers to the range of numbers represented. For example, float capacity is larger than long capacity.)
Capacity sorting of various data types:
be careful:
- When byte, char and short variables operate on each other (including the same type), the result is int!
- boolean type cannot be type converted with other types
- When the value of any basic data type is connected with a string, the value of the basic data type will be automatically converted to a string.
2. Cast type
- The reverse process of automatic type conversion, which converts data types with large capacity into data types with small capacity. The cast character: () should be added when using, but it may cause precision reduction or overflow. Pay special attention.
- boolean type cannot be converted to other data types.
3. Several special cases in coding process
- Forget to add L when assigning value to long type
class VariableTest { public static void main(String[] args) { // In this case, the value can be assigned and output successfully // Java will automatically recognize 123123 as int type and cast it to float type long l1 = 123123; System.out.println(l1); // Compilation failure // Since 34354347859438572974398578 has exceeded the representation range of int type, an error will be reported long l2 = 34354347859438572974398578; System.out.println(l2); } }
- Forget to add F when assigning value to float type (f must be added when assigning value to float type)
class VariableTest { public static void main(String[] args) { // Compilation failed // Error message: conversion from double type to float type may result in loss float f1 = 12.3; System.out.println(f1); //Compilation succeeded double d1 = 12.3; float f2 = (float)d1; System.out.println(f2); } }
- The default integer constant in Java is of type int, and the decimal constant is of type double. The following code will report an error:
class VariableTest4 { public static void main(String[] args) { // Compilation failed // Error message: incompatible type. Conversion from int type to byte may cause loss byte b = 12; byte b1 = b + 1; // Compilation failed // Error message: incompatible types. Converting from double type to float type may cause loss float f1 = b + 12.3; } }
2.3. 8-character String
- String is a reference data type, which is translated into: string
- When declaring a variable of type String, use a pair of double quotation marks
- String can operate with 8 data types, and can only be a connection operation "+", and the result after connection is still a string type
For example:
class StringTest { public static void main(String[] args) { String s1 = "Hello World!"; String s2 = ""; String s3 = "a"; // Connection operation: "+" int number = 1001; String numberStr = "Student No.:"; String info = numberStr + number; System.out.println(info); // Output result: "student No.: 1001" boolean b1 = true; String info1 = info + b1; System.out.println(info1); // Output result: "student No.: 1001true" } }
Note: "+" indicates connection in case of String type and addition in other types.
2.3. 9 practice
class StringTest { public static void main(String[] args) { char c = 'a'; int num = 10; String str = "hello"; System.out.println(c + num + str); // 107hello System.out.println(c + str + num); // ahello10 System.out.println(c + (num + str)); // a10hello System.out.println((c + num) + str); // 107hello System.out.println(str + num + c); // hello10a } }
2.4 operators
Operator is a symbol that represents the operation, assignment and comparison of data. Operators in Java:
- Arithmetic operator
- Assignment Operators
- Comparison operator (relational operator)
- Logical operator
- Bitwise operator (rarely used in development)
- Ternary operator
2.4. 1 arithmetic operator
operator | operation | example | result |
---|---|---|---|
+ | Plus sign | +3 | 3 |
- | minus sign | b=4; -b | -4 |
+ | plus | 5+5 | 10 |
- | reduce | 6-4 | 2 |
* | ride | 3*4 | 12 |
/ | except | 5/5 | 1 |
% | Surplus | 7%5 | 2 |
++ | Auto increment (before): Auto increment before operation | a=2; b=++a; | a=3; b=3 |
++ | Auto increment (after): operation before auto increment | a=2; b=a++; | a=3; b=2 |
– | Self subtraction (before): self subtraction before operation | a=2; b=–a; | a=1; b=1 |
– | Self subtraction (after): operation before self subtraction | a=2; b=a–; | a=1; b=2 |
+ | String connection | "he"+"llo" | "hello" |
Give some examples and precautions:
class AriTest { public static void main(String[] args) { // division int num1 = 12; int num2 = 5; int result1 = num1 / num2; System.out.println(result1); //2 int result2 = num1 / num2 * num2; System.out.println(result2); //10 double result3 = num1 / num2; System.out.println(result3); //2.0 double result4 = num1 / num2 + 0.0; System.out.println(result4); //2.0 double result5 = num1 / (num2 + 0.0); System.out.println(result5); //2.4 double result6 = (double)num1 / num2; System.out.println(result6); //2.4 // Remainder:% // The sign of the result is the same as that of the module // In development, it is often used to judge whether it can be eliminated int m1 = 12; int n1 = 5; System.out.println(m1 % n1); //2 int m2 = -12; int n2 = 5; System.out.println(m2 % n2); //-2 int m3 = 12; int n3 = -5; System.out.println(m3 % n3); //2 int m4 = -12; int n4 = -5; System.out.println(m4 % n4); //-2 // First + +: first increase by 1, and then operate // After + +: calculate first, and then increase by 1 int a1 = 10; int b1 = ++a1; // a1 first + 1, then assign a value to b1 System.out.println("a1 = " + a1 + ", b1 = " + b1); // a1=11, b1=11 int a2 = 10; int b2 = a2++; // Assign b2 first, a2 then + 1 System.out.println("a2 = " + a2 + ", b2 = " + b2); // a2=11, b2=10 // Note: increasing by 1 will not change the data type of the variable itself short s1 = 10; //s1 = s1 + 1; // Compilation failed s1 = (short)(s1 + 1); // Compilation succeeded s1++; // The compilation is successful and the efficiency is higher // Before --: subtract 1 first, and then operate // After --: first operation, and then self subtraction of 1 int a4 = 10; int b4 = --a4; System.out.println("a4 = " + a4 + ", b4 = " + b4); } }
Exercise: arbitrarily give an integer, print and display its single digit, ten digit and hundred digit values.
class AriTest1 { public static void main(String[] args) { int num = 187; int bai = num / 100; int shi = num / 10 % 10; int ge = num % 10; System.out.println("The hundredth is:" + bai); System.out.println("Ten are:" + shi); System.out.println("The bits are:" + ge); } }
2.4. 2 assignment operator
- Symbol:=
- When the data types on both sides of "=" are inconsistent, you can use the principle of automatic type conversion or forced type conversion
- Continuous assignment is supported
- Extended assignment operators: + =, - =, * =, / =,%=
class SetValueTest { public static void main(String[] args) { // assignment int i1 = 10; int j1 = 10; // continuous assignment int i2, j2; i2 = j2 = 10; int i3 = 10, j3 = 12; // += int num1 = 10; num1 += 2; // num1 = num1 + 2; System.out.println(num1); // %= int num2 = 12; num2 %= 5; // num2 = num2 % 5; System.out.println(num2); } }
2.4. 3 comparison operator
- Symbols: = =,! =, <, >, < =, > =, instanceof (check whether it is an object of class)
- The results of comparison operators are boolean, either true or false
- Comparison operator "= =" cannot be written as "=“
2.4. 4 logical operators
-
&: logic and
-
|: logical or
-
!: Logical non
-
&&: short circuit and
-
||: short circuit or
-
^: XOR (true if different, false if the same)
-
Logical operators are used to connect boolean expressions. They can't be written as 3 < x < 6 in Java. They should be written as x > 3 & x < 6
-
”&The difference between "and" & & ":
- ”&"And" & & "have the same result
- ”&": whether the left side is true or false, the right side performs operations
- ”&&": if the left is true, the right participates in the operation. If the left is false, the right does not participate in the operation
-
”|The difference between "and" | ":
- ”|The results of "and" | "are the same
- ”|": whether the left side is true or false, the right side is calculated
- ”||": the left side is true, and the right side does not participate in the operation
For ex amp le, the difference between "&" and "&"
class LogicTest { public static void main(String[] args) { // Distinguish & and&& boolean b1 = true; int num1 = 10; if (b1 & (num1++ > 0)) { System.out.println("I'm in Beijing now!"); } else { System.out.println("I'm in Nanjing now!"); } System.out.println("" + num1); // num1 = 11 boolean b2 = true; int num2 = 10; if (b2 && (num2++ > 0)) { System.out.println("I'm in Beijing now!"); } else { System.out.println("I'm in Nanjing now!"); } System.out.println(num2); // num2 = 11 boolean b3 = false; int num3 = 10; if (b3 & (num3++ > 0)) { System.out.println("I'm in Beijing now!"); } else { System.out.println("I'm in Nanjing now!"); } System.out.println(num3); // num3 = 11 boolean b4 = false; int num4 = 10; if (b4 && (num4++ > 0)) { System.out.println("I'm in Beijing now!"); } else { System.out.println("I'm in Nanjing now!"); } System.out.println(num4); // num4 = 10 } }
2.4. 5-bit operator
- Bit operation is an operation directly on the binary of an integer
- Within a certain range, every shift to the left is equivalent to * 2; Each image shifts one bit to the right, which is equivalent to / 2
- Move right > >:
- Positive number: the empty high position is filled with 0
- Negative number: the empty high position is filled with 1
- Unsigned shift right > > >: no matter positive or negative, the empty high position will be filled with 0
- Negate: each binary code is negated according to the complement
2.4. 6 ternary operator
Statement format: (conditional expression)? Expression 1: expression 2
explain:
- The result of the conditional expression is of type boolean
- Whether expression 1 or expression 2 is executed depends on whether the conditional expression is true or false
- If the conditional expression is true, expression 1 is executed
- If the conditional expression is false, expression 2 is executed
- Ternary operators can be nested
- Where ternary operators can be used, they can be changed to if else, and vice versa
- If the program can use both ternary operators and if else, the ternary operator is preferred. Reason: simplicity and high efficiency
For example, chestnuts:
class SanYuan { public static void main(String[] args) { // Gets the larger value of two integers int m = 12; int n = 5; int max = (m > n)? m: n; System.out.println(max); // Gets the maximum of three numbers int n1 = 89; int n2 = 30; int n3 = -43; int max1 = (n1 > n2)? ((n1 > n3)? n1: n3): ((n2 > n3)? n2: n3); // Nesting of ternary operators System.out.println(max1); } }
2.4. 7 priority of operators
- Operators have different priorities. The so-called priority is the operation order in expression operation, as shown in the following table
- Only unary operator, ternary operator and assignment operator operate from right to left