Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the knowledge points of javaSE?

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces what are the knowledge points of javaSE, which are introduced in great detail and have certain reference value. Friends who are interested must finish reading!

Summary of javaSE knowledge points

The essence of Java basic knowledge

Write code:

1. Define the needs. What am I going to do?

2, analyze the train of thought. What will I do? 1,2,3 .

3, determine the steps. What statements, methods, and objects are used in each part of the idea.

4, code implementation. Use specific java language code to reflect the idea.

Four points for learning new technologies:

1. What is this technology?

2, what are the characteristics of this technology (note in use):

3, how to use this technology. Demo

4. When will the technology be used? Test .

-

1: Overview of java:

Sun's James Gosling and others began to develop a language called Oak in 1991, hoping to control microprocessors embedded in cable TV exchange boxes, PDA, etc.

Renamed the Oak language to Java in 1994

Three technical architectures of Java:

JAVASE:Java Platform Standard Edition, which completes the development of desktop applications, is the foundation of the other two

JAVAEE:Java Platform Enterprise Edition, the development of enterprise environment applications, mainly for web program development

JAVAME:Java Platform Micro Edition, developing consumer electronics and embedded devices, such as programs in mobile phones

1. The development and running environment of Java Development Kit,java, which is the development tool of java, including jre.

2the running environment of java Runtime Environment,java program, and the necessary class library + JVM (java virtual machine) for JREVR running.

3, configure environment variables: let the tools in the java jdk\ bin directory run in any directory, because the system tells the system where the tool is located, and when using the tool, the system helps us find the specified directory.

Configuration of environment variables:

1): permanent configuration: JAVA_HOME=% installation path%\ Java\ jdk

Path=%JAVA_HOME%\ bin

2): temporary configuration method: set path=%path%;C:\ Program Files\ Java\ jdk\ bin

Features: by default, the system first goes to the current path to find the program to be executed, and if not, go to the path set in path.

Configuration of classpath:

1): permanent configuration: classpath=.;c:\; e:\

2): temporary configuration method: set classpath=.;c:\; e:\

Note: what you need to pay attention to when defining classpath environment variables

If the environment variable classpath,java is not defined, after starting jvm, it will look for the class file to run in the current directory

If classpath is specified, the class file to run is found in the specified directory.

Will you still look in the current directory? There are two situations:

1): if there is a semicolon at the end of the value of classpath, and the running class is not found in the specific path, it will be found again in the current directory by default.

2): if the value of classpath shows that there is no semicolon, the running class is not found in the specific path, and it will not be found in the current directory.

Generally, a semicolon is not specified, and if the class file to be run is not found in the specified directory, an error is reported, so that the program can be debugged.

4What do the javac command and java command do?

Java is divided into two parts: one is to compile and the other is to run.

Javac: responsible for the compilation part. When javac is executed, the compiler program for java will be started. Compiles the .java file with the specified extension. A bytecode file that can be recognized by jvm is generated. That is, the class file, that is, the running program of java.

Java: the part responsible for running. Jvm will be started. Load the class libraries needed for the runtime and execute the class file.

For a file to be executed, there must be a starting point for execution, which is the main function.

-

Second, the basis of java grammar:

1, keyword: in fact, a language gives a special meaning to the word.

Reserved words: words that are not given a special meaning yet, but are prepared to be used in the future.

2, marker: it is actually a noun defined in the program. Such as class name, variable name, function name. Contains 0-9, amurz, $, _

Note:

1), the number cannot begin.

2), no keywords can be used.

Constant: data that does not change in the program.

4. Variable: a storage space in memory for storing constant data.

Function: convenient for calculation. Because some of the data are uncertain. So determine the noun and storage space of the data.

Features: variable space can be reused.

When do you define a variable? Define variables whenever the data is uncertain.

What elements are needed for the development of variable space?

1. What data will be stored in this space? Data type.

2, what is the name of this space? Variable name.

3, what is the first data in this space? The initialization value of the variable.

Scope and lifetime of variables:

Scope of the variable:

The scope starts at the position defined by the variable and ends with the pair of curly braces in which the variable is located

Life cycle:

The variable lives in memory from the defined location.

The variable disappears in memory when it reaches its scope

Data type:

1): basic data types: integer byte, short, int, long, floating point float, double, character char, Boolean boolean

2): reference data types: arrays, classes, interfaces.

The level from low to high is: byte,char,short (these three levels)-- > int-- > float-- > long-- > double

Automatic type conversion: from low-level to high-level, the system automatically converts

Cast: under what circumstances? Assign a high-level number to a lower-level variable

Operation symbol:

1), arithmetic operator.

+-* /%%: any integer module 2 is either 0 or 1, so as long as the module is changed, the switch operation can be realized.

+: connector.

+,-

2), assignment operator.

= +-= * /% =

3), comparison operator.

Features: the operator is characterized by: the result of the operation, either true or false.

4), logical operator.

& | ^! & & | |

The logical operator is divided! Are used to concatenate two boolean type expressions.

&: only both sides are true and the result is true. Otherwise it's false.

| |: as long as both sides are false, the result is false, otherwise it is true. |

^: XOR: a little different from or.

The result on both sides is the same, which is false.

The result of the two sides is not the same, it is true.

The difference between & and & &: no matter what the result on the left is, the right is involved in the operation.

&: short circuit and. If the left side is false, then the right side has no parameters and operations.

| and | | difference: |: operate on both sides.

| |: short circuit or, if the left side is true, then the right side does not participate in the operation.

5) bit operator: the operator used to manipulate binary bits.

& | ^

> (unsigned move to the right)

Exercise: exchange the data of the two variables. No third-party variables are required.

Int a = 3 ~ (th) b = 5 ~ *

A = a + b; a = 8

B = a-b; b = 3X c

A = a-b; a = 5

A = a ^ banner /

B = a ^ b * b = a ^ b ^ b = a

A = a ^ b take a = a ^ b ^ a = b

Exercise: efficiently calculate 2: 8 = 21; / / (max+min) / 2 / position / the median is the maximum plus the minimum divided by 2

While (ARR [mid]! = key) {/ / if the value in the array is not equal to key

If (key > arr [mid]) {/ / if the value in key >

Min = mid + 1

}

Else if (key1

}

Return mid

}

Memory partition of the Java virtual machine (jvm):

1: register. 2: local method area. 3: method area. 4: stack. 5: heap.

The role of region names

1. Register: for CPU use, has nothing to do with our development.

two。 Local method stack: JVM is used when using operating system functions, regardless of our development.

3. Method area: stores class files that can be run.

4. Method stack: the memory used when the method runs, such as the main method, which is executed in the method stack.

5. Heap memory: store objects or arrays, created by new, are stored in heap memory.

Stack: all stored are local variables (variables defined in functions, parameters on functions, variables in statements)

As long as the area in which the data operation is completed ends, the data will be released.

Heap: used to store arrays and objects, that is, entities. What is an entity? It is used to encapsulate multiple data.

1: every entity has a memory header address value.

2: variables in heap memory have default initialization values. Because the data type is different, the value is different.

3: garbage collection mechanism.

Math class: the java.lang.Math class contains methods for performing basic mathematical operations, such as elementary exponents, logarithms, square roots, and trigonometric functions.

1] public static double abs (double a): returns the absolute value of double, such as: double D1 = Math.abs (- 5); / / D1 is 5

2] public static double ceil (double a): returns the smallest integer greater than or equal to the parameter. For example, double D2 = Math.ceil (- 3.3); / / the value of D2 is-3

3] public static double floor (double a): returns an integer that is less than or equal to the largest parameter. For example, double D2 = Math.floor (- 3.3); / / the value of D2 is-4.0

4] public static long round (double a): returns the long that is closest to the parameter. (equivalent to rounding)

For example, long D1 = Math.round (5.5); / / the value of D1 is 6.0

Long D2 = Math.round (5.4); / / the value of D2 is 5.0

