Basic Syntax of Java#
1. Keywords and Reserved Words#
1.1 Definition and Characteristics of Keywords#
- Definition: Strings (words) with special meanings assigned by the Java language for specific purposes.
- Characteristics: All letters in keywords are lowercase.
- Official address (click to jump)
1.2 Reserved Words#
Java reserved words: Not currently used in the current version of Java, but may be used as keywords in future versions. Avoid using these reserved words when naming identifiers. goto, const
1.3 Identifiers#
Identifiers:#
- Character sequences used by Java to name various elements such as variables, methods, and classes.
- Tip: Identifiers can be used wherever you can name something.
Rules for Defining Legal Identifiers:#
- Consist of 26 lowercase and uppercase English letters, 0-9, _, or $.
- Cannot start with a number.
- Cannot use keywords or reserved words, but can contain keywords and reserved words.
- Java is case-sensitive and has no length limit for identifiers.
- Identifiers cannot contain spaces.
1.4 Naming Conventions in Java:#
- Package names: All letters are lowercase when composed of multiple words: xxxyyyzzz
- Class and interface names: The first letter of each word is capitalized when composed of multiple words: XxxYyyZzz
- Variable and method names: The first letter of the first word is lowercase, and the first letter of each subsequent word is capitalized when composed of multiple words: xxxYyyZzz
- Constant names: All letters are uppercase. When composed of multiple words, each word is connected by an underscore: XXX_YYY_ZZZ
2. Variables#
2.1 Concept of Variables:#
- A storage area in memory.
- The data in this area can change within the same type range.
- Variables are the most basic storage units in a program. They include variable types, variable names, and stored values.
2.2 Purpose of Variables:#
- Used to store data in memory.
2.3 Notes on Using Variables:#
- In Java, each variable must be declared before use.
- Use the variable name to access the data in this area.
- Variable scope: within the pair of { } where it is defined.
- Variables are only valid within their scope.
- Within the same scope, variables with the same name cannot be defined.
2.4 Declaring Variables#
- Syntax:
- For example: int var;
2.5 Assigning Variables#
- Syntax: =
- For example: var = 10;
2.6 Declaring and Assigning Variables#
- Syntax: =
- For example: int var = 10;
2.7 Classification of Variables - by Data Type#
- Each type of data in Java has a specific data type (strongly typed language) and is allocated different sizes of memory space in memory.
- Addition: Classification of Variables - by Declaration Position
- Variables declared outside the method body and inside the class body are called member variables.
- Variables declared inside the method body are called local variables.
- Note: The difference between them in terms of initialization values
- Same: Both have a lifecycle Different: Local variables, except for formal parameters, require explicit initialization.
2.8 Integer Types: byte, short, int, long#
- Java has fixed representation ranges and field lengths for each integer type, which are not affected by specific operating systems to ensure the portability of Java programs.
- Integer constants in Java are default to int type. To declare a long constant, you need to add 'l' or 'L' at the end.
- Variables in Java programs are usually declared as int type unless they are not enough to represent larger numbers, in which case long is used.
public class VariableTest {
public static void main(String[] args) {
int number1;
number1 = 10;
int number2;
number2 = 20;
int number3;
number3 = number1 + number2;
System.out.println("Number3 = " + number3);
int number4 = 50;
int number5 = number4 - number3;
System.out.println("Number5 = " + number5);
}
}
2.9 Floating-Point Types: float, double#
- Similar to integer types, Java floating-point types also have fixed representation ranges and field lengths, which are not affected by specific operating systems.
- Floating-point constants have two forms of representation:
- Decimal form: such as 5.12, 512.0f, .512 (must have a decimal point)
- Scientific notation: such as 5.12e2, 512E2, 100E-2
- float: single precision, the mantissa can be accurate to 7 significant digits. In many cases, the precision is difficult to meet the requirements. double: double precision, the precision is twice that of float. Usually used in this type.
- Floating-point constants in Java are default to double type. To declare a float constant, you need to add 'f' or 'F' at the end.
2.10 Character Type: char#
- char type is used to represent "characters" in the usual sense (2 bytes).
- All characters in Java use Unicode encoding, so a character can store a letter, a Chinese character, or another character in a written language.
- Three forms of character variables:
- Character constants are single characters enclosed in single quotes (' '). For example: char c1 = 'a'; char c2 = ' 中 '; char c3 = '9';
- Java also allows the use of escape characters '' to convert the character after it into a special character constant.
For example: char c3 = '\n'; // '\n' represents a newline character - Directly use the Unicode value to represent character constants: '\uXXXX'. Where XXXX represents a hexadecimal integer. For example: \u000a represents \n.
- char types can be operated on. Because they correspond to Unicode codes.
2.11 Boolean Type: 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 the values true and false, and cannot be null.
- 0 or non-zero integers cannot be used instead of false and true, which is different from C language.
- There are no bytecode instructions dedicated to boolean values in the Java virtual machine. The Java language expression for expressing boolean values is replaced by the int data type in the Java virtual machine: true is represented by 1, and false is represented by 0. - "Java Virtual Machine Specification 8th Edition"
2.12 Basic Data Type Conversion#
- Automatic type conversion: The type with a smaller capacity is automatically converted to a data type with a larger capacity. The data types are sorted by capacity:
- - When there are multiple types of data mixed operations, the system first automatically converts all data to the data type with the largest capacity, and then performs the calculation.
- byte, short, and char are not converted to each other, and they are all converted to int when calculating.
- boolean type cannot be operated with other data types.
- When any basic data type value is concatenated with a string (String) through the "+" operator, the basic data type value will be automatically converted to a string (String) type.
2.13 String Type: String#
- String is not a basic data type, but belongs to a reference data type.
- It is used in the same way as basic data types. For example: String str = "abcd";
- One string can be concatenated with another string, or directly concatenated with other types of data. For example: str = str + "xyz"; int n = 100; str = str + n
public class StringTest {
public static void main(String[] args) {
int no = 10;
String str = "abcdef";
String str1 = str + "xyz" + no;
str1 = str1 + "123";
char c = '国';
double pi = 3.1416;
str1 = str1 + pi;
boolean b = false;
str1 = str1 + b;
str1 = str1 + c;
System.out.println("str1 = " + str1);
}
}
2.14 Type Casting#
- The reverse process of automatic type conversion, converting a data type with a larger capacity to a data type with a smaller capacity. The cast operator () should be added when using it, but it may cause a decrease in precision or overflow, so special attention should be paid.
- Usually, strings cannot be directly converted to basic types, but they can be converted to basic types through the corresponding wrapper classes.
- For example: String a = "43"; int i = Integer.parseInt(a);
- boolean type cannot be converted to other data types.
3. Operators#
- Operators are special symbols used to represent data operations, assignments, and comparisons.
- Arithmetic operators
Assignment operators
Comparison operators (relational operators)
Logical operators
Bitwise operators
Ternary operators
3.1 Operators: Arithmetic Operators#
- Notes on arithmetic operators
- If the modulus is taken of a negative number, the negative sign can be ignored, such as 5%-2=1. However, if the dividend is negative, it cannot be ignored. In addition, the result of the modulus operation is not necessarily always an integer.
- For the division operator "/", it has different meanings for integer division and decimal division: when dividing integers, only the integer part is retained and the decimal part is discarded.
- In addition to the string concatenation function, the "+" operator can also convert non-strings into strings.
3.2 Operators: Assignment Operators#
- Symbol: =
When the data types on both sides of "=" are different, automatic type conversion can be used or handled using the principle of type casting.
Supports consecutive assignment. - Extended assignment operators: +=, -=, *=, /=, %=
- The result of comparison operators is a boolean type, which means it can only be true or false.
- The comparison operator "==" cannot be mistakenly written as "=".
3.3 Operators: Logical Operators#
- & - Logical AND | - Logical OR ! - Logical NOT
&& - Short-circuit AND || - Short-circuit OR ^ - Logical XOR
- Logical operators are used to connect boolean expressions. In Java, you cannot write 3<x<6, you should write x>3 & x<6.
- The difference between "&" and "&&":
When using a single "&", regardless of whether the left side is true or false, the right side will be calculated;
When using double "&", if the left side is true, the right side will be calculated, if the left side is false, the right side will not be calculated. - The difference between "|" and "||" is the same, "||" means: when the left side is true, the right side will not be calculated.
- The difference between XOR (^) and OR (|) is: when both sides are true, the result is false.
- XOR pursues "different"! (0 for the same, 1 for different)
3.4 Operators: Bitwise Operators#
- Bitwise operations are performed directly on the binary representation of integers.
3.5 Operators: Ternary Operators#
- Format:
(conditional expression)?expression1;
If true, the result of the operation is expression1;
If false, the result of the operation is expression2;
Expression1 and expression2 are of the same type.
The connection and difference between the ternary operator and if-else:
- The ternary operator can simplify the if-else statement.
- The ternary operator requires that a result must be returned.
- The code block after if can have multiple statements.
- Operator Precedence