A, Java

Java was born in 1995 and was originally owned by SUN. On April 20, 2009, Oracle, an American data software giant, announced its acquisition of SUN for 7.4 billion dollars. Java, the most popular development language, has been hot for 20 years and continues to lead the IT programming language. The LOGO of Java is a steaming cup of coffee, which is really memorable

1.1 Why Java is Platform Independent (cross-platform)

Traditional language

The Java language

Java programs can be compiled to generate platform-independent files called bytecode files (.class). However, neither Windows nor Linux can execute bytecode files. Only Java Virtual Machine (JVM) can recognize bytecode files. Therefore, in order to run the Java program on Windows system, we can only install Windows VERSION JVM on Windows platform. If you want to run it on a Mac, you need to install the Mac version of the JVM.

  1. Java is compiled to generate platform-independent.class files
  2. 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

Java environment

2.1, the JRE

Java Runtime Environment (JRE) : A Java Runtime Environment. If you want to run Java programs, you need to support THE JRE. The JRE contains the JVM and is generally installed on a server that only runs programs but does not develop programs

2.2, the JDK

Java Development Kit (JDK) : A Java Development tool that contains all the tools for developing Java programs, such as Javac and Java. The JDK contains the JRE. If the JDK has been installed, you do not need to install the JRE

2.3, the JVM

Java Virtual Machine (JVM) : A Java Virtual Machine that runs all Java programs. The JVM is not cross-platform. You install the Windows JVM under Windows and the Linux JVM under Linux

Java compile and run mechanism

  1. Writing source files (Java files)
  2. Use the Java C tool to compile the source file (Java C source file. Java) to generate a. Class file
  3. After generating the bytecode file (.class file), start the JVM using a Java tool and run the program (class name of the Java main method)

Iv. Java Basics

4.1. Grammar Rules

  1. The Java language is strictly case sensitive, and uppercase and lowercase are different concepts
  2. A Java source file can define multiple Java classes, but only one of them can be defined as a public class. If the source file contains a public class, the source file must have the same name as the public class
  3. If a source file contains N Java classes, N bytecode files will be generated after successful compilation, and each class will generate a separate. Class file with the same bytecode file name as its corresponding class name
  4. For a class to run, it must have the main method, which is the entry point to the program

4.2, comments,

Java provides three annotation types:

  1. Single-line comments
// This is a one-line comment
// Shortcut key :Ctrl+/
Copy the code
  1. Multiline comment
/* I am a multi-line comment shortcut for: type /* then press Enter */
Copy the code
  1. Documentation comments
     /* * * I am document type * shortcut keys are: type /* and then press the TAB key */
Copy the code

Multi-line comments can’t be cross-nested with each other because/Will find examples of their most recent/Symbols that form a comment block, as shown in figure 1* /The symbol is not recognized by the compiler

4.3. Keywords and Reserved Words

The keyword

Keywords: pre-defined words in a programming language that have a special meaning and purpose

Reserved words

Reserved words: Words that, like keywords, are defined by the programming language to be reserved because they do not have a specific function at the moment but may be suddenly given a function at some point in the future. Such as goto and const are reserved words

4.4 delimiters and identifiers

4.4.1. Delimiters

  1. Semicolon (;) : The division of statements, indicating the end of a sentence, like the period we use.
  2. Curly braces ({}) : represents a code block as a whole. Curly braces should be used in pairs.
  3. Square brackets ([]) : Used when defining arrays and accessing array elements.
  4. Parentheses (()) : this is widely used.
  5. Dot (.) : used when classes and objects access their members.
  6. Space () : To divide a whole sentence into several paragraphs with no limit on the number of Spaces, just as words are written separately in English.

4.4.2 Identifiers

In order to make the code more readable, we will customize a lot of names: class names, method names, variable names, etc. In programming, we call these custom names, which are used to make programs more readable, identifiers

Naming rules for identifiers:

  1. The name contains letters, digits, underscores (_), and $, but cannot start with a number (note: The letters can be In Chinese or Japanese).
  2. Case sensitivity
  3. Java keywords and reserved words cannot be used
  4. Cannot use class names built into Java

4.5. Data types

Note :Java has only eight big data types. String is not a basic data type. It is a reference data type

The most common integer types are int and long, byte and short are rarely used, and decimal types are double and float are rarely used. Because double is imprecise, we use the BigDecimal class to represent exact decimals in real development

  1. The default integer type is int and the default decimal type is double
  2. Represents a constant of type long. Either L or L is recommended
  3. Represents a constant of type float. If you want to add F or F, F is recommended

