A, Java
Java was born in 1995 and was originally owned by Sun. On April 20, 2009, Oracle (ORACLE) announced that it was buying Sun for $7.4 billion. Java is the most popular development language, has been hot for 20 years, and continues to be the leading programming language in IT. JAVA LOGO is a cup of steaming hot coffee, really is memorable
1.1 Why Java is platform-independent (can be cross-platform)
Traditional language
The Java language
Java programs can be compiled to produce a platform-independent file called a.class. Only the Java Virtual Machine (JVM) can recognize bytecode files, so in order to run the Java program on Windows, we have to install the Windows version of the JVM on Windows. If you want to run on a Mac, you will need to install the Mac version of the JVM. To sum up, here are two things:
- Java compiles to produce platform-independent.class files
- The JVM is platform-dependent
The tool that does the compilation here is called javac, and the tool that starts the JVM and loads the bytecode into the JVM is called Java
Second, the Java environment
2.1, the JRE
Java Runtime Environment (JRE) : Java Runtime Environment (JRE) : Java Runtime Environment (JRE) : Java Runtime Environment (JRE) : Java Runtime Environment (JRE) : Java Runtime Environment (JRE) : Java Runtime Environment (JRE) : Java Runtime Environment (JRE) : Java Runtime Environment (JRE) : Java Runtime Environment (JRE)
2.2, the JDK
JDK(Java Development Kit) : Java Development tools, including all the tools for developing Java programs such as javac and Java, the JDK contains the JRE, if you have installed the JDK do not need to install the JRE
2.3, the JVM
JVM (Java Virtual Machine) :Java Virtual Machine, which is the Virtual Machine that runs all Java programs. The JVM is non-cross-platform, with the Windows JVM under Windows and the Linux JVM under Linux
Third, the mechanism of Java compilation and operation
- Write source files (Java files)
- Use Java C tools to compile the source file (Java C source file.java) to generate.class files
- After generating the bytecode file (.class file), use Java tools to start the JVM and run the program (the class name of the Java main method)
4. JAVA Foundation
4.1. Grammar rules
- The Java language is strictly case-sensitive, and uppercase and lowercase are different concepts
- Multiple Java classes can be defined in a Java source file, but at most one of them can be defined as a public class. However, if the source file contains a public class, the source file must have the same name as the public class
- When a source file contains N Java classes, a successful compilation generates N bytecode files, each of which generates a separate.class file with the same bytecode filename as its corresponding class name
- If a class wants to run, it must have a main method (main), which is the entry point to the program
4.2, comments,
Java provides three annotation types:
- Single-line comments
// This is a single-line comment // shortcut key :Ctrl+/
- Multiline comment
/* I am a multi-line comment shortcut key: type /* and press Enter */
- Documentation comments
/* * * I am a document type * The shortcut is: type /* and then press the TAB key */ several times
Multiple line comments cannot be cross-nested with each other because/
Will look for examples of their own nearest/
Symbol that forms a comment statement block, as shown in the figure above* /
The symbol is not recognized by the compiler
4.3. Key words and reserved words
The keyword
Keyword: A predefined word in a programming language that has a specific meaning and purpose
Reserved words
Retained words: words that, like keywords, are pre-defined by the programming language, but do not currently have a special function, but may be given a function suddenly at a later date and are therefore retained. For example, goto and const are reserved words
4.4, delimiters and identifiers
4.4.1. Separators
- Semicolon (;) : Split a sentence to indicate the end of a sentence, like we use full stop.
- Curly braces ({}) : denote a block of code as a whole. Use curly braces in pairs.
- Square brackets ([]) : Used when defining an array and accessing its elements.
- PARENTHESES (()) : These are widely used, but are used in more detail.
- Dot (.) : Used by a class and object when accessing its members.
- Spaces () : to divide a whole statement into several paragraphs. The number of Spaces is unlimited, just like the words in an English sentence should be written separately.
4.4.2 Identifiers
In order to enhance the readability of the code, we will customize a lot of names such as: class name, method name, variable name, etc. In programming, we refer to these names as identifiers, which are custom-made to enhance the readability of a program
Naming rules for identifiers:
- Consisting of letters, numbers, underscores, $, but cannot begin with a number (Note: here the letter can be Chinese, Japanese, etc.)
- Case sensitive
- You cannot use keywords and reserved words in Java
- You cannot use class names built into Java
4.5. Data types
Note :Java only has 8 large data types. String is not a primitive data type. It is a reference data type
The most common integer types are int and long, byte and short are rarely used, and the most common decimal types are double, and float are rarely used. Since double is imprecise, we use the BigDecimal class to represent exact decimals in real development
- Integer types default to int and decimal types default to double
- Constants of type long (L or L, recommended)
- Denotes a constant of type float, plus F or F is recommended
Five, the variable
A variable is an area of memory to which data can be stored, modified, or retrieved. If a variable is not initialized, it means that no memory space is allocated for storage and it cannot be used
The syntax for defining variables is as follows:
- String, which means type, you can write any type here
- Name: variable name, the same as our name, no why
- The = : assignment operator, as we’ll see later, assigns the value on the right to the variable on the left
- “XIAOLIN” : A value of type string, otherwise not enclosed in quotation marks
Variables have several characteristics:
- Occupying a certain area of memory
- This field has its own variable name and data type
- It can be reused
- The value of a variable in this region can change continuously within the same type range
5.1 Definition and Assignment of Variables
Public class varDemo {public static void main(String[] args) {public static void main(String[] args) { Int age; // Variable name = constant value; // Define a variable of type int, starting with 17 int name; // change the age variable to 17 age = xiaolin; System.out.println(age); // The datatype variable name = the initializer value; String name = "zs"; String name = "zs"; }}
Note the following points when using variables:
- Variables must be declared and initialized before they can be used (except by defining wrapper classes).
- Define variables must have data types
- Variables can be used from the beginning of their definition to the scope in which they are defined, but cannot be used outside the scope, and variable names cannot be repeated within the same scope
Definitions of several common variable types:
Public class varDemo {public static void main(String[] args) {// Byte b = 20; System.out.println(b); //short = 20; System.out.println(s); //int I = 20; System.out.println(i); //long = 20L; //long = 20L; System.out.println(l); Float F = 3.14f; float F = 3.14f; System.out.println(f); //double d = 3.14; System.out.println(d); //char type variable char c = 'A'; System.out.println(c); // Boolean type variable Boolean bb = true; System.out.println(bb); //String STR = "Hello "; System.out.println(str); }}
5.2. Exchange the values of two variables
Train of thought
- Store the value of num1 in a temporary variable called temp
- Assigns the value of num2 to the num1 variable
- Assigns the value stored in temp to the num2 variable
The implementation code
public class ChangVarDemo{ public static void main(String[] args) { int num1 = 10; int num2 = 20; System.out.println("num1=" + num1); System.out.println("num2=" + num2); / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / interactions int temp = num1; num1 = num2; num2 = temp; //-------------------------------- System.out.println("num1=" + num1); System.out.println("num2=" + num2); }}
6. Expressions
An expression is a combination of numbers, operators, parentheses, constants, variables, etc., to obtain a result
Seven, data type conversion
Of the eight basic data types, Boolean is not a numeric type and therefore does not participate in the conversion. The conversion rules for the other types are shown below. In general, byte, short, and char types do not convert each other. There are two types that convert each other (note: Boolean types do not convert) :
- Automatic type conversion: Small range data type is directly converted to large range data type, small -> large
- Cast: A large-range data type is cast to a small-range data type, large-> is small
7.1. Automatic type conversion and promotion
7.1.1 Automatic type conversion
Automatic type conversion, also known as implicit type conversion, is a direct conversion of a small range of data types to a large range of data types
Conversion rules: byte, short, char — >int — >long — >float — >double
Note: byte, short, and char are not converted to each other. They are first converted to int
Syntax format: large-range data type variable = small-range data type value
Public class TypeConvertDemo1{public static void main(String[] args) {// Enables a longNumber = 17; // Convert long type to float type float f1 = longNumber; // Convert float to double double d = f1; Int a1 = 2; int a1 = 2; int b1 = 3; int c1 = a1 + b1; // byte b2 = 2; // byte b2 = 2; int c2 = 3; System.out.println(b2 + c2); //byte d1 = b2 + c2; //byte d1 = b2 + c2; Int d3 = b2 + c2; // compile through}}
7.1.2. Automatic type promotion
When an arithmetic expression contains constants or variables of more than one primitive data type (except Boolean), the result type of the entire arithmetic expression is automatically promoted. The rule is:
- All byte, short, and char types are automatically promoted to int before being evaluated
- The final result type of the entire expression is promoted to the highest type in the expression
System.out.println('a' + 1); //98 byte b = 22; b = b + 11; Double d1 = 123 + 1.1f + 3.14 + 99L; double d1 = 123 + 1.1f + 3.14 + 99L; double d1 = 123 + 1.1f + 3.14 + 99L;
Conclusion: The type of the result of an arithmetic expression is the widest of the data types.
7.2. Cast casting
Cast casts, also known as “explicit casts,” are casts from a wide range of data types to a small range of data types
(small range data type) = (large range data type value);
Note: It is generally not recommended to use strong turns, as strong turns may lose accuracy
public class TypeConvertDemo2{ public static void main(String[] args) { int a = 2; byte b = 3; Int c = a + b; // cast byte d = (byte) (a + b); Int I = (int)3.14; int I = (int)3.14; System.out.println(i); / / 3}}
Operators
The symbols that operate on constants and variables are called operators
Common operators are arithmetic operators, assignment operators, comparison operators, logical operators, and triple operators
8.1. The arithmetic operator
The operator | Operational rule 1 | The sample | The results of |
---|---|---|---|
+ | A plus sign | + 3 | 3 |
+ | add | 52 + 3 | 5 |
+ | Concatenation string | “China “+” Guo” | “China” |
– | symbol | int a = 3 -a |
– 3 |
– | Reduction of | 3-1 | 2 |
* | take | 2 * 3 | 6 |
/ | In addition to | 5/2 | 2 |
% | modulus | 5% 2 | 1 |
++ | Since the increase | int a = 1<br/>a++(++a) | 2 |
— | Since the reduction of | int b =2 <br/>b–(–b) | 1 |
8.2. Increment and Decrease
Increment: The ++, increment operator, increments the value of a variable by 1. There are prepositions and postpositions. It can only operate on variables.
Decrease: –, the decrement operator that subtracts 1 from the value of a variable. It operates on variables only.
Take ++ as an example:
A ++ and ++ A both result in increment of A by 1, but if you only want increment of A, you can use either one
But there was one difference between them:
- Preposition (++a) : Indicates the operation of the result after a is added by 1, adding first and then using
- Postset (a++) : Operates on the value (original value) before the increment of a variable
public class ArithmeticOperatorsDemo2{ public static void main(String[] args) { int a1 = 5; int b1 = ++ a1; System.out.println("a1=" + a1 + ",b1=" + b1); //a1=6,b1=6 int a2 = 5; int b2 = a2 ++; System.out.println("a2=" + a2 + ",b2=" + b2); //a2=6,b2=5 } }
Lower level explanation
A ++ means take the address of A, increment its contents, and put the value in the register. A ++ means take the address of A, load its value into the register, and increment the value of A in memory
8.3 Assignment Operator
The operator | algorithm | The sample | The results of |
---|---|---|---|
= = | Is it equal to | 4 = = 3 | false |
! = | Is it not equal to | ! 4 = 3 | true |
< | Less than | 4 < 3 | false |
> | Is greater than | 4 > 3 | true |
< = | Less than or equal to | 4 < = 3 | false |
> = | Greater than or equal to | 4 > = 3 | true |
8.4 Ternary Operator
The ternary operator, which represents an expression involving three elements, is also known as the ternary operator, whose semantics refer to if-else (do if, do otherwise).
Syntax format: data type variable = Boolean expression? Result A: Result B
The meaning of the expression, Boolean expression Result:
- If true, the result of the ternary operator is result A
- If false, the result of the ternary operator is result B
Note:
- A ternary operator must define a variable to accept the result of the operation, otherwise an error is reported
- The type of the result of the ternary operator is determined by results A and B, which are of the same type
8.5. Logical Operators
The logical operator is used to concatenate two Boolean expressions, and the result is also of type Boolean
The operator | algorithm | demonstration | The results of | ||||
---|---|---|---|---|---|---|---|
& | with | false & true | false | ||||
\ | or | false \ | true | true | |||
^ | Exclusive or | true ^ false | true | ||||
! | non | ! true | false | ||||
&& | Short circuit and | false && false | false | ||||
\ | \ | Short circuit or | false \ | \ | false | true |
Rule:
- Non: inverse,! True or false,! False is true
- And: false is false
- Or: true if true
- XOR: ^ false if same, true if different
8.5.1, & and && (| and | |)
& : & The left-hand expression evaluates whether it is true or false
&& : If the left expression of && is true, the right expression of && participates in the operation, otherwise the right expression of && does not participate in the operation, so it is called short circuit and
| and | | for the same reason, the difference between a | |, the left is true, the right not to participate in the operation
public class LogicalOperatorDemo2 { public static void main(String[] args) { System.out.println(false & 1 / 0 == 1); Println (false &&1/0 == 1); println(false &&1/0 == 1); println(false &&1/0 == 1); / / don't complain that are not performed on the right System. Out. The println (true | 1/0 = = 1); / / an error, the right to perform the System. The out the println (true | 1/0 = = 1); // no error: no}}
Nine, arrays,
9.1 Preliminary exploration of the JVM
- Program counter: An indicator of the line number of bytecode being executed by the current thread
- Local method stack: Serves native methods used by the virtual machine
- Method area: A thread-shared memory area that stores information, constants, and static variables for classes that have been loaded by the virtual machine. The main goal of memory collection in this area is to retrieve the constant pool and unload the type
- Java Virtual Machine Stack: Stack for short. Each method is executed and a stack frame is created to store the method’s local variables, operation stacks, dynamic links, method exits, etc
- The Java heap: An area of memory shared by all threads that is started when the virtual machine is created.
Instances of all objects (new objects)
As well asAn array of
Allocate memory space on the heap,So the heap takes up much more memory than the stack
- Each time a method is called, a stack frame is created that holds local variables of the current method. When the method is called, the stack frame for the method is destroyed
- Every time we create an object, we create a new chunk of memory
9.2, arrays,
9.2.1 What is an array
A form of data in which multiple constant values of the same type are organized in an orderly manner. An array uses an index to indicate where the elements are placed. The index starts at 0 and has a step size of 1, similar to the line number of an Excel spreadsheet
9.2.2. Define the syntax
Array element type [] array name; int [] nums;
Note:
- You can think of int[] as a data type, an array type of int
- An int[] array indicates that the elements in this array are of type int
9.2.3 Initialization of Arrays
After an array is defined, it must be initialized before it can be used. To initialize an array, allocate space in the heap memory and assign an initial value to each element. There are two ways to do this: Static initialization and dynamic initialization, the length of the array is fixed, no matter in which, once the initialization is complete, the length of the array (the number of elements) is fixed, does not change, unless it is in the initialization, initialization time, if we clear the specific elements with static initialization, if still don’t know exactly which elements, only know number, using dynamic initialization
9.2.3.1 Static initialization
We directly set the initialization value for each array element, and the array length is determined by the system (JVM)
Syntax: array element types [] array name = new array element types [] {elements 1, 2, 3, elements,… };
Int [] nums = new int[]{1,3,5,7,9}; Int [] nums = {1,3,5,7,9}; // The definition and initialization must be written at the same time
9.2.3.2 Static initialization memory analysis
Public class ArrayDemo1{public static void main(String[] args) {public static void main(String[] args) {// ArrayDemo1 = new Int [] {1, 3, 5, 7}; System.out.println(" array length =" + nums.length); // Reinitialize nums = new Int [] {2, 4, 8}; System.out.println(" array length =" + nums.length); }}
If num = null, null means that the memory space in the heap is no longer referenced, and nums is uninitialized and cannot be used
9.2.3.4 Dynamic Initialization
The programmer sets only the number of elements in the array, and the initial value of the elements in the array is determined by the system (JVM)
ArrayName = new ArrayName [length]; ArrayName = new ArrayName [length];
int[] nums = new int[5];
Int [] nums = new int[5]{1,3,5,7,9} int[] nums = new int[5]{1,3,5,7,9
The memory graph is the same as static initialization, except that it has default values
9.2.4 Operations on Elements in Arrays
9.2.4.1 Get the number of elements
Int size = array name.length;
9.2.4.2 Set Elements
nums[1] = 30;
9.2.4.3 Get the element
Element type variable name = array name [index];
9.2.5 Common Exceptions in Arrays
- NullPointerException: Null pointer exception (null reference exception)
Operates on an array that has not been initialized or allocated memory space
- ArrayIndexOutOfBoundsException: index of an array of cross-border anomalies
The index of the array operated on is not in the range [0, array name.length-1]
9.2.6 Array traversal
9.2.6.1, for loop
int[] nums = new int[] { 1, 3, 5, 7 }; for (int index = 0; index < nums.length; index++) { int ele = nums[index]; //index = 0, 1, 2, 3, System.out.println(ele); }
9.2.6.2, For-each (enhanced for loop)
For (array element type variable: array){//TODO}
int[] nums = new int[] { 1, 3, 5, 7 };
for (int ele : nums) {
System.out.println(ele);
}
Using the for-each array is simpler because you can ignore the index, and the underlying principle is the same as the for-loop array above
9.2.7 Two-dimensional Arrays
Before, each element of an array was a value, and this type of array is called a one-dimensional array. A two dimensional array, which means that each element in the array is another one dimensional array
9.2.7.1. Definition and initialization of two-dimensional arrays
static
Public class ArrayInArrayDemo1 {public static void main(String[] Args) {int[] Array1 = {1, 2, 3}; int[] arr2 = { 4, 5 }; int[] arr3 = { 6 }; Int [][] arr = new int[][] [] {arr1, arr2, arr3}; int[][] arr = new int[][] {arr2, arr3}; }}
The element type of a two-dimensional array is a one-dimensional array. The element type [] of the array is regarded as a whole and represents the data type
dynamic
ArrayName = new ArrayName [x][y]; ArrayName = new ArrayName [y]; X means how many one-dimensional arrays there are in a two-dimensional array and Y means how many elements there are in each one-dimensional array. int[][] arr = new int[3][5];
9.2.7.2 Get the elements of a two-dimensional array
The for loop
for (int index = 0; index < arr.length; Index2 ++) {int[] arr2= arr[index]; // Iterate for (int j = 0; j < arr2.length; j++) { int ele = arr2[j]; System.out.println(ele); } System.out.println("-----"); }
for-each
For (int[] arr2: arr) {for (int ele: arr2) {for (int ele: arr2) {System.out.println(ele); } System.out.println("-----"); }
Ten, methods,
10.1 Definition of methods
Method: A block of code designed to perform a specific function (sum, count, etc.)
Syntax format:
Returns value type method name (parameter type parameter name 1, parameter type parameter name 2,...) {method body; [return value;] }
Format analysis:
- (static, public, static, etc.); (static, public, static); (static, public, static)
-
Return value type: Does a method need to return a result to the caller after completing a function, as defined by the type of return value?
- If you need to return a result to the caller, write the type of data to be returned
- If you do not need to return a result to the caller, use a keyword
void
, indicating that no result is returned
- Method name: Used to call a method, follows the identifier specification, starts with a lowercase letter, uses hump nomenclature, knows what you mean by your name
- Formal arguments: Variables in parentheses within a method that can have more than one formal argument
- Method body: Write the code for how this function is accomplished
-
The function of the return keyword
- Returns the value to the caller of the method
- End the method. No more statements can be learned after return
- When there is no return in the method body, the return value of the method must be void
- Actual arguments: The value of the arguments that are actually passed when a specific method 1 is called
- If a return value is required, make sure that the return value is required under any conditions
Matters needing attention
- A method must be defined in a class, and the smallest unit of programming in Java is a class
- You can define more than one method in a class
- Methods are parallel to each other. You cannot define a method within a method (you cannot build a house inside a house).
- Method definitions are in no order
10.2 Method invocations
If a method is statically decorated, it can be called directly with the class name of the class in which the method is located. If it is not statically decorated, it must be called using an instantiated object
10.3. Method overloading
Arguments list: type of argument + number of arguments + order of arguments
Method signature: method name + method parameter list
In the same class, the method signature is unique, otherwise the compiler will report an error
Method overloading: One or more methods of the same name are allowed for a method in the same class, but only if the argument list is different
10.3.1. How is method overloading
The principle of method overloading judgment: two identical different
Duplex: Within the same class, the method name is the same
One difference: the parameter list of the method is different (parameter type, parameter number, parameter order), as long as the parameter type, parameter number, parameter order of one of the difference, it is the parameter list is different
Method overloading is independent of the return value type, except that it is generally required to have the same return value type
10.3.2 The role of method overloading
It solves the problem that methods with the same function need to be named repeatedly because of different method names caused by different parameters