Hello World
1. Create a new folder and store the code
2. Create a new java file
- The file extension is .java
- Hello.java
- [Note] The system may not display the file extension, we need to open it manually;
3. Write code
public class Hello{ public static void main(String args[]){ System.out.println("hello world!") } }
4. Compiling javac Hello.java will generate a class file
5. Run the class file, namely java Hello
possible problems
1. There should be no problem with the size of each word, JAVA is case sensitive;
2. Try to use English;
3. The file name and class name must be consistent, and the first letter is capitalized;
4. If the symbols are in Chinese, an error may be reported;
Java operating mechanism
Compiled
Explanatory
Java Basic Grammar
There are three types of annotations in Java
- Single-line comment //Comment content
- Multi-line comment /comment content/
- Documentation comments /**
*
*/
Generate java documentation:
javadoc -encoding UTF-8 -charset UTF-8 Doc.java
identifier
- Keywords, such as public static void, etc.;
variable
- What is a variable: it is the amount that can change;
- Java is a strongly typed language, each variable must declare its type;
- A Java variable is the most basic storage unit in a program, and its elements include variable name, variable type, and scope.
type varName [=value] [{,varName[=value]}] //Data type variable name = value; multiple variables of the same type can be declared separated by commas.
Precautions
- Each variable has a type, which can be a basic type or a reference type;
- Variable names must be legal identifiers;
- A variable declaration is a complete statement, so each declaration must end with a semicolon;
variable scope
- class variable
- instance variable
- local variable
public static Variable{ static int allClicks=0; // class variable String str="hello world"; // instance variable public void method(){ int i=0; // local variable } }
constant
- Constant: the value cannot be changed after initialization, and the value will not change;
- The so-called constant can be understood as a special variable whose value is not allowed to be changed during the running of the program after its value is set.
final constant name=value; final double PI=3.14;
- Constant names generally use uppercase characters
Variable naming convention
- All variables, methods, and class names: see the name and know the meaning
- Class member variables: lowercase first letter and camel case Principle: monthSalary Except for the first word, the first letter of the following words is capitalized
- Local Variables: Lowercase and CamelCase
- Constants: capital letters and underscores: MAX_VALUE
- Class names: capital letters and camelCase principles: Man, GoodMan
- Method name: lowercase first letter and camel case principle run() runRun()
operator
- Arithmetic operators + - * / % ++ –
- assignment operator =
- Relational operators > < >= <= != instanceof
- Logical operators && || !
- Bitwise operators & | ^ ~ >> << >>>
- conditional operator ? :
- Spread assignment operators += -= *= /=
Java process control
- The program interacts with the human, and the user can input. java.util.Scanner
- Basic syntax:
The input string is obtained through the next() and nextLine() methods of the Scanner class. Before reading, we generally use hasNext() and hasNextLine() to determine whether there is any input data.Scanner s = new Scanner(System.in)
break continue
- break In the main part of any loop statement, break can be used to control the loop flow. break is used to forcibly exit the loop without executing the remaining statements in the loop. (The break statement is also used in the switch statement)
- The continue statement is used in the loop statement body for a certain loop process, that is, to skip the unexecuted statement in the loop body, and then to judge whether to execute the loop next time.
Java method
Definition: It is a piece of code used to complete a specific function.
- A method consists of a method header and method body.
- Modifier: defines the access type of the method;
- Return value type: the method may return a value;
- Method name: is the actual name of the method;
- Parameter type: A parameter is like a placeholder. When the method is called, a value is passed to the parameter. This value is called an actual parameter. Parameters are optional, the method may not contain any parameters;
- Method body: The method body contains specific statements that define the function of the method.
modifier return value type method name(parameter type parameter name){ ... method body ... return return value; }
method overloading
- Overloading is a function in a class with the same function name but different parameters.
- Method overloading rules:
- The method names must be the same;
- The parameter lists must be different (different numbers or types or different order of parameters);
- The return types of the methods can be the same or different;
- Merely having a different return type is not enough to be a method overload;
Passing parameters on the command line
package method; public class Demo03 { // Execute java method/Demo03 under src after javac compilation public static void main(String[] args) { // arge.length array length for (int i = 0; i < args.length; i++){ System.out.println("args[" + i + "]:" + args[i]); } } }
variable parameter
package method; public class Demo04 { public static void main(String[] args) { Demo04 demo04 = new Demo04(); demo04.test(1,2,3,4,5); } // Varargs must come last public void test(int x, int... i){ for(int j = 0; j < i.length; j++){ System.out.println(i[j]); } } }
Array declaration creation
- Array variables must first be declared before the array can be used in the program. Following is the syntax for declaring array variables:
dataType[] arrayRefVar; // preferred method or dataType arrayRefVar[]; // Same effect, but not the preferred method
- The Java language uses the new operator to create an array, the syntax is as follows:
dataType[] arrayRefVar = new dataType[arraySize];
- The elements of the array are accessed by index, and the array index starts from 0;
- Get array length: arrayRefVar.length
Java memory
- heap
- Store new objects and arrays
- Can be shared by all threads and will not store other object references
- the stack
- Store basic variable types (including specific values of these basic types)
- The variable that refers to the object (the specific address of the reference in the heap will be stored)
- method area
- can be shared by all threads
- Contains all class and static variables
sparse array
package array; public class ArrayDemo05 { public static void main(String[] args) { int[][] array1 = new int[11][11]; array1[1][2] = 1; array1[2][3] = 2; // output the original array System.out.println("output the original array"); for (int[] ints : array1){ for (int anInt : ints){ System.out.print(anInt+"\t"); } System.out.println(); } System.out.println("=============================="); // Convert to sparse array to save // Get the number of valid values int sum = 0; for (int i = 0; i<array1.length; i++){ for (int j = 0; j<array1[0].length; j++){ if (array1[i][j]!=0){ sum++; } } } System.out.println("number of valid values"+sum); // 2. Create an array of sparse arrays int[][] array2 = new int[sum+1][3]; array2[0][0] = array1.length; array2[0][1] = array1[0].length; array2[0][2] = sum; // Traversing a two-dimensional array, storing non-zero values in a sparse array int count = 0; for (int i = 0; i<array1.length; i++){ for (int j = 0; j<array1[0].length; j++){ if (array1[i][j]!=0){ count++; array2[count][0] = i; array2[count][1] = j; array2[count][2] = array1[i][j]; } if(count>sum){ break; } } } //output sparse array System.out.println("sparse array"); for (int i =0; i<array2.length;i++){ System.out.println(array2[i][0]+"\t"+array2[i][1]+"\t"+array2[i][2]); } // restore sparse array System.out.println("restore sparse array"); // 1. Read sparse array int[][] array3 = new int[array2[0][0]][array2[0][1]]; // 2. Restore the value in it for (int i = 1; i < array2.length; i++){ array3[array2[i][0]][array2[i][1]] = array2[i][2]; } //output restore array for (int[] arr : array3){ for (int val : arr){ System.out.print(val+"\t"); } System.out.println(); } } }
object oriented
- Object-Oriented Programming (OOP)
- The essence of object-oriented: organize code in the form of classes, and organize (encapsulate) data in the form of objects;
- abstract
- Three characteristics
- encapsulation
- inherit
- polymorphism
- Objects are concrete things. A class is an abstraction, an abstraction of an object;
- From the perspective of code operation, there are classes first and then objects. Classes are templates for objects.
constructor
- same as class name
- no return value
effect - The essence of new is to call the constructor
- initialize the value of the object
be careful
1. After defining a parameterized structure, if you want to use a parameterless structure, you need to explicitly define a parameterless structure
Alt+Insert automatically generates construction methods based on attributes
encapsulation
property private, get/set
- Improve program security and protect data
- hide the implementation details of the code
- unified interface
- System maintainability increased
inherit
- The essence of inheritance is the abstraction of a certain batch of classes, so as to achieve better modeling of the world
- extends means extension. A subclass is an extension of a parent class.
- Classes in Java have only single inheritance, no multiple inheritance
- Inheritance is a relationship between classes and classes. In addition, the relationship between classes and classes includes dependency, composition, aggregation, etc.;
- There are two classes in the inheritance relationship, one is the subclass (derived class) and the other is the parent class (base class). A subclass inherits from a parent class, represented by the keyword extends.
- In a sense, there should be an "is a" relationship between the subclass and the parent class
- All classes in java inherit the object class by default
super note
- super calls the constructor of the parent class, which must be the first in the constructor
- super must only appear in subclass methods or constructors
- super and this cannot call the constructor at the same time
Vs this
- Different objects are represented:
- this: call this object itself
- super: represents the application of the parent class object
- premise:
- this: Can be used without inheritance
- super: can only be used when inheriting the adjustment
- Construction method
- this(); call the constructor of this class
- super(); call the constructor of the parent class
rewrite
There needs to be an inheritance relationship, and the subclass overrides the method of the parent class
- method names must be the same
- The argument lists must be identical
- Modifier: the scope can be expanded; public > Protected > Default > private
- The exception thrown; the scope can be narrowed, but not expanded;
polymorphism
That is, the same method can take many different behaviors depending on the sending object
Polymorphism Considerations
- Polymorphism is the polymorphism of methods, but no polymorphism of properties
- The parent class and the subclass must be connected, otherwise there will be a type conversion exception! ClassCastException!
- Existence conditions: inheritance relationship, methods need to be rewritten, and parent class references point to subclass objects! Father f1 = new Son();
Methods modified by the following modifiers are not polymorphic
- static method, which belongs to the class, it does not belong to the instance
- final constant
- private method
static keyword
public class Person { { // Code block (anonymous code block) is created when the object is created, before the construction method System.out.println("anonymous code block"); } static { // The static code block is loaded when the class is loaded, and is only executed once System.out.println("static block"); } public Person(){ // Construction method System.out.println("Construction method"); } public static void main(String[] args) { Person person1 = new Person(); System.out.println("=================="); Person person2 = new Person(); System.out.println("=================="); } }
output:
static block
anonymous code block
Construction method
==================
anonymous code block
Construction method
==================
- Abstract classes cannot be new;
- Ordinary methods can be written in abstract classes
- Abstract method must be in abstract class
- Abstraction of abstraction: Constraints improve development efficiency
interface
- constraint
- Define some methods for different people to implement
- All methods in the interface default to public abstract
- All variables in the interface are public static final by default
- The interface cannot be instantiated, there is no constructor in the interface
- implements can implement multiple interface calls
- The method in the interface must be overridden
Select the line that may have a problem, option + command + t can generate a try/catch/finally statement
Exception priority: Throwable > Error = Exception > both child exceptions