Five, the variable

A variable is an area of memory to which data can be stored, modified, and retrieved. If a variable is not initialized, it means that there is no memory allocated for storage and cannot be used

The syntax for defining variables is as follows:

  • String, for type, you can write any type here
  • Name: the variable name, as understood by our name, no why
  • The = : assignment operator, as we’ll see later, means to assign the value on the right to the variable on the left
  • “Xiaolin” : a string value, unquoted if any other type

Several characteristics of variables:

  1. Occupying a storage area in memory
  2. The field has its own variable name and data type
  3. It can be reused
  4. The variable values in this region can vary over time within the same type range

5.1 Definition and assignment of variables

public class VarDemo{
	public static void main(String[] args) {
        // Define a variable first, then assign a value
		// Data type variable name; Such as: int age;
		// Variable name = constant value;
		// Define a variable of type int with an initial value of 17
		int name;
		// Change the age variable to 17
		age = xiaolin;
		System.out.println(age);
        // Set the value of the declaration at the same time (recommended)
		// Data type variable name = initialization value;
        // Define a variable of type String with the initial value zs
        String name = "zs"; }}Copy the code

Note the following points when using variables:

  1. Variables must be declared before they are used and initialized before they can be used (except for defining wrapper classes)
  2. Definition variables must have data types
  3. Variables can be used from the beginning of the definition to the scope of the variable, but not outside the scope, and variable names within the same scope can not be repeated

Definitions of several common variable types:

public class VarDemo{

	public static void main(String[] args) {

		// a byte variable
		byte b = 20;
		System.out.println(b);

		//short variable
		short s = 20;
		System.out.println(s);

		// Variable of type int
		int i = 20;
		System.out.println(i);

		// a variable of type long, using the L suffix
		long l = 20L;
		System.out.println(l);

		// A variable of type float, using the suffix F
		float f = 3.14 F;
		System.out.println(f);

		// Double
		double d = 3.14;
		System.out.println(d);

		// a char variable
		char c = 'A';
		System.out.println(c);

		// Boolean type variable
		boolean bb = true;
		System.out.println(bb);

		// A String variable
		String str = "Hello"; System.out.println(str); }}Copy the code

5.2. Swap two variable values

Train of thought

  1. Store the value of num1 in the temporary variable temp
  2. Assign the value num2 to the num1 variable
  3. Assign the temp stored value to 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);
		//--------------------------------		
		// Interactive operations
		int temp = num1;
		num1 = num2;
		num2 = temp;
		//--------------------------------		
		System.out.println("num1=" + num1);
		System.out.println("num2="+ num2); }}Copy the code

Vi. Expressions

Expression is a combination of numbers, operators, parentheses, constants, variables, etc., to obtain the result

7. 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 other types are shown below. In general, the byte, short, and char types do not convert to each other. There are two types of conversion (note: Boolean types do not convert) :

  1. Automatic type conversion: Converts small data types directly to large data types, small -> large
  2. Cast: Casts a wide range of data types to a small range of data types, large -> small

7.1. Automatic type conversion and promotion

7.1.1. Automatic Type conversion

Automatic type conversion, also known as “implicit type conversion, is the 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: Wide range of data type variables = small range of data type values

public class TypeConvertDemo1{
	public static void main(String[] args) {
		// Convert a variable of type int to long
		long longNumber = 17;// Integer defaults to int
		// Convert long to float
		float f1 = longNumber;
		// Convert a float to a double
		double d = f1;
		
		// Define two variables of type int
		int a1 = 2;
		int b1 = 3;
		int c1 = a1 + b1;

		// Define a byte and an int
		byte b2 = 2;
		int c2 = 3;
		System.out.println(b2 + c2);

		// The byte, short, and char types participate in the operation to promote themselves to int
		//byte d1 = b2 + c2; // Compile error
		int d3 = b2 + c2;// The compiler passes}}Copy the code

7.1.2 automatic type promotion

When an arithmetic expression contains constants or variables of more than one basic data type (except Boolean), the result type of the entire arithmetic expression is automatically promoted as follows:

  • All byte, short, and char types are automatically promoted to ints and then evaluated

  • The resulting 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;// Compile error, result type should be int
double d1 = 123 + 1.1 F + 3.14 + 99L ;
Copy the code

Conclusion: The type of the result of an arithmetic expression is the largest range of data types.

7.2. Cast

Casts, also known as “explicit casting,” cast a wide range of data types to a small range of data types

# syntax:
# small datatype variable = (small datatype) large datatype value;
Copy the code

Note: In general, it is not recommended to use strong turns, because strong turns may lose accuracy

public class TypeConvertDemo2{
	public static void main(String[] args) {
		int a = 2;
		byte b = 3;
		// Automatic type conversion
		int c = a + b;
		// Cast
		byte d = (byte) (a + b);
		// Convert double to int
		int i = (int)3.14;
		System.out.println(i);/ / 3}}Copy the code

Operators

Symbols that operate on constants and variables are called operators

Common operators are divided into: arithmetic operators, assignment operators, comparison operators, logical operators, ternary operators

8.1 Arithmetic operators

The operator Operation Rule 1 The sample The results of
+ A plus sign + 3 3
+ add 52 + 3 5
+ Concatenated string “China “+” China” “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

a++(++a)
2
Since the reduction of int b =2

b–(–b)
1

8.2. Autoincrement and autodecrement

Increment: ++, the increment operator, increases the value of a variable by 1, has a pre – and post-divided, can only operate on variables.

Decrement: the decrement operator, which subtracts the value of a variable by 1.

Take ++ for example:

A ++ and ++a both increase the value of a by 1, if you just need to increment it, you can use either one

But there’s only one difference between them:

  1. Prefix (++a) : Computs the result after a is added to 1
  2. After (a++) : the value (original value) before adding 1 to variable A is calculated
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}}Copy the code

Compare the underlying interpretation

++a means take the address of A, increment its contents, and then put the value in a register a++ means take the address of A, put its value in a register, and then increment the value of A in memory

8.3. Assignment operators

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 operators

The ternary operator represents an expression with three elements, so it is also called the ternary operator. The semantics of the ternary operator are if-else (do if, do otherwise).

Data type variable = Boolean expression? Result A: Result B

Boolean expression result:

  • True, the result of the ternary operator is result A
  • If false, the result of the ternary operator is result B

Note:

  1. The ternary operator must define a variable to accept the result of the operation, otherwise an error is reported
  2. The type of the result of the ternary operator is determined by the result A and B, which are of the same type

8.5. Logical operators

The logical operator is used to join two Boolean expressions, and the result is 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: take reverse,! True or false,! False is true

  • And: False false

  • If there is true, there is true

  • Xor: ^ Same false, different true

8.5.1, & and && (| and | |)

& : & The right-hand expression is evaluated regardless of whether the left-hand expression is true or false

&& : If the expression on the left of && is true, the expression on the right of && participates in the operation; otherwise, the expression on the right 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);// The right side is executed
		System.out.println(false && 1 / 0= =1);// If no error is reported, the right side is not executed
		System.out.println(true | 1 / 0= =1);// The right side is executed
		System.out.println(true | 1 / 0= =1);// If no error is reported, the right side is not executed}}Copy the code

Nine, arrays,

9.1 Initial exploration of JVM

  • Program counter: An indicator of the line number of bytecode executed by the current thread
  • Native method stack: serves native methods used by virtual machines
  • Method area: an area of memory shared by threads that stores information, constants, and static variables about classes that have been loaded by the VIRTUAL machine. The goal of this area of memory reclamation is to recycle constant pools and unload types
  • Java virtual machine stack: short for stack, each method is executed and a stack frame is created to store the local variables, operation stack, dynamic link, method exit and other information of the method
  • 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 ofAllocate memory 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 the local variables of the current method. When the method is called, the stack frame of the method is destroyed
  • Each time an object is new, a new block of memory is created

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 order. An index is used to indicate the location of elements in an array. The index starts at 0 and steps 1, similar to the row number of an Excel table

9.2.2. Define the syntax

Array element type [] Array name; int [] nums;Copy the code

Note:

  1. You can think of int[] as a data type, an array type of type int
  2. An array of int[] means that the elements in this array are of type int, and so on

9.2.3 Array initialization

After an array is defined, it must be initialized to use it. Initialization refers to allocating storage space to an array in the heap and assigning an initial value to each element. There are two ways to initialize: 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
Copy the code

9.2.3.2 Statically Initializing memory analysis

public class ArrayDemo1{
  public static void main(String[] args) {
// Define and initialize an array
    int[] nums = new int[] { 1.3.5.7 };
    System.out.println("Array length =" + nums.length);
// reinitialize the array
    nums = new int[] { 2.4.8 };
    System.out.println("Array length ="+ nums.length); }}Copy the code

If num = null, null means that the memory space in the heap is no longer referenced, and numS is then uninitialized and unusable

9.2.3.4 dynamic Initialization

The programmer sets only the number of elements in the array, and the initial values of the array elements are determined by the system (JVM)

