Today, let’s review the Java basics and record them here
Java annotations
Java three comments: single-line comments | | a multi-line comment documentation comments
Features of the Java language
Java was originally developed by SUN and acquired by Oracle in 2007
Easy to learn, object-oriented, cross-platform (compile once, run anywhere), secure, multi-threaded, distributed
Virtual machine cross-platform. Class files run on different platforms, that is, different platforms have different JDK VMS. So it’s not the Java language itself that can be cross-platform, it’s just the Java VIRTUAL machine that can be cross-platform?
Data types and operators
1. Identifier
Naming rules for related object names in the language; Java requires a name to contain only letters, digits, underscores (_), and $, and cannot start with a number. At the same time, the identity cannot be the same as the built-in keyword in the Java language.
Variable names, function names: Follow camel nomenclature
Class names, interface names, enumerations: Pascal nomenclature is required
Camel nomenclature: requires the first letter of the name to be lowercase, followed by the first character of each word to be uppercase;
Pascal nomenclature: the first letter of the name is capitalized, and the first character of each word is capitalized;
2. Constants and variables
1. A space in memory; How to access?
Variables in the Java language are divided into local variables and global variables (member variables).
Local variables: Variables declared in a method (function) or statement block are called local variables (including method parameters). Local variables are used with data (priming).
Global variables: variables declared outside a method (variables declared in a class); Global variables can be left uninitialized (because the system assigns default values);
int : 0
String : null;
Constant: a variable that cannot be changed. In Java, to declare a constant, add the keyword final (constant name in all uppercase)
3. Data types
Data types in the Java language are divided into basic data types (value types) and reference types (to be learned in object-oriented grammar courses).
Basic data types: 8
Four integer types: byte (8-bit) Short (16) int(32) Long (64) —- Int is the default integer type
Float (32),double(64) – Double is the default type of floating-point numbers
Char (16) can store Chinese characters
Boolean: the Boolean (true | false).
4. Data type conversion
Implicit conversion: Assigning a small data type to a large data type automatically generates an implicit conversion;
Display conversion: Assigning a large data type to a small data type requires a display conversion (manually implemented by the programmer); Strong transfer application runtime may be wrong (thrown exception | get an invalid data), there are also may not be a problem
5. Operators
It is basically the same as the operators in life;
Arithmetic operators (+,- * / %, ++,–)
The relational operator (> >= < <=! = = =)
Assignment operator (=, += -= *= /=)
Logical operators (&& | |!
An operator (& | > > < < > > >); (Highest efficiency)
Second, process control
1. Program structure
In the language, designers have designed three kinds of structures: sequential structure, selective structure and cyclic structure.
2. Choose structure
IF statement (three versions)
IF(expression){
}
IF(expression){
}else{
}
If (expression){
}else if(expression){
}else if(expression){
}else if(expression){
}…
else{
}
Expressions: the value of the type of the structure of the operation to a Boolean (true | false)
Switch (expression){
}
The structure of the expression after switch is a value (int)
** Conclusion: **switch is the most efficient. In practical applications, use switch statements instead of IF statements
Data types supported by expressions in switch statements — Byte,short int, String,enum(enumeration)
Break: One is to break out of the loop, breaking the switch statement within the switch statement;
3. Circular structure
For statement implementation
For (counter; Exit conditions; Change the value of the counter){
The loop body
}
While (expression){
}
The expression value in the while loop is a Boolean value;
Methods and arrays
1. Basic concepts of methods
In a procedural language (C), there are no methods (only functions). In an object-oriented language, there are only methods, but no functions.
Functions and methods do the same thing: a named block of code that implements a function and a method that can be called an unlimited number of times.
C: Organizing programs is a modular idea (each module usually corresponds to a function or functions, organized together by a file)
Method: In an object-oriented language, simply expresses the behavior of the current object
Method statement:
Return value method name (parameter list…..) ) {
Method body
}
The main method | the main function of public static void main (String [] args) {/ / application entry}Copy the code
2, learn method encapsulation
Learn to encapsulate a business function with a method and know whether the method is designed to provide return values and method parameters
3. Methods overload
Overloaded: A group of methods with the same method name and different types, numbers, or orders of arguments.
Note: Overloading has nothing to do with the return value.
4. Method recursion
In general: The use of a method is to call a method from within another method
Recursion: a recursive call to a method in which a statement directly or in question calls the method itself; Recursion is an algorithm in a program (some problems are very convenient, simple, and easy to understand using recursion), recursion is to extrapolate from the known to the unknown
Any function that can be achieved through a loop can be achieved through recursion;
Recursive need exports: no export recursive nature is an infinite loop (Exception Java. Lang. StackOverflowError), so the recursive need to export;
Rule of thumb: first write a method (usually with parameters and return values), inside the method from known conditions to write; (Recursive exit)
5. Method parameters
Parameter difficulties: For parameters of basic data type and reference type, parameter values are different when assigning parameters;
Basic data type: Data is stored in the stack area of the machine memory. When passing variables of basic data type, they are passed a copy of the value. Modification of variables (parameters) after passing does not affect the value of the original variable
Reference type: Data is stored in the memory heap area (a reference type variable heap address – is stored in the memory address), so a reference type variable in the pass, pass the address, so can guide system of multiple variables (reference) at the same time pointing to the pile of area same space data, an arbitrary variable can access this space data (random variables can be read this space data, You can also change the data in this space.
6, arrays,
Arrays: Collections of bulk data of the same type; The size of an array cannot be changed once it is defined (the size of the container is required to define an array). The elements are subscripted, and the subscripts start at 0. The length attribute returns the length of the array.
A one-dimensional array | | 2 set of array multidimensional arrays
Problem 1: Declare an array
Array name = new type [length];
String[] users = new String[10];
int[] intArray = new int[10];
Copy the code
If the array is not initialized when it is created, the program automatically gives the default value when it is run.
byte short int long — > 0
Double, float – > 0.0
Char – > Spaces
boolean — > false;
Other types (reference types) — > NULL
Type [] array name = new type [] {};
Double [] doubleArray = new double[] {1.0,2.0,3.0,4.0,5.0};Copy the code
Type [] Array name = {};
char[] charArray = {'a','b','c','d'};
Copy the code
4 Four sorts
Bubble sort: the comparison of adjacent elements is the smallest or the largest
,2,1,10,9 int [] arr = {4}; for(int i=0; i<arr.length-1; I++) {// control the order of comparison; System.out.println(" "+ (I +1) +"); for(int j=0; j<arr.length-1-i; J++) {// control the comparison of adjacent elements; If (arr[j] > arr[j]) {// exchange; int tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp; }}}Copy the code
** Select sort: ** each time the smallest or largest element in the array is found, and then swap with the element in a certain position;
Public static void selectionSort(int[] arr) {public static void selectionSort(int[] arr) { for(int i=0; i<arr.length-1; I++) {// control the order of comparison; / /,2,1,10,9 {4}; int minIndex = i; // i =0; for(int j=i+1; j<arr.length; J++) {// can find the smallest element subscript; if(arr[j] < arr[minIndex]) { minIndex =j; } } if(minIndex! = I) {// find an index smaller than minIndex; // Swap elements; int tmp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] =tmp; }}}Copy the code
Insertion sort: To place elements in an sorted array; (Split the array into two parts, sorted and unsorted)
,2,1,3,7,5,6,8,10,9 int [] arr = {4};
1 lun: 2,4,1,3,7,5,6,8,10,9
Second lun: 1,2,4,3,7,5,6,8,10,9
public static void insertSort(int[] arr) { for(int i=1; i<arr.length; I++) {// control order; int position = i; //position: the position to insert; Default original location; int insertElement = arr[i]; // The element to insert; While (position > 0 && arr[position-1] > insertElement) {arr[position] = arr[position-1]; // Replace the former with the latter; position--; } arr[position] = insertElement; // Place the element to be inserted in the current position; }}Copy the code
Aaron: 1,2,3,4,7,5,6,8,10,9
** Quicksort: ** Set a base number (the first element) for each column, split the array into two parts, the left is the number of columns smaller than the base number, the right is the number of columns larger than the base number;
Six, one, two, seven, nine, three, four, five, ten, eight
The first lun — 1:6,1,2,5,9,3,4,7,10,8
First lun — 2:6,1,2,5,4,3,9,7,10,8
At the confluence: reset the base numbers: 3,1,2,5,4,6,9,7,10,8
Aaron: 2 points in sequence based on the left side of the first benchmark than | again based on the new benchmark for right is also based on the new benchmark
public static void quickSort(int[] arr,int left,int right) { int i = left; Int j = right; int j = right; if(left > right) return; // Exit condition; int temp = arr[left]; // Set the base number; while (i ! = j) {// do not merge; while (arr[j] >= temp && i < j) { j--; While (arr[I] <= temp &&i < j) {I ++; Int t = arr[I]; int t = arr[I]; int t = arr[I]; arr[i] = arr[j]; arr[j] = t; }} // Switch base number; arr[left] = arr[i]; arr[i] = temp; quickSort(arr, left, i-1); // Call this method again on the left side to continue sorting; quickSort(arr, i+1, right); }Copy the code
Query: array traversal (projects, now do 99% basic it can use this way) | binary search (first order)
In JDK, sort and binary search implemented – Java. Util. Arrays. Sort | Java. Util. Arrays. The binarySearch | Arrays. The copyOf; Arraycopy (SRC, srcPos, Dest, destPos, Length);
public static int findElement(int[] arr,int element) { int index = -1; for(int i=0; i<arr.length; i++) { if(arr[i] == element) { index = i; break; } } return index; }Copy the code
public static int binarySearch(int[] arr,int element) {
int index = -1;
int startIndex = 0;
int endIndex = arr.length-1;
while(startIndex<=endIndex) {
int middle =(startIndex + endIndex) / 2;
if(arr[middle] == element) {
index = middle;
break;
}else if(arr[middle] > element) {
endIndex = middle -1;
} else {
startIndex = middle + 1 ;
}
}
return index;
}
Copy the code
Two-dimensional arrays: Data structures are table structures (x,y)
Problem 1: Declare an array
Arr =new int[][] arr =new int[2][3]; For (int I =0; i<arr.length; i++) { for(int j=0; j<arr[i].length; j++) { System.out.print(arr[i][j] +"\t"); } System.out.println(); }Copy the code
Type [d] 1 [d] 2 array name = new type [] [] {} int [] [] arr2 = new int [] [] {{1, 3}, {4 and 6}, {7,8,9,10}};Copy the code
Type [dimension 1][dimension 2] Array name = {{},{},{}}Copy the code
4. String (String)
1. Understand strings
String: The character set is called string **(storage is an array of characters **)
public final class String{
private final char value[];
}
Copy the code
Features: string string once defined, cannot be modified | string is defined as a final class (eventually), so the string cannot be inherited
Declaring strings: There are two ways (different)
String STR ="hello,wolrd"; S3 =new String("hello,world"); s3 =new String("hello,world"); String created literally in a string pool; New creates a string object that allocates space in the heap and places the string in the heap memory.Copy the code
2. String manipulation
Problem: You need to remember the common operation API (Application Program Interface) for String class design.
Of character string matching: equals | equalsIgnoreCase
Problem: the difference between == and equals in string comparisons
String concatenation: concat | String. The valueOf
String split: Split a string into an array of characters;
** Gets the character at the specified position: **charAt(index);
Check whether a character contains a substring: contains
Judgment of characters in a string start | end: startsWith | endsWith
Convert a string to an array of characters: toCharArray()
The string to uppercase | lowercase: toUpperCase | toLowerCase
** String interception: **subString
Find a character of subscript: indexOf | lastIndexOf
Go to left and right Spaces: trim
String replacement: replace | replaceAll
Check whether the string isEmpty: isEmpty();
3, StringBuffer | StringBuilder
Question: What is the difference between String and StringBuffer?
String defines an immutable String, and a StringBuffer construct is a mutable String object; So appending a StringBuffer to a String is more efficient than just using a String;
Question: StringBuffer is different from StringBuilder;
Both StringBuffer and StringBuilder can build mutable string objects, and both have the same API; StringBuffer is thread-safe, StringBuilder is thread-safe;
StringUtils utility class
Here attached an Apache site: commons.apache.org/proper/comm…
A lot of open source code, pay attention to the use of annotations to declare the use of other code, some kind.
Classes and objects
1. Understand classes
Class represents a race (a group with the same characteristics and behaviors), and the object is a specific individual generated based on this race; In the computer world, if you want to show on the planet a an individual (| object), all of these things belong to race in the world of computer must have a (regardless of life and non-life);
Race (class) — the relationship between things (objects) : first there is race (class), then there is the object;
2. Class design
Class class name {
/ / class members: early member properties | | | constructor member method makes the block
}
Initialization block: executes each time an object is created.
Create an object
Type name object name = new constructor (parameter list); Declare an empty object;
3. Construction method
Function: Initializes (assigns a default value to) the properties of an object when creating it.
- The constructor is usually public (it can be another wrapper)
- Constructor returns no value (void cannot be added)
- Constructor names are the same as class names
- Constructors can be overloaded
- When designing a class that has no constructor, the compiler automatically adds a constructor with no arguments to the class at compile time. When constructors are present, no parameterless constructors are added at compile time.
- A constructor cannot be called through an object
4, encapsulation
Members of the class encapsulation: the safety of the solution to a class member (data security – | right) effectively;
In the JAVA language, there are four levels of encapsulation: default, Private,protected, and public
Default: accessible inside the class, inside the package, and not outside the package;
Private: can only be accessed inside the class (inside the package, not outside the package)
Public: public (access is not restricted — within this class, within this package, within other packages)
The modifier | The interior of the class | In the same package | A subclass | Any location |
---|---|---|---|---|
private | Square root | x | x | x |
default | Square root | Square root | x | x |
protected | Square root | Square root | √(Subclass inside) | x |
public | Square root | Square root | Square root | Square root |
Object – oriented languages are characterized by encapsulation, inheritance and polymorphism
5. This keyword
**this :** represents the object of the class. This ([parameter]) : constructor of the class
** Note: If other constructors are called within the ** constructor, they must be placed in the first statement of the constructor
6, package (package)
Package: A folder that manages classes (typically in development, classes of the same nature are placed in the same package)
Package naming: generally use the reverse order of the url (with. Division)
Classes in the same package are directly used. If they are not in the same package, you need to import them. If they are not imported, you need to use the full class name
Learn about a commonly used package in the JDK
Java. Lang: base classes in this package, this package all the classes and interfaces in the direct use of default has import) - Java. Util: in Java tools and set in the package (Scanner | Date | Arrays) Java awt: GUI components be put into the package; Java.io: The relevant classes and interfaces for file operations are placed in this package; Java.net: Network programming related interfaces and classes in this package; Java.sql: The design for database operations is in this package; Javax. swing: Package for GUI component design (an upgrade of the AWT)...... Import package: Import package. Class;Copy the code
Static keyword
The members of the class is divided into two categories: static members | instance (object) members, is through object to access;
Static: static (members shared by all objects of the class). Static member data is not stored in the heap. Static method of data storage memory area (open up a piece of space – static area | share area)
Record the number of objects created;
Static member access: recommend static member access static members | instance access; Although instance members can access static members, this is not recommended (the message is not clear), static members must not be able to access the instance;
Summary class instance members: properties, constructors, initializer blocks, instance methods
Static members of a class: properties, static initializer blocks, static methods;
Static initialization blocks: run once when the class is loaded into memory.
** Difficult points: ** What is the process of creating an object when all members of the class are saved;
In the design of classes (especially tool classes), for the convenience of use, the class members are made static;
8. Singleton mode
Patterns: A generic solution to a class of problems is called a pattern; In software development, there are 23 kinds of design problems, so the predecessors give 23 modes;
Singleton pattern: a class can create only one object;
Public class Singleton {private static Singleton = null; // private Singleton() { } public static Singleton newInstance() { if(singleton ==null) { singleton = new Singleton(); } return singleton; Public class Singleton {private static Singleton = new Singleton(); // private Singleton() { } public static Singleton newInstance() { return singleton; }}Copy the code
Inheritance and polymorphism
1, inheritance,
To inherit is to own – to dominate – to get for nothing;
Qualitative analysis: similarity classes have the same features and behavior, need to separately in each class to provide low – efficiency | volume (nonsense)
Solution: make a single base class (parent class), this class defines the common properties or behavior (method), other only need to inherit this class can be;
If two classes build an inheritance relationship: the class’s identity changes;
Be inherited class: the parent class | base class
Inherited classes: subclass | derived classes;
JAVA inheritance is single-root inheritance (there can be only one direct parent of a class), but it can be layered;
1.1 extends: Implements inheritance
public class Horse extends Animal{
}
Copy the code
1.2 protected: Encapsulation of the protected level
Protected: This encapsulation level is designed for inheritance. Subclasses of this encapsulation level can access the members of their parent class.
The interior of a subclass (whether in the same package or in a different package) is accessible, but the exterior of the class is not (not in the same package)
1.3 Super Keyword
Super: object of the parent class; Parameters of super ([…]. ) : constructor of the parent class;
1.4 Understanding the creation of subclass objects [Difficulty]
, when creating a subclass object will be transferring in the parent class constructor, create a superclass object, by default, will call the superclass no arguments constructor to create the superclass object (if the parent class any constructor, could save show calls), if there is no design without the parent class constructor, must show calls the superclass constructor refs
Each subclass contains an Object of the parent class (if the parent class has a parent class, continue to create the parent Object until the Object class).
1.5 Final keyword
The final effect:
- Modify a variable, which is defined as a constant;
- Modifier methods that cannot be overridden
- Modify class, class cannot be inherited
Classes currently known in the JDK that cannot be inherited: java.util.Scanner | java.util.Math|java.lang.String|java.lang.System|java.lang.StringBuffer|java.lang.StringBuilder
1.6 Upward transformation and downward transformation
A subclass inherits a class: constructs a parent-child relationship (is a relation), for is a relation of the class, when defining the object, can directly assign the object of the subclass to the parent class object; —- Upward transition (manual processing is not required, automatic implementation)
After the upward transformation, the object of the parent class can access only the members of the acquired class, but the object of the parent class of the newly added member of the child class cannot access. ;
Instead of assigning a parent object directly to a subclass object (a parent object can represent any of its subclasses), you need to cast it downward
A downward cast may cause a problem (the parent object is not of the current type) or it may not cause a problem (the parent object is of the current type), resulting in a ClassCastException.
Determine the type of object: instanceof
1.7 Object class
When a class does not explicitly inherit from a class, it inherits from the Object class, which is the root of the class hierarchy in the JAVA language. Object class members defined in each class (to be inherited)
Familiarity with Object class design is required
Protected Object clone() : If a class provides clone(), this class needs to implement the Cloneable interface. Clone () gets a new Object.
Public Boolean equals(Object) : bool equals(Object)
public boolean equals(Object obj) {
return (this == obj);
}
Copy the code
The String class reimplements the equals method inherited from Object.
Protected void Finalize () : called by GC; You can release resources manually.
public Class<? > getClass(): returns the full pathname of the class;
public String toString()
return getClass().getName() + "@" + Integer.toHexString(hashCode());
Copy the code
Public int hashCode() : Return the address of the object (in decimal)
Notify | notifyAll: thread wakes up
Wait: the thread waits.
1.8 tools
java.text.SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
java.util.Date now = new java.util.Date();
String strDate = fmt.format(now);
java.util.Calendar cal = java.util.Calendar .getInstance();
int year= cal.get(Calendar.YEAR)
int month= cal.get(Calendar.MONTH)
Copy the code
2 polymorphism (polymorphic)
Problem: the behavior of the parent class does not satisfy the requirements of the child class (not the child class) – how to solve the problem? ;
Solution: Redesign inherited methods in subclasses
Override: A subclass reimplements (redesigns) a method of its parent class, typically with the @override annotation
** polymorphisms: ** The multifaceted behavior of the parent class is called polymorphisms (caused by subclass overwriting);
Polymorphic implementation conditions:
- There should be inherited
- You have to have a override
- Must be called through an object of the parent class (object-oriented programming – objects of the base class)
Abstract classes and interfaces
1. Abstract classes
Parent subclass in service, if you have implemented in the superclass method (behavior), can be directly used in subclasses (not modify | not rewrite), in the parent class implementation; If the method (behavior) of the parent class needs to be overridden in the word class, only the method can be defined in the parent class, without providing the implementation of the method – abstract method;
Abstract method: only method definition, no method implementation, need to add a keyword — abstract;
Abstract class: A class that contains abstract methods is called abstract class (designed as abstract class)
- Define the abstract class keyword: abstract
- Abstract classes usually appear as superclasses
- Abstract classes cannot be instantiated;
- Abstract class application: use a subclass of the abstract class | see this abstract class have static members (properties) | method
- Abstract classes are classes in nature, so any member of an ordinary class can be in an abstract class.
Problem: The difference between classes and abstract classes
Class and abstract class essence is the same, are classes; Abstract classes usually appear as base classes. They serve subclasses and can contain abstract methods, but ordinary classes cannot. Abstract classes cannot be instantiated. Ordinary classes can be instantiated.
Template method pattern: The template method pattern defines the skeleton of an algorithm in a method, deferring the implementation of some steps to subclasses. The template approach allows subclasses to redefine the concrete implementation of certain steps in an algorithm without changing the structure of the algorithm.
Public abstract class AbstractLogin {public final void login() { this.validate(); // Step 2: Implement login; this.userLogin(); // Step 3: Log; this.writeLog(); } public abstract void validate(); public abstract void userLogin(); public abstract void writeLog(); }Copy the code
2, interfaces,
Object-oriented programming in three levels: the specific class of objects – the parent class object (abstract classes | common parent), object (interface) of the parent
** Interface: ** is a custom set of standards, specifications, and constraints on the behavior (methods) of a class;
| method constraint specification: return values of | | method of parameters (type, quantity, order)
-
Define the interface: interface
-
Implements interface: implements (all methods in the interface need to be implemented, unless the class is abstract)
-
Methods in interfaces are abstract by default, and the abstract keyword can be defined with or without it. (Not added)
-
The encapsulation of all members of an interface defaults to public.
-
Interfaces cannot be instantiated;
-
A class can implement multiple interfaces, but a class can only have one direct parent class.
-
Members: method of interface into can define | attributes (static constant static final)
-
JAVA8 extends interfaces to allow static and default methods to be defined in the interface
What is the difference between abstract classes and pumps?
The essence of abstract class is class, the essence of interface is to customize the behavior of class specification; Neither abstract classes nor interfaces can be instantiated; A class can have only one parent class, but can implement multiple interfaces. Abstract classes can have abstract methods and all class members, but interfaces can only have abstract methods and attributes. There can be default methods and static methods).......Copy the code