Abstract: Java Basic Grammar (Procedure Oriented) Before learning object-oriented programming, we need to understand process oriented progr...
Java Basic Grammar (Procedure Oriented)
Before learning object-oriented programming, we need to understand process oriented programming thinking. If you have studied C language and Python, it will be very easy!
Variables and keywords
Variables
A variable is a variable, such as defining a variable of type int (int is an integer type):
int a = 10;
a = 20;
a = 30;
We can freely change its value, which means its value is constantly variable, and we call it a variable. Variables can be variables of a class or local variables within a method (we mainly use local variables at this stage, and class variables will be explained in object-oriented language)
Variables are different from variables in C language. Variables in Java are stored in JVM managed memory, while variables in C language are stored in memory (in some cases, memory needs to be manually released, while Java automatically helps us clean up the memory occupied by variables). Java and C++are similar, but there are no pointers! Java, also known as C+±-
Java is a strongly typed language, and you can only use it after clearly defining variables! Once a data type is specified, it will always be considered the corresponding type (unlike JS!)
The format for defining a variable is as follows:
[Type] [Identifier (First Name)]=[Initial Value (Optional)]
int a = 10;
Note: Identifiers cannot be:
- The identifier consists of uppercase and lowercase letters, numbers, underscores (_), and dollar signs ($), but cannot start with a number.
- Case sensitive!
- Cannot have symbols such as spaces, @, #,+, -,/, etc
- A meaningful name should be used to achieve the purpose of knowing the meaning of the name, preferably starting with a lowercase letter
- Cannot be true or false
- Cannot have duplicate names with Java language keywords
Keywords
Including basic data types, process control statements, etc., just understand them and don't have to memorize them. We will gradually introduce you later!
Constant
A constant is a variable whose value cannot be modified. The value of a constant can only be defined once:
final int a = 10;
a = 10; //report errors!
The final keyword must be added before the constant (const in C language, although Java also has it, it cannot be used!) This is just the first usage of the final keyword, and there will be more usage in the future.
Comment
Develop a good habit of commenting, otherwise you won't be able to understand your code in the future! Annotations include single line and multi line annotations:
//I am a single line comment
/**
*I am
*Multiple line comments
*/
//TODO to be marked
Basic data type
The data types in Java are divided into two categories: basic data types and reference types. We will mention reference types when object-oriented, and basic data types are the key points! Firstly, we need to understand what types there are. Then, what we need to know is not their accuracy or the range they can represent, but why Java defines these types for us and how computers represent them, so that we can better remember their accuracy and the range they represent. So, from the perspective of computer principles, we take everyone into the basic data types of Java.
This part is a bit brain burning, but it is the most important thing. If you master these, any related interview questions will not be difficult for you! If you have studied the principles of computer composition, it is easy to understand.
Binary representation in computers
In a computer, all content is represented in binary form. Decimal is carried by 10, such as 9+1=10; Binary is full binary (because our computer is electronic, and the level signal only has high and low bits, you can temporarily understand it as powered on and off. High level represents 1, low level represents 0, and since there are only 0 and 1, we can only use binary to represent our numbers!) For example, 1+1=10=2 ^ 1+0, a bit is also called a bit, 8 bits are called 1 byte, 16 bits are called a word, and 32 bits are called a doubleword, 64 bits are called a quadword, and we generally use bytes to describe the data size.
The decimal 7->in binary is 111=2 ^ 2+2 ^ 1+2 ^ 0
Now there are 4 bit bits, what is the maximum number that can represent?
- Min: 0000=>0
- Maximum: 1111=>23+22+21+20=>8+4+2+1=15
In Java, both decimals and integers need to be signed (unlike C, which has unsigned numbers). Therefore, let's use the first digit as our sign bit, or take 4 bits as an example. The first digit is now the sign bit (1 represents a negative number, 0 represents a positive number):
- Min: 1111=>- (22+21+2 ^ 0)=>-7
- Maximum: 0111=>+(22+21+2 ^ 0)=>+7=>7
Now, the range that we can represent with 4 bits has changed to -7~+7, which is called the original code.
Addition and subtraction in computers
Original code
Although the original code is simple, it is very troublesome when doing addition and subtraction in the original code! Taking the 4-bit bit bit as an example:
1+(-1)=0001+1001=How can a computer calculate? (Although we know how to calculate, the computer doesn't know!)
We need to create a better representation! So we introduced the inverse code:
Inverse code
- The inverse of a positive number is itself
- The inverse of a negative number is based on its original code, with the sign bit unchanged and the other bits taken as inverse
After the above definition, let's proceed with addition and subtraction:
1+(-1)=0001+1110=1111=>-0 (Adding directly makes it much simpler!)
Thinking: 1111 represents -00000 represents+0, and within our range of real numbers, does 0 have a positive or negative distinction?
- 0 is neither a positive nor a negative number, so obviously this representation is still not reasonable enough!
Complement
Based on the above problem, we have introduced the final solution, which is the complement, defined as follows:
- The complement of a positive number is itself (invariant!)
- The complement of a negative number is based on its original code, with the sign bit unchanged, the rest taken as negation, and finally+1 (i.e.+1 on the basis of the inverse code)
Actually, I can figure it out now, -0 has actually been eliminated! Let's take a look at the above calculation:
1+(-1)=0001+1111=(1) 0000=>+0 (No matter how you calculate it now, there won't be -0!)
So now, the range that 4-bit bits can represent is -8~+7 (Java uses complement!)
The above content is the key and essential knowledge to master. These knowledge are your final line of defense in the interview! With these theoretical foundations, no matter how the interview questions change, they can be solved through theoretical knowledge
Integer type
The integer type is the easiest to understand type! Now that we know how binary numbers are represented in computers, we can easily express our decimal content in binary form.
In Java, integer types include the following:
- Byte type (8 bits, i.e. 1 byte) range: -128~+127
- Short short integer (16 bits, i.e. 2 bytes) range: -32768~+32767
- The most commonly used type of int integer (32 bits, which is 4 bytes)!
- Long long integer (64 bits, which is 8 bytes) needs to be added with l or L at the end
The number has reached the maximum value of byte, can we still add it? For ease of understanding, take 4bit as an example:
0111+0001=1000=>-8 (You're right, that's it!)
Integers can also be represented in octal or hexadecimal:
- Decimal is 15=octal is 017=hexadecimal is 0xF=binary is 1111 (binary cannot be used in code!)
Character types and strings
In Java, there are character types that can represent a character:
- The char character type (16 bits, which is 2 bytes without symbols!) ranges from 0 to 65535
- Using Unicode representation means: u0000~ uffff
Characters should be enclosed in single quotes! For example, char c='gan';
Characters are essentially numbers, but these numbers are mapped through encoding tables to represent different characters. For example, the ASCII code of character 'A' is the number 65, so the char type can actually be converted to the integer type above.
Java's char uses a Unicode encoding table (not ASCII encoding!), which contains all the content of ASCII and also includes languages from all over the world. ASCII only has 1 byte, while Unicode encoding is 2 bytes, which can represent 65536 different types of text, enough to contain text from all over the world!
Since char can only represent one character, how can it contain one sentence? (Regarding arrays, we will not understand them at this point. We will explain arrays in the object-oriented chapter)
String is the string type in Java (note that it is a class, and the string created is essentially an object, not our basic type). A string, like its name, represents a string of characters, which is a complete sentence.
Enclose the string in double quotes! For example, String str="Three meals a day without worries";
Decimal Type
Decimal types are difficult to understand (referring to principles, not usage). First, let's take a look at what decimal types in Java include:
- Float single precision floating-point (32bit, 4 bytes)
- Double double precision floating-point (64bit, 8 bytes)
According to the international standard IEEE 754, any binary floating point number V can be expressed in the following form:
V = (-1)^S × M × 2^E
(1) (-1) ^ S represents the sign bit, when S=0 and V is a positive number; When S=1, V is a negative number.
(2) M represents a significant number, greater than or equal to 1 and less than 2, but the integer part of 1 remains unchanged, so it can be omitted. For example, if the mantissa is 1111010, then M is actually 1.111010. The first digit of the mantissa must be 1, followed by a decimal point. If 0001111 occurs, remove the previous 0 and move it to the first digit. As a side note: Over time, the IEEE 754 standard defaults to the first digit as 1. Therefore, in order to store more data, the first digit is omitted. For example, when saving 1.0101, only 0101 is saved, which can store one more digit According to)
(3) 2^E represents the exponential position. (Used to move the decimal point)
For example, the binary corresponding to 5.25 in decimal is 101.01, which is equivalent to 1.0101*2^2. So, S is 0, M is 1.0101, and E is 2. So, for floating-point types, the maximum and minimum values not only depend on the sign and mantissa, but also on their order codes. We won't calculate here, but if you want to know more, you can search for relevant information.
Thinking: Even if double has 64 bits, there are still accuracy limitations. What if I want to perform high-precision calculations?
Boolean type
Boolean types only have true and false values, which are either true or false. Variables of Boolean type are usually used as process control judgment statements. (C language generally uses 0 to represent false, and all numbers except for 0 represent true.) The size of space occupied by Boolean types is not clearly defined, but varies depending on the JVM.
Type conversion
Implicit type conversion
Implicit type conversion supports automatic conversion of types with small bytes to types with large bytes, and automatic conversion of integer types to decimal types. The conversion rules are as follows:
- byte→short(char)→int→long→float→double
Question: Why is long larger than float and can it still be converted to float? The storage rules for decimals make the maximum value of a float larger than a long, but it may lose precision in certain places!
So, the following code can run normally:
byte b = 9;
short s = b;
int i = s;
long l = i;
float f = l;
double d = f;
System.out.println(d);
//output 9.0
Display Type Conversion
Display type conversion is also known as forced type conversion, which means violating the rules of implicit conversion and sacrificing precision to force type conversion.
int i = 128;
byte b = (byte)i;
System.out.println(b);
//output -128
Why is the result -128? The accuracy is lost!
- 128 of int type represents: 000000 000000 000000 000000
- After converting the byte type, it represents: xxxxxxxx xxxxxxxx xxxxxxxx 10000000=>-128
Automatic data type elevation
When participating in an operation (which can also be in an expression, except for self increasing and self decreasing), all byte, short, and char values will be promoted to int:
byte b = 105;
b = b + 1; // report errors!
System.out.println(b);
This feature is defined by the Java Virtual Machine specification and is also intended to improve the efficiency of the operation. Other features include:
- If an operand is of type long, the calculation result is of type long
- If an operand is of float type, the calculation result is of float type
- If an operand is of double type, the calculation result is of double type
Operator
Assignment and arithmetic operators
The assignment operator=is the most commonly used operator, which actually passes the result on the right side of our equal sign to the variable on the left side of the equal sign, for example:
int a = 10;
int b = 1 + 8;
int c = 5 * 5;
The arithmetic operators, also known as+- */%, which we learned in elementary school, represent addition, subtraction, multiplication, division, and remainder, for example:
int a = 2;
int b = 3;
int c = a * b;
//Result is 6
It should be noted that+can also be used as a string connector:
System.out.println("lbw" + "nb"); //lbwnb
Of course, strings can be directly connected to other types, but they will all be treated as strings:
int a = 7, b = 15;
System.out.println("lbw" + a + b); //lbw715
The arithmetic operators also include++and -, which are self increasing and self decreasing, taking self increasing as an example:
int a = 10;
a++;
System.out.println(a); //output is11
There are differences in the return values of the self increasing and self decreasing operators before and after variables:
int a = 10;
System.out.println(a++); //10 (First return the value, then autoincrement)
System.out.println(a); //11
int a = 10; System.out.println(++a); //11 (First autoincrement, then return value) System.out.println(a); //11
int a = 10;
int b = 2;
System.out.println(b+++a++); //Guess what the result is
To make the code more concise, you can also use extended assignment operators, including+=, -=,/=, *=,%=, similar to autoincrement and autodecrement, which perform the operation first, return the result, and change themselves:
int a = 10;
System.out.println(a += 2); //Equivalent to a=a+2
Relational Operators
The result of a relational operator can only be a Boolean type, which means it is either true or false. The relational operators include:
> < == //
>= <= != //
Relational operators are generally only used for comparison of basic types, and the result of the operation can only be a boolean:
int a = 10;
int b = 2;
boolean x = a > b;
System.out.println(x);
//Result is true
Logical operator
Both sides of the logical operator can only be Boolean types or relational/logical operation expressions, and the return value can only be Boolean types! Logical operators include:
&&//AND operation requires both sides to be true in order to return true
||//OR operation, requires at least one on both sides to be true in order to return true
! // Non operations, usually placed at the beginning of an expression, are enclosed in parentheses to indicate the reversal of the result of the expression
Let's take a look at the actual case:
int a = 10;
int b = 2;
boolean x = a > b && a < b; //How can it be satisfied at the same time
System.out.println(x); //false
int a = 10; int b = 2; boolean x = a > b || a <= b; //There must be a satisfaction! System.out.println(x); //true
int a = 10;
int b = 2;
boolean x = !(a > b); //Reverse the result, which should have been true
System.out.println(x); //false
Bitwise operator
&//Bitwise AND, note that the returned value is of the same type after the operation, not a boolean!
|//Bitwise or
^//bitwise XOR 0 ^ 0=0
~//Bitwise non
Bitwise operations actually calculate results based on the binary encoding of values, such as bitwise and, taking 4bit as an example:
0101&0100=0100 (1 is only obtained if both bits correspond to 1)
int a = 7, b = 15;
System.out.println(a & b); // The result is 7
Process Control
Our programs are all run from top to bottom, but that's not enough. We need more advanced control statements to help me achieve more flexible control. For example, to determine the number input by a user, if it is greater than 1, an OK will be output, and if it is less than 1, an NO will be output. In this case, we need to use a selection structure to help us determine the conditions and branch the program. Learning C language is easy!
Select Structure
Selecting structures that include if and switch types can help us determine which block of code to execute based on conditions.
If statement
As mentioned above, to determine the number entered by the user, if it is greater than 1, it will output OK, and if it is less than 1, it will output NO. To achieve this effect, we can first use the if statement:
If (judgment condition){
//Determine the content of successful execution
}else{
//Determine the content of failed execution
}
//After the execution of the if content is completed, the subsequent content is executed normally
Among them, the else statement is not mandatory. Now, there is a new requirement. The user inputs 1 to print OK, 2 to print Yes, and the others to print No. This requires us to make multiple conditional judgments, and of course, if can make multiple branch judgments:
If (judgment condition 1){
//Determine the content of successful execution
}Else if (judgment condition 2){
//Once again, if the successful execution of the content is judged
}else{
//None of the above were successful, we can only go here
}
Similarly, the else statement is not mandatory.
Now, there is a new requirement. After the user inputs 1, they can determine what the user will input next. If it is 1, print yes, otherwise print no, so that nested if can be used:
If (judgment condition 1){
//The premise is that condition 1 must be successful in order to enter!
If (judgment condition 2){
//Determine the content of successful execution
}else{
//Determine the content of failed execution
}
}
Switch statement
We can easily see that although else if can solve the problem of multi branch judgment, its efficiency is really too low. Multi branch if uses step-by-step downward judgment, which is obviously time-consuming and laborious. So, is there anything that has always been more professional in solving multi branch judgment problems?
Switch (judgment subject){
Case value 1:
//Run xxx
break; // Break is used to jump out of the switch statement, not adding it will cause the program to continue running downwards!
Case value 2:
//Run xxx
break;
Case value 3:
//Run xxx
break;
}
In the above statement, the statement in the case will only be executed if it is determined that the subject is equal to the value after the case. At the same time, it is necessary to use break to jump out of the switch statement, otherwise it will continue to run downwards!
Why is a switch more efficient? Because a switch uses a binary approach for searching (which is also why a switch can only determine equal values), it can quickly find the results we want!