Syntax: Array type [] array name = new array element type [length]; int[] nums = new int[5];

Int [] nums = new int[5]{1,3,5,7,9} is incorrect

The memory map 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 elements

Element type variable name = array name [index];

9.2.5 common exceptions in arrays

  1. NullPointerException: NullPointerException

Operates on an array that has not been initialized or allocated memory

  1. ArrayIndexOutOfBoundsException: index of an array of cross-border anomalies

The index of the operated array 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 is 0, 1, 2, 3
    System.out.println(ele);
    }
Copy the code

9.2.6.2 for-each (Enhanced for loop)

for(Array element type variable: array){//TODO
}
Copy the code
int[] nums = new int[] { 1.3.5.7 };
for (int ele : nums) {
System.out.println(ele);
}
Copy the code

It’s easier to manipulate arrays with for-each because you don’t care about indexes, and the underlying principle is still the same for loop that manipulates arrays

9.2.7 two-dimensional Arrays

Before, each element of an array was a value, and this kind of array was called a one-dimensional array. A two-dimensional array, where 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) {
// Define three one-dimensional arrays
int[] arr1 = { 1.2.3 };
int[] arr2 = { 4.5 };
int[] arr3 = { 6 };
// If you store three one-dimensional arrays in another array, that array is a two-dimensional array
int[][] arr = new int[][] { arr1, arr2, arr3 }; }}Copy the code

The element type in a two-dimensional array is a one-dimensional array, and the array element type [] is regarded as a whole to represent the data type

dynamic

Array element type [] [Array name = new array element type [x] [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];
Copy the code

9.2.7.2. Get the element of a two-dimensional array

The for loop

for (int index = 0; index < arr.length; index++) {
// Fetch each one-dimensional array
int[] arr2= arr[index];
// Iterate over a one-dimensional array
for (int j = 0; j < arr2.length; j++) {
int ele = arr2[j];
System.out.println(ele);
}
System.out.println("-- -- -- -- --");
}
Copy the code

for-each

for (int[] arr2 : arr) {
  //arr2 is the one-dimensional array iterated each time
for (int ele : arr2) {
    //ele is the element iterated from the arr2 one-dimensional array
System.out.println(ele);
}
System.out.println("-- -- -- -- --");
}
Copy the code

Ten, methods,

10.1. Definition of methods

Method: a block of code used to perform a specific function (e.g., sum, count, etc.)

Syntax format:

Modifier] Return value type method name (Parameter type Parameter name 1, parameter type parameter name 2...) {method body; [return Return value;] }Copy the code

Format analysis:

  • Static modifiers: public, static, etc. Static modifiers can be called by the class name. Static modifiers belong to the class
  • Return value type: Defines the type of return value. After a method completes a function, does it need to return a result to the caller?
    1. If you need to return a result to the caller, write the type of returned data
    2. If you don’t need to return results to the caller, use keywordsvoid, indicating that no result is returned
  • Method name: Used to call the method, follows the identifier specification, starts with lowercase letters, uses camel name, is known by name
  • Formal parameters: variables in parentheses in a method that can have more than one formal parameter
  • Method body: Write code that accomplishes this functionality
  • Function of the return keyword
    1. Returns the value to the caller of the method
    2. End this method, no more statements can be learned after return
    3. When there is no return in the method body, the return value type of the method must be void
  • Actual parameter: The value of the actual parameter passed when a specific method 1 is called
  • If a return value is required, be sure to have a return value under any conditions

Matters needing attention

  1. Methods must be defined into classes, and the smallest unit of program in Java is a class
  2. Multiple methods can be defined in a class
  3. Methods are parallel to each other, so you cannot define a method within a house.
  4. Method definitions are in no order

10.2. Method invocation

If a method has a static modifier, it can be called directly by the class name of the method’s class; if it does not, it must be called with an instantiated object

10.3 method overloading

Parameter list: parameter type + parameter number + parameter order

Method signature: method name + method parameter list

The method signature is unique within the same class, otherwise the compilation will fail

Method overloading: Allows one or more methods with the same name for a method in the same class, provided that the argument lists are different

10.3.1, How is method overload

The principle of method overload judgment: two same and different

Identical: Method names are the same in the same class

Difference: the parameter list of the method is different (parameter type, parameter number, parameter order), as long as one of the parameter type, parameter number, parameter order is different, the parameter list is different

Method overloading is independent of the return value type, but generally requires that the return value type be the same

10.3.2. The role of method overloading

It solves the problem that methods with the same function have different names due to different parameters and need to be named repeatedly