Three: object-oriented: ★

Object-oriented: the emphasis is on implementing the function by invoking the behavior of the object, rather than operating it step by step.

Object-oriented features: 1: simplify complex things.

2: object-oriented turns the executor of the previous process into the commander.

3: the idea of object-oriented is in line with people's thinking habits.

The difference between process-oriented and object-oriented

Give an example

Laundry:

Process-oriented: take off your clothes-- > find a basin-- > put some washing powder-- > add some water-- > soak for 10 minutes-- > knead-- > wash clothes-- > wring dry-- > hang them up.

Object-oriented: take off clothes-- > turn on automatic washing machine-- > throw clothes-- > buttons-- > hang them up.

Difference:

Process-oriented: emphasize steps.

Object-oriented: emphasize the object, the object here is the washing machine. Object-oriented languages contain three basic features, namely, encapsulation, inheritance and polymorphism.

How are processes and objects reflected in our program? The process is actually a function; the object encapsulates some content such as the function.

Anonymous object usage scenarios:

1: anonymous objects can be used when a method is called only once.

2: anonymous objects cannot be used when an object makes multiple calls to a member. The object must be named.

Classes and objects

Class: a collection of related properties and behaviors. It can be regarded as a template for a class of things, which is described by the attribute and behavior characteristics of things.

Attribute: is the status information of the thing. Behavior: is what the thing can do.

Object: generally refers to all things in reality, is the concrete embodiment of a kind of things. An object is an instance of a class (the object is not looking for a girlfriend) and must have the properties and behavior of this kind of thing.

For example: a kitten. Attributes: tom, 5kg, 2 years, yellow. Behavior: walk around the wall, run, meow.

The relationship between classes and objects:

A class is a description of a class of things and is abstract.

An object is an instance of a kind of thing, which is concrete.

A class is a template for an object, and an object is an entity of a class.

Definition of the class:

Define a class: define the members of the class, including member variables and member methods. Before the definition, it is necessary to analyze the attributes and behavior of things before they can be reflected in code.

1: member variable: in fact, it corresponds to the attributes of things. In the class, outside the method

2: member function: in fact, it corresponds to the behavior of things. Just need to get rid of static.

The use of objects

Object format: create object: class name object name = new class name ()

Use objects to access members of a class:

1) object name. Member variable

2) object name. Member method ()

Default value of member variable

Data type default value

Basic type: integer (byte,short,int,long) 0

Floating point number (float,double) 0.0

Character (char)'\ u0000'

Boolean false

Reference type: array, class, interface null

The difference between member variables and local variables:

1: member variables are defined directly in the class, outside the method

Local variables are defined in methods, parameters, and statements.

2: member variables are valid in this class.

The local variable is valid only in the curly braces to which it belongs, which ends and the local variable loses its scope.

3: member variables exist in heap memory, exist with the generation of objects, disappear and disappear.

The local variable exists in the stack memory, exists with the operation of the region to which it belongs, ends and is released.

There are three main features of java object-oriented programming: encapsulation, inheritance and polymorphism.

The main features of object-oriented are encapsulation and inheritance polymorphism and abstraction.

Related concepts:

Encapsulation: hide the internal implementation, provide external implementation methods, benefits: do not affect the internal structure of the class, protect data. It means that an object encapsulates its own data with its operations on the data.

Encapsulation has good modularity, and the goal is to achieve the idea of high cohesion and low coupling in programming (to prevent the changing effects of interdependence).

In object-oriented, objects are the basic unit of encapsulation, so in object-oriented languages, the use of encapsulation makes the code clearer.

In object-oriented, encapsulation is to encapsulate the behavior attributes of an object into a module, that is, in a class, the attributes are defined by variables and the behavior is defined by methods, such as entities.

Encapsulated answers range from ideas to objects to how to encapsulate an object.

Inheritance: two classes have an inclusion relationship (is-a), and the parent class code is reused to prepare for polymorphism.

The answer to inheritance: the subclass inherits from the parent class, and the subclass inherits the data and operations on the data of the parent class, while adding its own data and operations on the data

Polymorphism: there are two main types of polymorphism. One is the polymorphism of the name of the operation, that is, the name of multiple operations is the same, but the message type accepted must be different; the other is the polymorphism related to inheritance, in which different types of objects have different effects on the invocation of the same operation.

Polymorphism occurs at run time of the code. (generic)

Polymorphism enhances the flexibility and expansibility of the software (behavior sharing (method sharing))

It provides a solution for decoupling between system components or modules.

The period and benefits of polymorphisms.

There are two ways to achieve polymorphism, override and overload.

Override refers to the practice of a subclass redefining the virtual function of the parent class.

Overloading means that multiple functions of the same name are allowed, and these functions have different parameter tables (either the number of parameters, the type of parameters, or both).

Function overloading: multiple functions of the same name are allowed. These functions have different parameter lists, either because of the number of parameters, or because of different parameter types, or because both are different.

An important point: function overloading occurs in the same class. When called, it is called according to the type of parameter, and the compiler determines the function to be called during compilation. The overloading of the function is independent of polymorphism.

Function overrides: function overrides, also known as function rewriting (override), are methods that subclasses redefine virtual functions of the base class.

The conditions that make up the function cover:

(1) functions of the base class must be virtual functions (declared by virtual)

(2) the two functions that overwrite must be in the derived class and the base class, respectively.

(3) the function name and argument list must be exactly the same.

Due to the fact that c # polymorphism is realized by virtual functions, function coverage is always associated with polymorphism, and it is the function that the program determines to call at run time, so it also becomes dynamic binding or late binding.

Function hiding: refers to a function with the same name as the base class in the subclass, but does not consider whether the parameter list is the same, thus hiding the function of the base class with the same name in the subclass. There are two situations:

(1) the subclass function is exactly the same as the base class function, except that the function of the base class does not use the virtual keyword, so the function of the base class will be hidden.

(2) the subclass function and the base class function have the same name, but the parameter list is different, in this case, the base class function will be hidden regardless of whether the base class function is declared as virtual or not.

Abstraction: find out some common features of some objects and put them into a class, which is created to consider only the similarities of these objects.

Encapsulation

Encapsulation (one of the object-oriented features): refers to hiding the properties and implementation details of the object and providing only public access to the outside world.

Benefits: isolation of changes; ease of use; improved reusability; security.

1. Encapsulation principle: hide the property, and if you need to access a property, provide public methods to access it

two。 Steps for encapsulation

1]. Use the private keyword to modify member variables.

2]. Provide a pair of getXxx methods and setXxx methods for the member variables that need to be accessed

3. Encapsulated operation-- private keyword

The meaning of private

1. Private is a permission modifier that represents minimum permissions.

two。 You can modify member variables and member methods.

3. Member variables and member methods modified by private can only be accessed in this class

The format of private: private data type variable name

For example, private int age;// has the lowest private access, and only the access in this class is valid.

Note: private ownership is only one form of encapsulation.

Private members: other classes cannot directly create object access, so private access can only be completed by providing specific access methods to this class, and it can be accessed in the form of functions.

Benefits: you can add logical judgment and other operations to the function, and judge the data and other operations.

Summary: when developing, keep in mind that properties are used to store data, are accessed directly, and are prone to security risks, so properties in classes are usually privatized and public access methods are provided.

There are generally two methods for this: for the property xxx, you can use setXXX () and getXXX () to operate on it.

4. Package optimization

Encapsulation optimization 51--this keyword

The meaning of this: this represents the reference (address value) of the current object of the class, that is, the reference of the object itself. This: represents an object. Is a reference to the object to which the function belongs.

What exactly does this stand for? Where the object calls the function where the this is located, the this represents the object and is the reference to the object. That is, this represents whoever is calling.

When do you use this when you are developing?

When defining a function, if the object that invokes the function is used internally by the function, the object is represented by this.

This can also be used for calls between constructors.

Call format: this (actual parameter)

1] follow the this object. Member properties and member methods are called (general methods)

This uses the format: this. Member variable Note: when there is only one variable name in the method, the this modifier is also used by default, which can be omitted.

2] the this object is followed by the () call to the constructor of the corresponding parameter in this class.

Note: calling the constructor with this must be defined on the first line of the constructor. Because the constructor is used for initialization, the initialization action must be performed. Otherwise, the compilation fails.

Encapsulation Optimization 2Mel-Construction method

When an object is created, the constructor is used to initialize the object, assigning initial values to the object's member variables.

Note: whether you customize constructors or not, all classes have constructors, because Java automatically provides a parameterless constructor, and once you define your own constructor, the default parameterless constructor provided by Java automatically becomes invalid.

The definition format of the construction method

Modifier constructor name (parameter list) {

/ / method body

}

The method name is the same as the class name in which the construction method is written. It does not return a value, so there is no need to return a value type, or even a void. Such as:

Public class Student {

Private String name;private int age

/ / No-parameter construction method

Public Student () {}

/ / Construction method with parameters

Public Student (String name,int age) {

This.name = name

This.age = age

}

}

Matters needing attention

1. If you do not provide a constructor, the system will give a parameterless constructor.

two。 If you provide a constructor, the system will no longer provide parameterless constructors.

3. Constructors can be overloaded, either defining parameters or not defining parameters

5. Standard Code-JavaBean

JavaBean is a standard specification for writing classes in the Java language. JavaBean-compliant classes that require classes to be concrete and public, with parameterless constructors, and provide set and get methods for manipulating member variables

Format:

Public class ClassName {

/ / member variable

/ / Construction method

/ / No-parameter construction method [required]

/ / Construction method with parameters [recommendation]

/ / member method

/ / getXxx ()

/ / setXxx ()

}

Succession (one of the object-oriented features)

Benefits:

1: improve the reusability of the code.

2: the relationship between classes is created, which provides another premise of characteristic polymorphism.

The origin of the parent class: in fact, it is derived from multiple classes constantly extracting common content upward.

For inheritance in java, java only supports single inheritance. Although java does not directly support multi-inheritance, it retains this multi-inheritance mechanism and makes improvements.

Single inheritance: a class can have only one parent class.

Multiple inheritance: a class can have more than one parent class.

Why not support multiple inheritance?

Because when a class inherits two parent classes at the same time, the two parent classes have the same function, so which one will run when the subclass object invokes the function? Because there is a method body in the method in the parent class.

But java supports multiple inheritance. An inherits B B inherits C C inherits D.

With the emergence of multiple inheritance, there is an inheritance system. The top-level parent class in the system is extracted by continuous upward extraction. It defines the function of the most basic and common content of the system.

Therefore, if a system wants to be used, you can directly consult the functions of the parent class in the system to know the basic usage of the system. So when you want to use a system, you need to create an object. It is recommended that you create the most subclass object, because the most subclass can not only use the functionality in the parent class. You can also use some of the features specific to subclasses.

To put it simply: for the use of an inheritance system, look up the contents of the top-level parent class and create objects of the lowest-level subclass.

What are the characteristics of the members of the class after the appearance of the child parent class:

1: member variable.

When the same attribute appears in the child parent class, the property is called by an object of the subclass type, and the value is the property value of the subclass.

If you want to call a property value in the parent class, you need to use a keyword: super

This: represents an object reference that is the type of this class.

Super: represents a memory space reference in the parent class to which the subclass belongs.

Note: the member variable of the same name usually does not appear in the child parent class, because as long as the parent class is defined, the subclass does not need to be defined, it can be inherited and used directly.

2: member function.

When exactly the same method appears in the child and parent class, creating the subclass object runs the method in the subclass. It is as if the methods in the parent class are overwritten. So this is another feature of the function: overwriting (overwriting, rewriting)

When should I use the overlay? When the functional content of a class needs to be modified, it can be overridden.

3: constructor.

It is found that when the subclass constructor runs, the constructor of the parent class is run first. Why?

Reason: the first line of all the constructors of the subclass actually has an invisible statement super ()

Super (): represents the constructor of the parent class and calls the constructor in the parent class corresponding to the parameter. Super (): is calling the constructor of the hollow parameter of the parent class.

Why do functions in the parent class need to be called when the subclass object is initialized? (why add this super () to the first line of the subclass constructor?)

Because the subclass inherits the parent class and inherits the data in the parent class, it depends on how the parent class initializes its own data. Therefore, when the subclass initializes the object, it first calls the constructor of the parent class, which is the instantiation process of the subclass.

Note: all constructors in the subclass access the constructor of the null parameter in the parent class by default, because the first line of each subclass constructor has a default statement super ().

If there is no constructor with null arguments in the parent class, the constructor in the parent class to be accessed must be specified through the super statement in the constructor of the subclass.

If this is used in the subclass constructor to specify to call the subclass's own constructor, then the called constructor will also access the constructor in the parent class.

Question: whether super () and this () can appear in the constructor at the same time.

Only one of the two statements can be defined on the first line, so only one of them can appear.

Super () or this (): why does it have to be on the first line?

Because either super () or this () calls the constructor, which is used for initialization, the initialization has to be done first.

Details of inheritance:

When do you use inheritance?

Only when there is an ownership relationship between classes, does it have the premise of inheritance. An is one of the b. An inherits b. Wolf is a kind of canine family.

In English books, ownership: "is a"

Note: don't inherit just to get existing members of other classes.

Therefore, to judge the ownership relationship, we can simply see that if, after inheritance, the functions in the inherited class can be possessed by the subclass, then the inheritance is established. If not, it cannot be inherited.

Detail 2:

When overriding a method, note two points:

1: when a subclass overrides the parent class, it must be guaranteed that the permission of the subclass method must be greater than or equal to that of the parent method to achieve inheritance. Otherwise, the compilation fails.

2: when covering, it is either static or non-static. (static can only be overridden by static, or can be overwritten by static)

One drawback of inheritance is that it breaks the encapsulation. For some classes, or functions in the class, need to be inherited or overridden.

How to solve the problem at this time? Introduce a keyword, final: finally.

Final features:

1: this keyword is a modifier that modifies classes, methods, and variables.

2: the class decorated by final is a final class and cannot be inherited.

3: the method modified by final is a final method and cannot be overridden.

4: the variable modified by final is a constant and can only be assigned once.

In fact, the reason for this is to give some fixed data a more readable name.

Can't it be used without final modification? Then this value is a variable and can be changed. With the addition of final, the procedure is more rigorous. When a constant name is defined, there is a specification, and all letters are capitalized. If it is made up of multiple words, it is concatenated with _.

Abstract class: abstract

Abstract: not specific, can not understand. Abstract class representation.

In the process of continuous extraction, the method declaration in the common content is extracted, but the method is different and there is no extraction, so the extracted method is not specific and needs to be marked by the specified keyword abstract and declared as an abstract method.

The class of the abstract method must be marked as an abstract class, that is, the class needs to be modified by the abstract keyword.

The characteristics of the abstract class:

1: abstract methods can only be defined in abstract classes, abstract classes and abstract methods must be modified by the abstract keyword (classes and methods can be described, not variables).

2: abstract methods only define method declarations, not method implementations.

3: abstract classes cannot be created objects (instantiated).

4: the subclass can be instantiated only if it inherits the abstract class and overrides all abstract methods in the abstract class. Otherwise, the subclass is still an abstract class.

Details of the abstract class:

1: is there a constructor in the abstract class? Yes, used to initialize subclass objects.

2: can non-abstract methods be defined in abstract classes?

Sure. In fact, there is not much difference between abstract classes and general classes, they all describe things, but when abstract classes describe things, some functions are not specific. Therefore, both abstract classes and general classes need to define attributes and behaviors. It's just that there is one more abstract function than the normal class. And there is one less part of creating an object than a normal class.

3: the abstract keyword abstract and what can't coexist? Final, private, static

4: is it possible not to define abstract methods in abstract classes? Sure. The purpose of an abstract method is simply to prevent the class from creating objects.

Main function and constructor and general function

1. Principal function

Why is there no main function defined in the class?

Note: the main function exists only for whether the class needs to run independently, if not, the main function does not need to be defined.

The interpretation of the main function: to ensure that the class runs independently, is the entry of the program, and is called by jvm.

two。 Constructor: used to initialize the object, is to initialize the corresponding object, it is targeted, one of the functions.

Constructor characteristics:

1: the name of the function is the same as the name of the class in which it belongs.

2: there is no need to define the return value type.

3: this function has no specific return value.

Remember: all objects need to be initialized before they can be used when they are created.

Note: when a class is defined, if there is no constructor defined, an empty parameter constructor is automatically generated in the class. In order to facilitate the class to create objects, initialization is completed. If you customize the constructor in the class, the default constructor is gone.

There can be multiple constructors in a class, because their function names are all the same, so they can only be distinguished by a list of arguments. Therefore, if more than one constructor appears in a class. Their existence is reflected by overloading.

What is the difference between a constructor and a general function?

1: the two function definitions are in different formats.

2: the constructor is called when the object is created for initialization, and the initialization action is performed only once.

A general function, after the object is created, needs to be called before execution, and can be called multiple times.

When do I use the constructor?

When analyzing things, it is found that as soon as specific things appear, they have some characteristics, so define these characteristics into the constructor.

What's the difference between a code block and a constructor?

Construction code block: initializes all objects, that is, all objects call a code block. As soon as the object is established. The code block is called.

Constructor: initializes the corresponding object. It is targeted.

Person p = new Person ()

What does it do to create an object in memory?

1: first load the Person.class file in the specified location on the hard disk into memory.

2: when the main method is executed, the space of the main method is opened up in the stack memory (push stack-stack), and then a variable p is allocated in the stack area of the main method.

3: open up a physical space in the heap memory and assign a memory header address value. New

4: the attribute space is allocated in the entity space and initialized by default.

5: initialize the display of attributes in the space.

6: initialize the construction code block of the entity.

7: call the constructor corresponding to the entity to initialize the constructor. (.)

8: assign the first address to p, and the p variable references the entity. (pointed to the object)

-

Static: ★★★ keyword

The static keyword is a modifier that modifies variables, methods, and blocks of code. In the process of using it, the main purpose is to call the method without creating the object.

Static principle

Static embellished content:

Is loaded with the loading of the class, and only once.

It is stored in a fixed memory area (static area), so it can be called directly by the class name.

It takes precedence over objects, so it can be shared by all objects.

1. Modify variables:

Class variable: a member variable modified with the static keyword. Each object of this class shares the value of the same class variable. Any object can change the value of this class variable, but you can also manipulate class variables when an object of this class is not created

When used to modify members (member variables and member functions), the modified member belongs to the class, not just to an object. That is, since it belongs to a class, it can be called without creating an object.

Class variable definition format: static data type variable name

Such as: static int numberID

two。 Modification method:

Static method

Class methods: member methods modified with the static keyword. Static methods have static in the declaration, and it is recommended that you call them with a class name instead of a

Create an object of the class. The method of calling is very simple.

Define the format:

The modifier static returns the value type method name (parameter list) {

/ / execute statement

}

Considerations for static method calls:

1] static methods can access class variables and static methods directly.

2] static methods can only access static members, not ordinary member variables or member methods directly. Conversely, member methods can access class variables or static methods directly.

3] the this keyword cannot be used in static methods.

Call format

Members decorated by static can and are recommended to access directly through the class name. Although static members can also be accessed through object names, the reason is that multiple objects belong to

For a class, share the same static member, but it is not recommended that a warning message appears.

Format:

/ / access class variables

Class name. Class variable name

/ / call static method

Class name. Static method name (parameter)

3. Decorate code block

Static code block

Static code block: a code block {} defined in a member location and decorated with static.

Location: outside the method in the class.

Execution: executes once as the class is loaded, taking precedence over the execution of main methods and constructors.

Function: initialize and assign values to class variables.

Format:

Public class ClassName {

Static {

/ / execute statement

}

}

Static features:

1. Want to realize the object sharing of common data in the object. This data can be statically modified.

2, the statically modified member can be called directly by the class name. In other words, static members have one more way to call. Class name. Static mode.

3. Static is loaded as the class is loaded. And takes precedence over the object.

Static drawbacks:

1. Some data is object-specific and cannot be statically modified. Because in that case, the unique data becomes the shared data of the object. There is something wrong with the description of things in this way. Therefore, when defining static, it must be clear whether this data is shared by the object.

2, static methods can only access static members, not non-static members.

Because static methods take precedence over objects when loaded, there is no way to access members of the object.

3. The this,super keyword cannot be used in static methods.

Because this represents an object, and when static is present, there may be no object, so this cannot be used.

4, the main function is static

When do you define static members? Or: do you need to be statically modified when defining members?

There are two types of members:

1, member variable. (static when sharing data)

Whether the data of this member variable is the same for all objects:

If so, then the variable needs to be statically modified because it is shared data.

If not, it is said that this is object-specific data to be stored in the object.

2, member function. (defined as static when there is no call to unique data in the method)

What if you decide whether the member function needs to be statically modified?

As long as you refer to whether the unique data in the object is accessed within the function:

If there is access to specific data, the method cannot be statically modified.

If there is no access to unique data, then this method needs to be statically modified.

The difference between member variables and static variables:

1, the object to which the member variable belongs. So it is also called instance variable.

The class to which the static variable belongs. So it is also called class variable.

2, member variables exist in heap memory.

Static variables exist in the method area.

3, member variables exist with object creation. Disappear as the object is recycled.

Static variables exist with the loading of the class. Disappear with the disappearance of the class.

4, member variables can only be called by the object.

Static variables can be called by an object or by a class name.

Therefore, member variables can be called object-specific data, and static variables can be called object-shared data.

Static attention: static life cycle is very long.

Static code block: an area of a code block marked with static keywords. Defined in the class.

Function: the initialization of the class can be completed. Static blocks of code are executed as the class loads, and only once (new multiple objects are executed only once). If it is in the same class as the main function, it takes precedence over the main function.

Public: the maximum access rights.

Static: you don't need an object, just the class name.

Void: the main function does not return a value.

Main: the name specific to the main function.

(String [] args): the argument of the main function is a parameter of a string array type. When jvm calls the main method, the actual argument passed is new String [0].

Jvm passes an array of strings of length 0 by default, and when we run this class, we can also specify specific parameters to pass. You can add parameters later in the console when you run this class. Parameters are separated by spaces. Jvm automatically stores these string parameters as elements in the args array.

Execution order when static code block, constructor block and constructor exist at the same time: static code block à constructor block à constructor

Generate Java help documentation: command format: javadoc-d folder name-auther-version * .java

/ * / format

* Class description

* @ author author name

* @ version version number

, /

/ * *

* method description

* @ param parameter description

* @ return return value description

, /

-

Design pattern:

Design pattern: the most effective way to solve problems. Is a set of repeated use, most people know, after classification and cataloging, a summary of code design experience. Design patterns are used to reuse code, make it easier for others to understand, and ensure code reliability.

There are 23 design patterns in java:

Singleton design pattern: ★

Problem solved: ensure the object uniqueness of a class in memory.

For example, when multiple programs read a configuration file, it is recommended that the configuration file be encapsulated into an object. It is convenient to manipulate the data, and to ensure that multiple programs read the same profile object, the profile object is required to be unique in memory.

The Runtime () method is designed in a singleton design pattern.

How to ensure the uniqueness of the object?

Thoughts:

1, do not let other programs create this kind of object.

2, create a class object in this class.

3. Provide methods for other programs to get this object.

Steps:

1, because constructor initialization is required to create objects, as long as the constructors in this class are privatized, other programs can no longer create such objects.

2, create an object of this class in the class

3, define a method and return the object so that other programs can get the object of this class through the method. (function: controllable)

The code reflects:

1, privatization constructor

2. Create private and static objects of this class

3. Define a public and static method that returns the object.

-

/ / hungry Han style

Class Single {

Private Single () {} / / privatize constructor.

Private static Single s = new Single (); / / create private and static objects of this class.

Public static Single getInstance () {/ / defines a public and static method that returns the object.

Return s

}

}

-

/ / lazy style: delayed loading mode.

Class Single2 {

Private Single2 () {}

Private static Single2 s = null

Public static Single2 getInstance () {

If (s==null)

S = new Single2 ()

Return s

}

}

-

-

Template method design pattern:

Problem solved: when part of the function is implemented, it is determined, and part of the implementation is uncertain. At this point, you can expose the uncertain parts and let the subclasses implement them.

Abstract class GetTime {

Public final void getTime () {/ / if this function does not need to be copied, final can be added.

Long start = System.currentTimeMillis ()

Code (); / / uncertain functional parts are extracted and implemented by abstract methods.

Long end = System.currentTimeMillis ()

System.out.println ("millisecond is:" + (end-start))

}

Public abstract void code (); / / abstract the uncertain function and let the subclass overwrite the implementation

}

Class SubDemo extends GetTime {

Public void code () {/ / subclass replication function method

For (int yellow0; y servlet server java Mini Program.

Jar: a compressed package of java that is mainly used to store class files, configuration files, etc.

Command format: jar-cf package name. jar package directory

Extract: jar-xvf package name. Jar

Redirect the jar package directory list to a file: jar-tf package name. Jar > c:\ 1.txt

-

Multithreading: ★★★★

Process: a program in progress. In fact, a process is the memory allocation space when an application is running.

Thread: in fact, it is a program execution control unit and an execution path in the process. The process is responsible for the marking of the application's space. The thread is responsible for the execution order of the application.

A process has at least one thread running. When there are multiple threads in a process, the application is called a multithreaded application. Each thread has its own execution space, its own method area and its own variables in the stack area.

When jvm starts, it first has a main thread, which is responsible for the execution of the program and calls the main function. The code executed by the main thread is all in the main method.

When garbage is generated, the action of garbage collection does not need to be completed by the main thread, because in this way, the execution of the code in the main thread will stop and the garbage collector code will be run, which is inefficient, so a single thread is responsible for garbage collection.

The principle of randomness: because of the fast switching of cpu, which thread obtains the right to execute cpu, which thread will execute.

Returns the name of the current thread: Thread.currentThread () .getName ()

The name of the thread is defined by the: Thread- number. The number starts at 0.

The code that the thread wants to run is uniformly stored in the run method.

The thread must be opened by the method specified in the class to run. Start method. (after startup, there is one more execution path.)

Start method: 1), started the thread; 2), let jvm call the run method.

The first way to create a thread is to inherit the Thread and override the run method by the subclass.

Steps:

1. Define that the class inherits the Thread class

2. The purpose is to overwrite the run method, where all the code to be run by the thread is stored in the run method

3. Create a thread object by creating a subclass object of the Thread class

4. Call the thread's start method, start the thread, and execute the run method.

Thread status:

Created: start ()

Operation: have the executive qualification and the executive power at the same time

Freeze: sleep (time), wait ()-notify () wake up; thread releases execution power and releases execution qualification at the same time

Temporary blocking state: the thread is qualified to execute cpu and does not have the right to execute cpu

Demise: stop ()

The second way to create a thread is to implement an interface Runnable.

Steps:

1. Define the class to implement the Runnable interface.

2, override the run method in the interface (used to encapsulate the code that the thread is going to run).

3. Create thread objects through the Thread class

4. Pass the subclass object that implements the Runnable interface as the actual parameter to the constructor in the Thread class.

Why pass it on? Because you want the thread object to know the object to which the run method you want to run belongs to.

5. Call the start method of the Thread object. Start the thread and run the run method in the Runnable interface subclass.

Ticket t = new Ticket ()

/ *

Create a Ticket object directly, not a thread object.

Because objects can only be created through the new Thread class, or a subclass of the new Thread class.

So eventually you want to create a thread. Since there are no subclasses of the Thread class, you can only use the Thread class.

, /

Thread T1 = new Thread (t); / / create a thread.

/ *

As long as t is passed as the actual parameter of the constructor of the Thread class, the association between the thread object and t can be completed.

Why pass t to the constructor of the Thread class? In fact, it is to identify the run method of the code that the thread wants to run.

, /

T1.start ()

Why is there a Runnable interface?

1: the establishment of multithreading can be completed by inheriting the Thread class. But this approach has a limitation: if a class already has its own parent class, it cannot inherit the Thread class because of the limitations of java single inheritance.

However, there is still some code in this class that needs to be executed by multiple threads at the same time. What are we going to do then?

Only by making additional functional extensions to this class, java provides an interface Runnable. The run method is defined in this interface. In fact, the definition of the run method is to store the code to be run by multithreading.

Therefore, threads are usually created in the second way.

Because implementing the Runnable interface avoids the limitations of single inheritance.

2: in fact, it is to extract the code that needs to be executed by multi-thread in different classes. Define the location of the code to be run by multithreading into the interface separately. It provides a prerequisite for other classes to extend their functions.

So when the Thread class describes the thread, the internally defined run method also comes from the Runnable interface.

Implementing the Runnable interface avoids the limitations of single inheritance. Moreover, inheriting Thread, you can subclass override the methods in the Thread class. However, if you do not need to do this copy action, it is more convenient to implement the Runnable interface just to define where the thread code is stored. So the Runnable interface encapsulates the task that the thread is going to perform into an object.

/ / interview

New Thread (new Runnable () {/ / Anonymous)

Public void run () {

System.out.println ("runnable run")

}

}

{

Public void run () {

System.out.println ("subthread run")

}

}. Start (); / / result: subthread run

Try {

Thread.sleep (10)

} catch (InterruptedException e) {} / / simulate cpu switching when the thread is deliberately paused.

Causes of multithreaded safety problems:

Through illustration: it is found that when a thread is executing multiple statements and calculating the same data, other threads participate in the execution and manipulate the data. This leads to the generation of wrong data.

Two factors are involved:

1, multiple threads are operating to share data.

2, there are multiple statements to operate on the shared data.

Reason: these statements are executed by other threads before they are finished when they are executed by one thread at a certain time.

Principles for solving security problems:

As long as the statements that operate on shared data are executed by one thread in a certain period of time, this problem can be solved if other threads cannot come in to execute during the execution.

How to encapsulate the shared data code for multiple operations?

One solution provided in java is to synchronize code blocks.

Format:

Synchronized (object) {/ / any object is fine. This object is the lock.

Code that needs to be synchronized

}

Synchronization: ★

Benefits: thread safety issues have been solved.

Disadvantages: relatively reduce performance, because judging locks need to consume resources, resulting in a deadlock.

There is a premise for defining synchronization:

1. There must be two or more threads to synchronize.

2, multiple threads must ensure that the same lock is used.

The second form of synchronization:

Synchronization function: in fact, the synchronization keyword is defined on the function, so that the function has synchronization.

Which lock is used in the synchronization function?

After verification, the function has its own object this, so the lock used by the synchronization function is the this lock.

Which lock is used for synchronization when the synchronization function is modified by static?

The static function belongs to the class when it is loaded, and there may be no object generated by this class, but the bytecode file of this class has been encapsulated into an object when it is loaded into memory, and this object is the bytecode file object of the class.

So when statically loaded, only one object exists, then the static synchronization function uses this object.

This object is the class name .class

What is the difference between synchronization code blocks and synchronization functions?

The lock used by the synchronization code block can be any object.

The lock used by the synchronization function is this, and the lock of the static synchronization function is the bytecode file object of this class.

There is only one synchronization in a class, and you can use synchronization functions. If there is multiple synchronization, you must use synchronization code blocks to determine different locks. So synchronization code blocks are relatively flexible.

★ test site question: would you please write a singleton mode with delayed loading? Write lazy style; what to do when there is multithreaded access? Add synchronization to solve security problems; is it efficient? Not high; how to solve it? It is solved by double judgment.

/ / lazy style: delayed loading mode.

When multithreading accesses lazy data, because multiple statements operate on common data within the lazy method. Therefore, it is easy to have thread safety problems. In order to solve the problem, join the synchronization mechanism to solve the security problem. But it brings inefficiency.

In order to solve the problem of efficiency, it is solved in the form of double judgment.

Class Single {

Private static Single s = null

Private Single () {}

Who is the public static Single getInstance () {/ / lock? Bytecode file object

If (s = = null) {

Synchronized (Single.class) {

If (s = = null)

S = new Single ()

}

}

Return s

}

}

Synchronous deadlock: you can usually see the phenomenon as long as you nest the synchronization. There is a synchronization code block in the synchronization function and a synchronization function in the synchronization code block.

Inter-thread communication: idea: multiple threads are operating on the same resource, but the actions are different.

1: encapsulate the resource into an object.

2: the task that will be executed by the thread (the task is actually the run method.) It is also encapsulated into an object.

Wait-and-wake mechanism: the methods involved:

Wait: the thread in synchronization is frozen. Released the executive power, released the qualification. The thread object is also stored in the thread pool.

Notify: wakes up a waiting thread in the thread pool.

NotifyAll: all threads in the thread pool are awakened.

Note:

1: these methods need to be defined in synchronization.

2: because these methods must indicate the lock to which they belong.

You should know that the thread on lock An is wait, then this thread is equivalent to being in the thread pool of lock An and can only be awakened by the notify of lock A.

3: all three methods are defined in the Object class. Why are methods for manipulating threads defined in the Object class?

Because these three methods need to define synchronization and indicate the synchronization lock to which they belong, since the lock is called and the lock can be any object, the methods that can be called by any object must be defined in the Object class.

The difference between wait and sleep: analyze these two methods: from the perspective of executive power and lock:

Wait: you can specify a time or not. Do not specify a time, can only be awakened by the corresponding notify or notifyAll.

Sleep: you must specify a time to automatically transition from frozen state to running state (temporary blocking state).

Wait: the thread releases the execution power, and the thread releases the lock.

Sleep: the thread releases execution power, but not without releasing the lock.

Stop the thread: you can stop the thread through the stop method. But this method is out of date.

Stop the thread: the principle is that the code that the thread is running ends, that is, the run method.

How do I end the run method? A loop must be defined in a general run method. So just end the cycle.

The first way: define the end tag of the loop.

The second way: if the thread is in a frozen state, it is impossible to read the tag, so you need to force its frozen state to clear through the interrupt method in the Thread class. Restore the thread to a qualified state so that the thread can read the tag and end.

-

Interrupt (): interrupt the thread.

SetPriority (int newPriority): change the priority of a thread.

GetPriority (): returns the thread's priority.

ToString (): returns a string representation of the thread, including the thread name, priority, and thread group.

Thread.yield (): pauses the currently executing thread object and executes other threads.

SetDaemon (true): marks the thread as either a daemon thread or a user thread. Mark the thread as either a daemon thread or a user thread. The Java virtual machine exits when all the running threads are daemon threads. This method must be called before starting the thread.

Join: you can use the join method when temporarily joining a thread.

When thread An executes to the join mode of thread B. Thread An is frozen, the right of execution is released, and thread B begins to execute. A when will it be implemented? It is only when thread B is finished that A resumes execution from the frozen state.

Lock interface: when multithreading upgrades the JDK1.5 version, it introduces an interface Lock interface.

Thread safety problems are solved in the form of synchronization (synchronizing code blocks or synchronization functions). In fact, locking mechanisms are used in the end.

In a later version, the lock is encapsulated directly into an object. When a thread enters synchronization, it has the lock, when it is executed, and when it leaves synchronization, it releases the lock.

In the later analysis of the lock, it is found that the action of acquiring or releasing the lock should be the lock more clearly. So these actions are defined in the lock, and the lock is defined as an object.

So synchronization is an implicit lock operation, while the Lock object is a displayed lock operation, and its presence replaces synchronization.

In previous versions, it was done using wait, notify, and notifyAll in the Object class. That's because the lock in synchronization is an arbitrary object, so the wakeup methods for manipulating the lock are defined in the Object class.

Now the lock is the specified object Lock. Therefore, finding the wait-and-wake mechanism needs to be done through the Lock interface. The Lock interface does not directly operate the methods waiting for wake-up, but encapsulates these methods in a separate object. This object is Condition, which encapsulates the three methods in Object separately. And provide consistent methods await (), signal (), signalAll () to reflect the benefits of the new version of the object.

Condition interface: await (), signal (), signalAll ()

Class BoundedBuffer {

Final Lock lock = new ReentrantLock ()

Final Condition notFull = lock.newCondition ()

Final Condition notEmpty = lock.newCondition ()

Final Object [] items = new Object [100]

Int putptr, takeptr, count

Public void put (Object x) throws InterruptedException {

Lock.lock ()

Try {

While (count = = items.length)

NotFull.await ()

Items [putptr] = x

If (+ + putptr = = items.length) putptr = 0

+ + count

NotEmpty.signal ()

}

Finally {

Lock.unlock ()

}

}

Public Object take () throws InterruptedException {

Lock.lock ()

Try {

While (count = = 0)

NotEmpty.await ()

Object x = items [takeptr]

If (+ + takeptr = = items.length) takeptr = 0

-- count

NotFull.signal ()

Return x

}

Finally {

Lock.unlock ()

}

}

}

-

API: (Application Programming Interface, application programming interface) are predefined functions designed to provide applications and developers with the ability to access a set of routines based on some software or hardware without having to access the source code or understand the details of the internal working mechanism.

-String string: ★★★☆

The String class is used to describe it in java. The string is encapsulated by an object. The advantage is that you can easily manipulate common data such as strings. After the object is encapsulated, you can define N multiple attributes and behaviors.

How do you define a string object? String s = "abc"; any data caused by double quotation marks is a string object.

Features: once the string is initialized, it cannot be changed and stored in the constant pool in the method area.

String S1 = "abc"; / / S1 points to only one object abc in memory.

String S2 = new String ("abc"); / S2 points to two objects abc and new.

System.out.println (s1==s2); / / false = = compares address values

System.out.println (s1.equals (S2)); / / true, the equals in the string compares whether the string content is the same.

In Object, equals compares the address values of two objects to see if they are the same.

Check API.

Method of string:

1: construction method: convert a byte array or character array into a string.

String S1 = new String (); / / creates a string of empty content.

String S2 = null;//s2 has no object pointing and is a null constant value.

String S3 = ""; / / S3 points to a specific string object, but there is nothing in this string.

/ / generally, when defining a string, you do not use new.

String S4 = new String ("abc")

String S5 = "abc"; this is commonly used

New String (char []); / / converts an array of characters to a string.

New String (char [], offset,count); / / converts a portion of the character array into a string.

2: general method:

According to the object-oriented idea:

2.1 obtain:

2.1.1: get the length of the string. Length ()

2.1.2: the character of the specified position. Char charAt (int index)

2.1.3: gets the position of the specified character. If there is no return of-1, you can determine whether a character does not exist by returning a value of-1.

Int indexOf (int ch); / / returns the character corner sign found for the first time

Int indexOf (int ch,int fromIndex); / / returns the corner marker found for the first time from the specified location

Int indexOf (String str); / / returns the corner of the string found for the first time

Int indexOf (String str,int fromIndex)

Int lastIndexOf (int ch)

Int lastIndexOf (int ch,int fromIndex)

Int lastIndexOf (String str)

Int lastIndexOf (String str,int fromIndex)

2.1.4: get the substring.

String substring (int start); / / starts with the start bit and ends with length ()-1.

String substring (int start,int end); / / from start to end. / / contains the start bit, but not the end bit.

Substring (0quotation str.length ()); / / get the whole string

2.2 judgment:

2.2.1: does the string contain the specified string?

Boolean contains (String substring)

2.2.2: does the string begin with the specified string?

Boolean startsWith (string)

2.2.3: does the string end with the specified string?

Boolean endsWith (string)

2.2.4: determine whether the string is the same

Boolean equals (string); / / overrides the method in Object to determine whether the string content is the same.

2.2.5: determine whether the contents of the string are the same, ignoring case.

Boolean equalsIgnoreCase (string)

2.3 conversion:

2.3.1: you can convert an array of characters or bytes into a string through the constructor.

2.3.2: you can convert an array of characters into a string through static methods in a string.

Static String copyValueOf (char [])

Static String copyValueOf (char [], int offset,int count)

Static String valueOf (char [])

Static String valueOf (char [], int offset,int count)

2.3.3: convert basic data types or objects to strings.

Static String valueOf (char)

Static String valueOf (boolean)

Static String valueOf (double)

Static String valueOf (float)

Static String valueOf (int)

Static String valueOf (long)

Static String valueOf (Object)

2.3.4: convert the string to case.

String toLowerCase ()

String toUpperCase ()

2.3.5: turn the string into an array.

Char [] toCharArray (); / / turns into a character array.

Byte [] getBytes (); / / can be added to the coding table. Into a byte array.

2.3.6: convert a string to an array of strings. Cutting method.

String [] split (rules for segmentation-string)

2.3.7: replace the content of the string. Note: change to a new string after modification, not directly modify the original string.

String replace (oldChar,newChar)

String replace (oldstring,newstring)

2.3.8: String concat (string); / / appends a pair of strings.

String trim (); / / remove the spaces at both ends of the string

Int compareTo (); / / returns a value of 0 if the parameter string is equal to this string, a value less than 0 if the string is less than the string parameter in lexicographical order, and a value greater than 0 if the string is greater than the string parameter in lexicographical order.

-

-StringBuffer string buffer: ★★★☆

Construct a string buffer without characters, with an initial capacity of 16 characters.

Features:

1: the content of the string can be modified.

2: it's a container.

3: it is of variable length.

4: any type of data can be stored in the buffer.

5: eventually you need to turn it into a string.

Containers usually have some fixed methods:

1, add.

StringBuffer append (data): appends data to the buffer. Append to the tail.

StringBuffer insert (index,data): inserts data at the specified location.

2, delete.

StringBuffer delete (start,end); delete elements from start to end-1

StringBuffer deleteCharAt (index); deletes the element at the specified location

/ / sb.delete (0menthsb.length ()); / / clear the buffer.

3, modify.

StringBuffer replace (start,end,string); replace start to end-1 with string

Void setCharAt (index,char); replaces the character at the specified position

Void setLength (len); sets the original string to a string of specified length

4, find out. (no return-1)

Int indexOf (string); returns the index of the first occurrence of the specified substring in this string.

Int indexOf (string,int fromIndex); find the string from the specified location

Int lastIndexOf (string); returns the index at the rightmost occurrence of the specified substring in this string.

Int lastIndexOf (string,int fromIndex); reverse search from the specified index

5. Get the substring.

String substring (start); returns the substring from start to the end

String substring (start,end); returns the substring from start to end-1

6, reverse.

StringBuffer reverse (); string inversion

-

-StringBuilder string buffer: ★★★☆

JDK1.5 appears StringBuiler; to construct a string generator without characters, with an initial capacity of 16 characters. This class is designed to be used as a simple replacement for StringBuffer when a string buffer is used by a single thread (which is common).

In the same way as StringBuffer

The difference between StringBuffer and StringBuilder:

StringBuffer is thread safe.

StringBuilder thread is not safe.

Single-threaded operation, efficient use of StringBuilder.

Multithreaded operation, using StringBuffer security.

StringBuilder sb = new StringBuilder ("abcdefg")

Sb.append ("ak"); / / abcdefgak

Sb.insert (1, "et"); / / aetbcdefg

Sb.deleteCharAt (2); / / abdefg

Sb.delete (2B4); / / abefg

Sb.setLength (4); / / abcd

Sb.setCharAt (0djink'); / / kbcdefg

Sb.replace (0Magne2, "hhhh"); / / hhhhcdefg

/ / if you want to use a buffer, you first need to create an object.

StringBuffer sb = new StringBuffer ()

Sb.append (12). Append (""); / / method call chain.

String s = "abc" + 4 million Q'

S = new StringBuffer (). Append ("abc"). Append (4). Append ('q'). ToString ()

Class Test {

Public static void main (String [] args) {

String S1 = "java"

String S2 = "hello"

Method_1 (S1 and S2)

System.out.println (S1 + "...." + S2); / / java....hello

StringBuilder S11 = new StringBuilder ("java")

StringBuilder S22 = new StringBuilder ("hello")

Method_2 (s11 and S22)

System.out.println (s11 + "-" + S22); / / javahello-hello

}

Public static void method_1 (String S1 and string S2) {

S1.replace ('axiomatica')

S1 = S2

}

Public static void method_2 (StringBuilder S1 and StringBuilder S2) {

S1.append (S2)

S1 = S2

}

}

Basic data type object wrapper class: the basic data type is encapsulated into an object according to the object-oriented idea.

Benefits:

1: basic data can be manipulated through properties and behaviors in the object.

2: the conversion between basic data types and strings can be implemented.

The class name corresponding to the keyword

Byte Byte

Short Short paserShort (numstring)

Int Integer static method: parseInt (numstring)

Long Long

Float Float

Double Double

Char Character

Boolean Boolean

Basic data type object wrapper class: all have XXX parseXXX methods

There is only one type without a parse method: Character

Integer object: ★★★☆

The method of converting numeric format strings to basic data types:

1: encapsulate the string into an Integer object and call the object's method intValue ()

2: use Integer.parseInt (numstring): instead of creating an object, call the class name directly.

Convert the basic type to a string:

Static method String toString (int) in 1:Integer

2intt + ""

Convert a decimal integer to another base:

Convert to binary: toBinaryString

Convert to octal: toOctalString

Convert to hexadecimal: toHexString

ToString (int num,int radix)

Convert other decimal to decimal:

ParseInt (string,radix); / / converts the given number to the specified cardinality

After the jdk1.5 version, upgrade the basic data type object wrapper class. In an upgrade, wrapper classes using basic data types can perform operations in the same way as basic data types.

Integer I = new Integer (4); / / written before version 1.5

Integer I = 4; / / automatically boxed, written after version 1.5

I = I + 5

The / / I object cannot be added directly to 5. In fact, the bottom layer converts I to int first and adds it to 5. Operations that are converted to the int type are implicit. Automatic unpacking: the principle of unpacking is i.intValue (); iTun5 is an int integer after operation. How do you assign a value to reference type I? In fact, the results are boxed.

Integer c = 127c

Integer d = 127,

System.out.println (c = = d); / / true

/ / when packing, if the value is within the byte range, then the value is the same, and no new object will be generated, that is, multiple references with the same value point to the same object.

-

Collection framework: ★, a container for storing data.

Features:

1: objects encapsulate data, and if there are many objects, they need to be stored. Collections are used to store objects.

2: an array can be used to determine the number of objects, but what to do if you are not sure? You can use a collection. Because the collection is of variable length.

The difference between a collection and an array

1: the array is of fixed length; the set is of variable length.

2: arrays can store both basic and reference data types; collections can only store reference data types.

3: the elements stored in the array must be of the same data type; the objects stored in the collection can be different data types.

Data structure: this is how the data is stored in the container.

For collection containers, there are many kinds. Because each container has its own characteristics, the principle is that the internal data structure of each container is different.

The collection container is in the process of continuous upward extraction. There is a collection system.

When using a system, the principle: see the top-level content. Create the underlying object.

-Collection API:

Collection:

|-- List: in order (the order in which elements are stored in the collection is the same as the order in which they are taken out), and all elements are indexed. Elements can be repeated.

|-- Set: out of order (the order of deposit and withdrawal may be different), and duplicate elements cannot be stored. Element uniqueness must be guaranteed.

1, add:

Add (object): add an element

AddAll (Collection): add all the elements in a collection.

2, delete:

Clear (): deletes all the elements in the collection and empties the collection.

Remove (obj): deletes the specified object in the collection. Note: if deleted successfully, the length of the collection will change.

RemoveAll (collection): deletes some elements. Some elements are consistent with the incoming Collection.

3. Judge:

Boolean contains (obj): whether the collection contains the specified element.

Boolean containsAll (Collection): whether the collection contains multiple elements specified.

Boolean isEmpty (): whether there are elements in the collection.

4, get:

Int size (): there are several elements in the collection.

5, take the intersection:

Boolean retainAll (Collection): retains the same elements in the current collection as in the specified collection. Returns flase; if the two collection elements are the same. If retainAll modifies the current collection, it returns true.

6. Get all the elements in the collection:

Iterator iterator (): iterator

7, turn the collection into an array:

ToArray ()

-Iterator API:

Iterator: is an interface. Function: used to fetch elements in the collection.

Boolean

HasNext () returns true if there are still elements to iterate over.

E

Next () returns the next element of the iteration.

Void

Remove () removes the last element returned by the iterator from the collection pointed to by the iterator (optional).

Each collection has its own data structure and a specific way to extract its own internal elements. To make it easier to manipulate all the containers, take out the element. The way to remove the inside of the container is provided to the outside according to a unified rule, which is the Iterator interface.

In other words, as long as you can extract the elements in the Collection collection through this interface, you don't have to care about how each specific container extracts the details according to its own data structure, which reduces the coupling between the fetched elements and the specific collection.

Iterator it = coll.iterator (); / / gets the iterator object in the container, and it doesn't matter what this object is. This object must conform to a regular Iterator interface.

Public static void main (String [] args) {

Collection coll = new ArrayList ()

Coll.add ("abc0")

Coll.add ("abc1")

Coll.add ("abc2")

/ /-Mode 1 Mui-

Iterator it = coll.iterator ()

While (it.hasNext ()) {

System.out.println (it.next ())

}

/ /-Mode 2 uses this--

For (Iterator it = coll.iterator (); it.hasNext ();) {

System.out.println (it.next ())

}

}

-List API:

List itself is a subinterface of the Collection interface and has all the methods of Collection. Now we learn the common methods unique to the List system, and we find that all the unique methods of List have indexes, which is the biggest feature of the collection.

List: ordered (the order in which elements are stored in the collection is the same as the order in which they are taken out), and elements are indexed. Elements can be repeated.

|-- ArrayList: the underlying data structure is an array, threads are out of sync, ArrayList replaces Vector, and the speed of querying elements is very fast.

|-- LinkedList: the underlying data structure is a linked list, threads are out of sync, and the speed of adding and deleting elements is very fast.

|-- Vector: the underlying data structure is an array, threads are synchronized, and Vector is extremely slow to query, add or delete.

1, add:

Add (index,element): inserts an element at the specified index bit.

AddAll (index,collection): inserts a stack of elements at the specified index bit.

2, delete:

Remove (index): deletes the element with the specified index bit. Returns the deleted element.

3, get:

Object get (index): gets the specified element by index.

Int indexOf (obj): gets the index bit that occurs for the first time for the specified element, and returns-1 if the element does not exist

So, with-1, you can determine whether an element exists or not.

Int lastIndexOf (Object o): the reverse index specifies the location of the element.

List subList (start,end): gets the sublist.

4. Modify:

Object set (index,element): modifies the element to the specified index bit.

5, get all the elements:

ListIterator listIterator (): an iterator unique to the list collection.

The List collection supports the addition, deletion, modification, and query of elements.

The List collection has its own way of getting elements because the corner is marked: traversal.

For (int Xerox; x Integer

Byte-- > Byte

Short-- > Short

Long-- > Long

Char-- > Character

Double-- > Double

Float-- > Float

Boolean-- > Boolean

The previous basic data types and wrapper classes of jdk5 need to be converted to each other:

Basic-reference Integer x = new Integer (x)

Reference-basic int num = x.intValue ()

1), Integer x = 1; x = x + 1; what process did you go through? Packing à unpacking à packing

2) for optimization, the virtual machine provides a buffer pool for the wrapper class, the size of the Integer pool-128 to 127 bytes

3) string pool: Java provides a buffer pool to optimize string operations

Generics: a security mechanism that emerged after the jdk1.5 version. Presentation format:

Benefits:

1: convert the runtime problem ClassCastException problem into a compilation failure, which is reflected in the compilation time, and the programmer can solve the problem.

2: avoid the trouble of forced conversion.

As long as the classes or interfaces with them belong to classes or interfaces with type parameters, when using these classes or interfaces, you must pass a specific reference data type to the.

Generics: in fact, when applied at compile time, it is a technology for compilers, but at run time, generics no longer exist.

Why? Because of the erasure of generics: that is, after the editor checks that the types of generics are correct, there are no generics in the generated class file.

At run time, how do you know the type of element to get without having to force it?

Compensation for generics: because when storing, the type has been determined to be an element of the same type, so at run time, as long as you get the type of the element, you can convert it internally, so the user does not have to do the conversion action anymore.

When do you use generic classes?

When the reference data type of an operation in a class is uncertain, the Object used to be extended can now be represented by generics. This avoids the hassle of overturning and shifts the running problem to the compilation time.

The embodiment of generics in program definition:

/ / generic class: defines a generic type on a class.

Class Tool {

Private Q obj

Public void setObject (Q obj) {

This.obj = obj

}

Public Q getObject () {

Return obj

}

}

/ when the reference data type of a method operation is uncertain, generics can be defined on the method.

