Home  >  Article  >  Java  >  Summary of common knowledge points in Java

Summary of common knowledge points in Java

巴扎黑
巴扎黑Original
2017-07-21 16:59:061698browse

Chapter 1

#What are the types of Java programs?

Front-end(Applet), local(Application) and back-end(Servlets) programs

Java language program It must be compiled and interpreted.

Only one public-modified class can be defined in the same java source file, and the file name of the source program must be consistent with the public-modified class name. Main method is usually placed in this class as well.

What command should be used when compiling a java source program?

javac means using a compiler to compile a source program into a bytecode program; java means using an interpreter to interpret and execute a bytecode program; appletviewer is used to execute an Applet applet.

What are the extensions of Java source programs and bytecode files?

.java .class

Master the preparation of Application program

Master the preparation of Applet program

##import

java.applet.Applet; //import# The ## statement is used to introduce the classes provided by the javaimport

java.awt.*;

public

class j1_3 extends Applet //InheritanceAppletClass{

public

void paint(Graphics g) //This method is Applet Method to implement graphics drawing in { //Applet

The program will automatically call this method to draw, paint()Parameters of the methodg is a Graphics object that represents a "brush". g.setColor(Color.

red

); //Set the brush colorg.drawString ("Hello everyone

", 40, 80); //Draw a string at the specified position, the next two parameters are the coordinate positionsg.drawLine(30, 40, 130, 40); //Draw a straight line, starting point and end point coordinates

g.drawOval(30, 40, 80, 60); / /Draw an ellipse, the four parameters are the coordinates, width and height of the upper left corner of the rectangle circumscribed by the ellipse

}

}

Java platform version: J2SE, J2ME, J2EE

The difference between print and println .

Print implements data output without line breaks.

Println implements line wrapping after data output.

Chapter 2

The definition and use of arrays.

Definition format of array:

int c[ ]=new int[5]; float f[ ][ ]=new float [5][6];

When creating a multi-dimensional array, the size of the last dimension does not need to be given.

int c[ ][ ]=new int [5][ ];

Initialization of array. There are two ways:

(1) Direct assignment, for example

int a[ ][ ] = {{1,2,3,4}, {5,6, 7,8}, {9,10,11,12}};

(2) After creating it first, assign values ​​element by element. For example

int c[ ]=new int[5]; c[0]=1; c[1]=2; ......

Basic data types.

int, char, boolean, float, etc., the length and default value (default value) occupied by each type in memory.

int 4 bytes 0

char 2 bytes 0

boolean 1 byte false

float 4 bytes 0.0F

What is automatic data type conversion? What is forced data type conversion?

Java stipulates that if a "short data type" with a small data representation range is converted into a "long data type" with a large data representation range, the system will automatically perform the conversion; otherwise, forced type conversion must be used.

The increasing order of automatic conversion of basic data types is: byte->short->char->int->long->float->double.

The forced type conversion format is: variable = (data type) expression.

double i=15; short b=(short) i;

[Note] Boolean type cannot be converted with other typologies.

Naming rules for Java language identifiers.

Four rules:

(1) Identifiers consist of English letters (a~z, A~Z), numbers, Composed of underscore _ and dollar sign $;

(2) The first letter cannot use numbers;

(3) The identifier cannot be a reserved word, such as class;

(4) Uppercase and lowercase letters represent different meanings, that is, they represent different identifiers. (Case sensitive)

What are the commonly used reserved words (keywords) in Java? What are they used for?

Abstract, static, public, final, super, const, void, int, float...

Note: Reserved words are all lowercase letters, and reserved words cannot be used as identifiers.

The scope of the variable. The difference between local variables and global variables.

Global variables, also called member variables, are members of a class. They are declared in the class and can be used by the entire class. You can also control whether other classes can use them through access modifiers.

Local variables are declared in methods, code blocks, method parameters, etc. The scope is only from the place where it is declared downward to the nearest right curly bracket. It cannot be used outside this scope. .

Hide global variables. If a global variable has the same name as a local variable, then the global variable is hidden within the scope of the local variable, that is, it does not play a role.