Public void method (W w) {

System.out.println ("method:" + w)

}

/ / generics on static methods: static methods cannot access generics defined on the class. If the reference data type of a static method operation is uncertain, generics must be defined on the method.

Public static void function (QT) {

System.out.println ("function:" + t)

}

/ / generic interface.

Interface Inter {

Void show (T t)

}

Class InterImpl implements Inter {

Public void show (R r) {

System.out.println ("show:" + r)

}

}

Wildcards in generics: can solve the problem that when a specific type is uncertain, this wildcard is?; when manipulating a type, only the functions in the Object class are used when you do not need to use the specific functions of the type. So it works? Wildcards to indicate unknown types.

Generic qualification:

Upper limit:? Extends E: can receive E type or subtype objects of E.

Lower limit:? Super E: you can receive an E type or a parent type object of E.

When to use the upper limit: when you add elements to the collection, you can add both E-type objects and E-subtype objects. Why? Because when fetching, the E type can receive both E class objects and E subtype objects.

When to use the lower bound: when getting an element from the collection for operation, it can be received using either the type of the current element or the parent type of the current element.

Details of generics:

1) what the generic type represents depends on the type passed in by the caller. If it is not passed, the default is the Object type.

2) when creating an object using a class with generics, the generics specified on both sides of the equation must be the same

Reason: the compiler only looks at variables when checking objects to call methods, but it has to consider the specific types of objects when calling methods while the program is running

3) both sides of the equation can use generics on either side, but not on the other side (consider backward compatibility)

ArrayList al = new ArrayList (); / / wrong

/ / just make sure that the specific types of generics on the left and right sides are the same, so that it is not easy to make mistakes.

ArrayList

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report