main() method.

The main method is the entry and exit of the program; the format of the main method is fixed and generally cannot be changed. public static void main(String args[ ])

Commonly used operators.

(1) Conditional operator: c<10 ? 1: c<25 ? 2 : 3 .

(2) Logical operator && ||&!

(3)Arithmetic operators: x+=y; x=x+y; 5%3 int s; s=s+3;

Note: The difference between arithmetic addition and string addition: String s; s=s+3;

Chapter 3

Master the use of Java flow control statements, including branch statements, loop statements and jump statements.

For example, if…then…else…statement and the use of switch…case… statement.

int c=1;

switch (c)

{

case 1: … break;

case 2: … break;

                                                                                                                                  …

#While is judged first and then executed. do...while is executed first and then judged, at least once.

The difference between break and continue .

break: Break out of the loop. End the cycle.

continue: Terminate the current cycle and continue the next cycle.

The use of three comment statements.

//: single-line comment

/*&*/: multi-line comment

/**&*/: document comment

Chapter 4

How to create an object of a class and what reserved words should be used?

After defining the java class, you can use the "new+constructor" to create an object of the class.

How to recycle an object that is no longer used? What reserved words are used?

finalize reserved word

Java's memory recycling mechanism. Generally, the system's memory recycling program is responsible for releasing useless memory, and programmers do not need to be responsible for recycling memory.

Java uses the package statement to create a package.

Users can define their own packages, which are custom packages, or they can use the packages provided by the Java system, which are system packages.

Static variables and methods.

static is a static modifier, used to indicate that a variable or method is static. A static variable or method belongs to the class and does not belong to any object. It can be accessed through "class name. variable name" and "object name. variable name". Non-static variables and methods belong to specific objects and can only be accessed through "object name.variable name". Static variables, also called class variables, are a public memory unit.

Static: static

Usage: It is a modifier used to modify members (member variables, member functions)

When a member is statically modified, there is one more calling method. In addition to being called by the object,

can also be called directly by the class name. Class name.Static member.

static features:

1. Loaded as the class is loaded.

In other words: static will disappear with the disappearance of the class, indicating that its life cycle is the longest.

2. Prioritize the existence of objects

Let’s be clear: static exists first, and objects exist later.

3. Shared by all objects.

4. It can be called directly by the class name.

The difference between instance variables and class variables:

1. Storage location.

Class variables exist in the method area as the class is loaded.

Instance variables exist in heap memory as the object is created.

2. Life cycle.

Class variables have the longest life cycle and disappear when the class disappears.

The instance variable life cycle disappears when the object disappears.

Notes on static use:

1. Static methods can only access static members.

Non-static methods can access both static and non-static methods.

2. This and super keywords cannot be defined in static methods.

Because static precedes the existence of objects, this cannot appear in static methods.

3. The main function is static.

Static has advantages and disadvantages

Advantages: Store the shared data of objects in a separate space to save space. There is no need to store a copy in each object.

can be called directly by the class name.

Disadvantages: The life cycle is too long.

There are limitations in access (static is good, but only static can be accessed).

The main way to initialize member variables of a class. There are mainly 5 ways.

(1), is automatically initialized. If it is a basic member variable, it will be assigned the value 0, and if it is a basic member variable, it will be assigned the value null. booleanAssignmentfalse.

(2) , Direct assignment means assigning the value to the class member variable where it is defined.

(3) , provide the initial value by calling the method. If the method takes parameters, the parameters must be previously initialized.

(4), constructor initialization. Construct the Java object through the constructor with parameters, make the Java object by inputting different parameters with different initial values. But to be clear: there is no way to prevent automatic initialization from happening, it will happen before the constructor is called.

(5), Initialization of static data. Static data belongs to classes and only occupies one storage area. Static initialization is only done when necessary. Static objects are initialized when they are created or accessed for the first time. After that, static objects are not initialized again.

Chapter 5

The three major characteristics of object-oriented technology.

Encapsulation, inheritance, polymorphism.

The relationship between subclass objects and parent class objects.

Objects of a subclass can be directly assigned to objects of the parent class, but objects of the parent class cannot be directly assigned to objects of the subclass, and type conversion must be performed.

Father f=new Father(); Son s=new Son();

f=s; s=(Son)f;

The concept of inheritance. The difference between single inheritance and multiple inheritance.

Inheritance refers to the process by which one class obtains properties and methods from another class. Inherit using the extends keyword. JavaDoes not support multiple inheritance. In order to realize the function of multiple inheritance, Java adopts interface technology, and the interface can support multiple inheritance. The variables and methods in the interface are all public .

What is the Object class?

Object is the parent class of all classes. It has many methods used by class objects, such as the more commonly used toString , equals, when you create a new xx class, you can override ObjectMethods that have been defined can also be directly called methods in Object. If you write an encapsulated method and are not sure what type of value is passed in, you can use ObjectAs a general class.

Construction method of Java language. What is a constructor method? What are the characteristics of construction methods? What is the default constructor ?

The constructor method is the method with the same name as the class. Its function is to be used for initialization.

1.The constructor must be the same as the class Same name (if there are multiple classes in a source file, the constructor must have the same name as the public class)

2.Each class can have more than one constructor

3.Constructors can have 0, 1 or 1 More than #parameters

4.The constructor has no return value

5.The constructor is always accompanied by new Call the operation together

If you do not specify the form of any constructor, the program will get a constructor without any parameters for you function, then you can only use methods without parameters when generating objects of the class.

The problem of passing parameters when calling a function (that is, is it passed by value or address delivery).

If the type of the parameter is a basic type, then it is usually passed by value, that is, the value of the actual parameter is passed to the formal parameter; if the parameter is an object of a class, then it is usually passed by address, that is, the actual parameter is passed. The address of the parameter is passed to the formal parameter.

Covering and overloading.

Overloading means there are multiple methods with the same name in the same class, but the number or type of method parameters are different .

Override means that there are multiple methods with the same name between the parent class and the subclass, and the number and type of parameters are the same. Only the method body is different.

A java program can have multiple classes, but there can only be one main class (that is, the public class).

There is generally one main method in the main class, main() method.

Note the format of the main() method.

Modifier:

(1) Access permission modifier.

(2) abstract modifier.

The class modified by abstract is called an abstract class, and the method modified by abstract is called an abstract method. Abstract methods can only be located in abstract classes, but abstract classes can also have non-abstract methods.

(3) final modifier. The class modified by final is called the final class, and the final class cannot be inherited. The method modified by final is called the final method, and the final method cannot be overridden.

#Definition of interface(interface) and implementation(implements).

Interface is a special class composed of constants and abstract methods. The variables and methods in the interface are public.

Note The differences between public, protected, default (without modifiers) and private.

public protected default private:

In the same class: ok ok ok ok

The same package In: ok ok ok no

Subcategory: ok ok no no

In different packages: ok no no no

Chapter 6

String class and StringBuffer class.

Pay attention to the use of common methods of the String class: length(), charAt(), toUpperCase(), toLowerCase(), valueOf() methods;

String class is suitable for describing string things.

Then he provides multiple methods to operate on strings.

What are the common operations?

1. Get

1.1 The number of characters in the string, which is the length of the string.

int length(): Get the length

1.2 Get a character at the position based on the position.

char charAt(int index)

1.3 Get the position of the character in the string based on the character.

int indexOf(int ch): Returns the position of the first occurrence of ch in the string.

int indexOf(int ch,int fromIndex): Starting from the position specified by fromIndex, get the position where ch first appears.

1.4 Get the position of the string in the string based on the string.

int indexOf(String str): Returns the position where str first appears in the string.

int indexOf(String str,int fromIndex): Starting from the position specified by fromIndex, get the position where str first appears.

2. Determine whether

2.1 the string contains a certain substring.

boolean contains(str):

Special features: indexOf(str): You can index the position where str first appears. If -1 is returned, it means The str does not exist in the string. Therefore, it can also be used to determine whether a specified item is included.

2.2 Whether there is content in the string.

boolean isEmpty(): The principle is to determine whether the length is 0.

2.3 Whether the string begins at the specified position.

boolean startsWith(str):

2.4 Whether the string ends at the specified position.

boolean endsWith(str):

2.5 Determine whether the string contents are the same. Overriding the equals method in the Object class.

boolean equals(str):

2.6 Determine whether the contents are the same and ignore case.

boolean equalsIgnoreCase():

3. Conversion

3.1 Convert character array to string

Constructor:

String(char[])

String(char[],offset,count): Convert the count characters starting from the offset position in the character array into a string.

Static method:

static String copyValueOf(char[]);

static String copyValueOf(char[] data,int offset,int count )

static String valueOf(char[]);

3.2 Convert the string into a character array

char[] toCharArray();

3.3 Convert byte array to string

String(byte[]);

String(byte[],offset,count): Convert a portion of a byte array to a string.

3.4 Convert a string into a byte array

byte[] getBytes();

3.5 Convert a basic data type into a string

String valueOf(int)

String valueOf(double)

Special: Strings and character arrays can specify encoding tables during the conversion process;

4. Replacement

String replace(oldchar,newchar) ;

5. Cutting

String split(regex);

6. Substring

String substring(begin);

String substring(begin,end);

7. Convert, remove spaces, compare u

7.1 Convert characters Convert a string to uppercase or lowercase.

String toUpperCase(): Convert to uppercase

String toLowerCase(): Convert to lowercase

7.2 Remove multiple spaces at both ends of the string.

String trim();

7.3 Compare two strings in natural order.

int comparaTo(String);

StringBufferString buffer is a container.

Features:

1. The length is variable.

2. You can directly operate multiple data types.

3. It will eventually be turned into a string through the toString() method.

StringBuffer can add or delete string content.

CURD C create U update R read D delete

1. Storage

StringBuffer append(): will specify the data Added as a parameter to the end of existing data.

StringBuffer insert(index,data): Data can be inserted into the specified index position.

2. Delete

StringBuffer delete(start,end): Delete the data at the specified position in the buffer, including start but not end.

StringBuffer deleteCahrAt(index): Delete the character at the specified position.

3. Get

char charAt(int index)

int indexOf(String str)

int lastIndexOf(String str )

int length()

String substring(int start,int end)

4. Modify

StringBuffer replace( int start, int end, String str): Replace the string at a certain position with a string.

void setCharAt(int index,char ch): Replace the character at a certain position with a character.

5. Reverse

StringBuffer reverse():

6.

Reverse the buffer The specified data is stored in the specified character array.

void getChars(int srcbegin,int srcend,char[] dst,int dstBegin)

srcbegin: The starting position of interception in the string

srcend: The end of the string Position

dst: Array

dstBegin: The position where the array starts to store data

Use double The string enclosed in quotes is called a string constant, which is an anonymous String object.

There is only one same string constant in the memory. For example, there is only one constant "a" in the memory.

String connection operator: +, for example: 2+“,”+3

String comparison operation :

equals() method: Used to compare whether the values ​​contained in two string objects are equal.

== Operator: Used to compare whether the addresses of two string objects in memory are equal.

The difference between equals() method and equalsIgnoreCase() method.

equals() method: used to compare whether the values ​​contained in two string objects are equal.

equalsIgnoreCase() method: Case-insensitively compares whether the values ​​contained in two string objects are equal.

##Methods in Math class: random(), sin(x) cos(x)

ceil(x):

Find the smallest integer that is not less than the given real number.

Constants in the Math class: PI, E

Packaging class Integer class: parseInt(), toString()

Double class: parseDouble() Float class…….

Chapter 7

#Java exception handling mechanism.

The Throwable class is the superclass for all errors or exceptions in the Java language (that's what is throwable). It has two subclasses: Error and Exception.

Error: Used to indicate serious problems that reasonable applications should not attempt to catch. This situation is a big problem, too big for you to deal with, so just let it go and don't worry about it.

Exception: It indicates a condition that a reasonable application would want to catch. Exception is divided into two categories: one is CheckedException and the other is UncheckedException. The main difference between these two Exceptions is that CheckedException needs to be explicitly captured using try...catch..., while UncheckedException does not need to be captured. Usually UncheckedException is also called RuntimeException.

Use checked exceptions (CheckedException) for recoverable conditions, and use runtime exceptions (RuntimeException) for program errors (the implication is that they are unrecoverable and a big mistake has been made).

Our common RuntimeExcepitons include IllegalArgumentException, IllegalStateException, NullPointerException, IndexOutOfBoundsException and so on. There are too many CheckedExceptions to mention. During the process of writing the program, the exceptions we catch by try...catch... are all CheckedExceptions. IOException and its subclasses in the io package, these are CheckedException.

How are exceptions thrown, caught and handled?

throws/throw Keyword:

If a method does not catch a checked exception, then the method must use the throws key words to declare. The throws keyword is placed at the end of the method signature.

You can also use the throw keyword to throw an exception, whether it is newly instantiated or just caught.

A method can be declared to throw multiple exceptions, separated by commas.

Catch exceptions

Use try and catch keywords to catch exceptions. Try/catch code blocks are placed where exceptions may occur.

The code in the try/catch code block is called protection code. The syntax for using try/catch is as follows:

try

{

// Program Code

}catch(ExceptionName e1)

{

//Catch block

}

The Catch statement contains the exception type to be caught statement of. When an exception occurs in the protected code block, the catch block following the try is checked.

If the exception that occurs is contained in a catch block, the exception will be passed to the catch block, which is the same as passing a parameter to a method.

finally keyword

The finally keyword is used to create a code block that is executed after the try code block.

No matter whether an exception occurs or not, the code in the finally code block will always be executed.

In the finally code block, you can run cleanup type and other finishing statements.

The finally code block appears at the end of the catch code block

catch cannot exist independently of try.

It is not mandatory to add a finally block after try/catch.

There cannot be neither a catch block nor a finally block after the try code.

No code can be added between try, catch, and finally blocks.

The Java exception handling module can capture multiple exceptions at the same time. If there is an inheritance relationship between these exceptions, the exception of the subclass must be captured first. Then catch the exception of the parent class.

Keywords involved in Java exception handling:

try, throw, catch, throws, finally

Chapter 10

Design and development of Applet applet.

import java.applet.*

Note The difference between Applet and Application program.

The life cycle of Applet and the role of each method in the life cycle.

In the life cycle of Java Applet, there are four states (initial state, running state, stop state and death state) and four methods: init(), start (), stop() and destroy().

1. init()

When a Java Applet is created and loaded for the first time using a browser that supports Java, the init() method will be executed. In the Java Applet life cycle, this method is only executed once, so you can use this to perform some initialization operations that only need to be executed once in the init() method, such as initializing variables.

2. start()

After calling the init() method, the system will automatically call the start() method. When the user leaves the homepage containing the Applet and then returns, or when the browser returns from the icon state to a window, the system will automatically execute the start() method again.

is different from the init() method. The start() method is called multiple times during the life cycle of the Applet. This method is the main body of the Applet. In the start() method, you can perform some tasks, or start related threads to perform tasks, such as looping songs, etc.

3. stop()

corresponds to the star() method. When the user leaves the page where the Applet is located or the browser changes to an icon, the system will call stop () method, so this method can also be called multiple times.

The stop() method plays such a role: when the user is not paying much attention to the Applet at the current moment, it stops some resource-consuming work, which can improve the running speed of the system, and the system will automatically call This method does not require human intervention. If the Applet you write does not involve multimedia such as animation, you generally do not need to rewrite this method.

4. destroy()

When the user closes the browser, the system will call the destroy() method. You should pay attention to the stop() method and destroy() method. difference.

Drawing methods of graphics in Applet:

drawString, drawChars, drawBytes, drawLine, drawRect, fillRect, drawRoundRect, drawOval, drawArc, drawPolygon wait.

Related methods for graphics drawing:drawRect(100,100,150,150); setColor(Color.black); drawLine(10,10,10, 50);

Chapter 11

Java graphical user interface development.

What are the commonly used containers?

Frame, Panel, Applet, Dialog, Window.

#What are the commonly used layout types?

BorderLayout (border layout), FlowLayout (flow layout), GridLayout (grid layout), CardLayout (card layout), GridBagLayout (grid bag layout), among which Frame is missing The provincial layout type is BorderLayout; the default layout type of Panel and Applet is FlowLayout.

Use of various components

For example, text input components (TextField and TextArea), labels (Label) , button (Button), list (List), drop-down list (Choice), etc.

Set the size and background color of Frame, Panel and other containers.

setBounds, setSize and setBackground.

Frame has title and zoom function;

Panel does not have title and zoom function.

The Frame object is invisible by default, and its visibility needs to be set to true through the setVisible method.

In addition, The default size of the Frame object is 0×0 pixels.

Java graphical user interface development requires the import package: java.awt, and event processing in the graphical user interface requires the import package: java.awt.event

# Implementation steps of Java event processing (three steps).

In Java graphical interface development, in order for the graphical interface to receive user operations, it is necessary to add event processing mechanisms to each component. During event processing, three types of objects are involved. The first is the Event event, which realizes the user's operation of the graphical interface component and appears in the form of a class. For example, the class corresponding to the window operation is WindowEvent, and the class corresponding to the keyboard operation is KeyEvent; the second is the event source, that is, the place where the event occurs, such as a Buttons, radio buttons or check boxes, text boxes, etc.; the third is the event handler, which receives the events that occur and processes them, also called a listener.

1. Create a component (control) that accepts a response

2. Implement the relevant event listening interface

3. Register the action listener of the event source

4. Event processing when an event is triggered

Question types: fill-in-the-blank questions, multiple-choice questions, short-answer questions, program reading questions, program fill-in-the-blank questions, and programming questions.

Review method: Read more ppt courseware and teaching materials in class.

In addition, re-do the experimental questions that have been done in the experimental class. The programming questions may be done in previous experiments.

finally: Finally, as a modifier.

1. You can modify classes, functions, and variables.

2. Classes modified by finally cannot be inherited. In order to avoid being overwritten by subclasses after being inherited.

3. Functions modified by finally cannot be overwritten.

4. The variable modified by finally is a constant and can only be assigned once. You can modify both member variables and local variables.

When describing things, the values ​​that appear in some data are fixed. Then in order to enhance readability, these values ​​​​are given names to facilitate reading. This value does not need to be changed, so add finally modification.

Package name: All letters are lowercase.

Class name interface name: When it consists of multiple words, the first letters of all words must be capitalized.

Variable names and function names: When composed of multiple words, the first letter of the first word is lowercase, and the first letter of other words is uppercase.

Constant name: All letters are in capital letters. When it consists of multiple words, underscores connect the words.

Classification of constants in Java:

1. Integer constants, all integers.

2. Decimal constants, all decimals.

3. Boolean constant, true, false.

4. Character constant, identify a numeric character or symbol with ‘’.

5. String constant, mark one or more characters with "".

6. Null constants, only null

Escape characters: Use \ to change the meaning of the following letters or symbols.

\n: Line break

\b: Backspace, equivalent to the backspace key

\r: Press the Enter key, Windows system, the Enter key consists of two Characters to represent \r\n

\t: tab character, equivalent to the tab key

In future development, we will actually find an object to use. If there is no object, create one object.

Category: Description of things in real life.

Object: This type of thing actually exists as an individual.

To access between packages, the members of the package and class being accessed need to be public modified.

Subclasses in different packages can also directly access members modified by protected in the parent class.

There are two types of permissions that can be used between packages: public protected

In order to simplify the writing of class names, use a keyword: import

import imports the classes in the package.

Suggestion: Do not write wildcards *, import whichever class in the package you need to use.

It is recommended not to repeat the package name.

can be defined with url, which is unique.

The above is the detailed content of Summary of common knowledge points in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn