Summary of basic Java Knowledge (complete)

Source: Internet
Author: User
Tags comparable event listener logical operators throw exception variable scope java throws

1.JAVA Introduction

1.1java Architecture: J2SE,JAVAWEB,J2EE

1.2java Features: Platform independent (virtual machine), garbage collection (makes Java more stable)

1.3 JDK and Jre,jdk:java development environment, Jre:java operating environment

1.4 First Java program: Helloworld,java's entry is main (public static void main (string[] args))

1.5java program Development Steps:. Java compilation (JAVAC) into a. Class run (Java). class file

2. Basic data types

2.1 Marker: The place where you can take a name is called a marker

* Marker Rules: 1, can only be letters, numbers, underscores, $; cannot start with a number; You cannot use keywords as markers

2.2 Keywords: keywords are all lowercase

2.3 Constants: such as 123, "Hello"

* You can also use final to define constants (refer to Math.PI), such as public static final int slow_speed=1;

2.4 Variables: The essence of a variable is a small area in memory that holds the data in this area

* Variable declaration: Type variable Name

* Variables must first be declared, then assigned, and then used

* Note variables that distinguish between basic data types and those that reference data types

* variable scope, local variable and member variable: the variable is defined in the curly brace, where it is valid, the curly brace is invalid

2.5 Basic data types: Java data types fall into two main categories: basic data types, reference data types

* Basic data types are divided into 4 categories 8: boolean,char,byte,short,int,long,float,double

*boolean type only True,false

*char is a Unicode encoding

*float,double is accurate (not absolutely accurate)

2.6 Conversions between basic data types

*123 literal constant is int, 12.3 literal constant is double type, 8888888888888 this literal constant has a problem (because it has exceeded int's range, changed to 8888888888888L)

*boolean incompatible with other types

When the *byte,short,char between each other, it is converted to int before the operation

* Small-capacity data types can be automatically converted to large-capacity data types: byte,short,char-->int-->long-->float-->double

* Bulk conversion to small-capacity data type, to be cast

* When computing multiple data types, first convert to the largest data type and then perform the operation, the type of the whole expression is the most capacity data type

* Must master the exercises on PPT

3. Operators and Process Control 3.1 operators: arithmetic, relationship, assignment, logic (note), bitwise operator

* Self-added minus + +,--, note the order

* The result of the relational operator is a Boolean type

* Logical operators note short-circuiting with &&, short-circuit or | |

* Ternary operator (logical expression)? expression one: Expression two

3.2 Flow Control statements: Conditions (If,switch), loops (For,while,do while), break and continue

Rules for 3.3 switch:

*switch can only detect: The value of the Byte,short,char,int type (only these 4 can be followed by case)

*switch be careful of case penetration (the code will run until a break stop is encountered, it is recommended to write a break for each scenario)

*default: If no matching case is found, execute the default

3.4 For,while,do While figuring out the execution flow of the code (there is a diagram on the PPT, you must remember)

3.5 break,continue

* Can be used in the loop, break can also be used in switch

*break a block of code before jumping out of a single (end loop)

*continue: Skip this round cycle and continue to the next round (the loop will continue, just skip this time)

3.6 Process Control Code writing: You can flexibly combine these process control code, note that you must write {}

4. Object-oriented basic syntax

Need to master: The difference between a class and an object, how to define a class, how to instantiate an object

4.1 Defining a Class

* Use class keyword to define classes, note class name capitalization

* Member properties: The member property is not assigned a value will have a default value (default value rule reference ppt)

* Member method

* Construction Method: There is no return value, the name is the same as the class name, the constructor method is intended to initialize the object (Initialize the object's property values)

4.2 Instantiation object: Student s = new Student ();

* Instantiate an object using the new + construct method

*new the object space in the heap and assigns the default value to the property

* Next Call the constructor method, execute the code in the constructor method

* Last return reference to object

4.3 Distinguishing between reference types and basic data types

* Variables of reference type have two areas in memory, one is the reference itself and the other is the object to which the reference is directed

* The basic data type has only one space in memory: The value is stored inside

4.4 How to manipulate objects: using the. operator

* Use object name. Property Action Object properties (such as: Stu.age = 18;)

* Use object name. method to invoke the object's method (for example: Stu.study ());

*this: Each object has a this,this that is a reference to itself, representing itself

4.5. Must be able to write Point3D code independently (topic on PPT)

5. Access control, method definition with call, overload, method override 5.1 Access control 5.1.1 Package use

* Use the Package Definition pack: Packages can only be placed in the first line of code

*import: Guide package, you can go into the package under all import java.io.*; Import Java.io.Reader can be imported into a specific class;

* Function of the package: 1, category; 2, hidden (role of encapsulation), 3, easy to manage

*java itself provides some packages: Java.lang (Core class, this package needs to be introduced), Java.util (collection framework and other common classes), java.io (input and output), java.awt,javax.swing (graphics)

5.1.2 Inheritance (simple concept): Using the extends keyword to represent inheritance

* Subclass inherits all properties of parent class

* Subclass inherits all methods except private (not the same as the default method) for the parent class

* Subclass Object has a super reference that represents a reference to a parent class that can use super to explicitly call a method or property of a parent class

5.1.34 access levels, from large to small: public,protected, default, private

* Note that the access level is for the class, not for the object!!!!!!!

* Note that access modifiers for classes can only use public or default

* After the access control: the properties of the class are written private, the property is assigned by the Set/get method, the value

5.2 Overloading and rewriting

1. Determine if it is overloaded, or whether it is an override, and is not constrained by overriding overloaded rules if it is not overridden or overloaded

5.2.1 Overloading: A class in which there are methods with the same method name and different parameters, called overloading

* Cannot change only the return value: cannot be overloaded based on the return of the method

5.2.2 rewrite: In inheritance, the subclass writes the method of the parent class again: The overridden method has the same method signature as the overridden method (return value type, method name, number of parameter columns)

*. The overridden method can change the access level of the overridden method, noting that it can only be equal or enlarged

*. Overridden methods cannot throw more exceptions than overridden methods, note that only the range of exceptions can be narrowed

*. If the method being overridden is specific, the override cannot be changed to abstract

5.3 Classes and the life cycle of objects

5.3.1 class and object initialization process:

* Static properties are initialized first, and only once initialized

* Declare the static property first, assign the default value, and then execute the code from the top down to the static code block or static assignment

* Each object is created, the member property is instantiated first: the member property declaration is given, the default value is assigned, and then the. Execute Assignment statement

* The constructor method is called after the member property is initialized

5.3.2 Garbage collection mechanism

*java virtual use of garbage collection mechanism for garbage collection

* Garbage collection itself is a thread (garbage collection is generally done when memory is not available)

* Garbage collection cannot be called through the program, only the virtual machine can be recommended for garbage collection via System.GC ()

* When garbage collection is performed, the object's Finalize method is called

5.4 Singleton mode: A class can have only one instance (one of the design patterns)

* The construction method must be private

* Provides a static method to get the object

* Provides a static property, which is an object of the class

6. Inheritance, abstract class, interface 6.1 inheritance:

6.1.1 inherited syntax: Using the extends keyword to represent inheritance

* Subclass inherits all properties of parent class

* Private methods cannot be inherited

The *super keyword represents a reference to the parent class, and you can use Super to invoke the parent class's method or property

Construction methods in 6.2.2 Inheritance: Understanding the following knowledge points and the execution of code when instantiating an object

* The constructor of a subclass must call its base class construction method

* Subclasses can use Super (arg_list) to call the constructor of a base class in their own construction process

* If you call super, you must write the first line in the subclass construction method

* Additional construction methods for this class can be called using this (argument_list)

* If the construction method of the calling base class is not shown in the constructor method of the subclass, the system defaults to calling the base class parameterless constructor method

* If there is no explicit call to the base class construction method in the subclass constructor method, there is no parameterless construction method in the base class, and the compilation error

Transformation of 6.3.3 Objects

* A reference type variable of a base class can point to an object of its child class

* A reference to a base class does not have access to new members of its child class object

* You can use the INSTANCEOF keyword to determine whether the object that a reference type variable points to is the type being developed

* Subclasses of objects can be used as objects of the base class to use as an upward transformation, and vice versa, as a downward transformation

* Subclasses can be used as parent classes without displaying transformations

* Parent class reference is converted to subclass reference to be cast

* Note: Incompatible types cannot be converted to each other (only classes that have a direct or indirect parent-child relationship are compatible types) or compile with an error

* Note: The conversion between compatible types depends on the actual type of the object, so it is best to use instanceof to determine if a type is converted to avoid reporting an error.

6.4.4 polymorphism: Also known as runtime binding: Refers to the parent class reference to the child class object, through the parent class reference calls the quilt class overrides the method, this time executes is the subclass method

* Summarize polymorphism in one sentence: What type of method the object is actually called

* Conditions for polymorphic establishment: 1, to have inheritance. 2, to have a rewrite. 3, a parent class reference must be directed to the subclass object.

6.2 Abstract Classes: Classes that are decorated with abstract are called abstract classes (abstract intent is not specific)

1. Abstract methods cannot have method bodies

2. Abstract classes cannot be instantiated.

3. Classes containing abstract methods must be declared as abstract classes,

4. Subclasses inherit abstract classes and must be overridden by the parent class's abstract methods, otherwise they must also be declared abstract classes

5. Methods and properties in abstract classes are not constrained by other rules, and abstract classes can have non-abstract methods and properties in abstract classes.

6.3 Static: Still keyword

6.3.1static Properties: In a class, the member variable with static declaration is called a static variable, and he is the common variable for the class, initialized at first use, and for all objects of that class, the static member variable has only one copy

6.3.2 static method: The method declared with static is a static method, and when the method is called, no reference to the object is passed to it, so the static method cannot access non-static members.

* Non-static members cannot be accessed in static methods

* Static member method does not have this reference

* Static members can be accessed through the class name (no instantiation required) or object reference

6.4 Final Keyword:

Final means the ultimate meaning

The value of the *final variable cannot be changed

Member variables for *final

Local Variables for *final (formal parameters)

The *final method cannot be rewritten.

*final classes can not be inherited

6.5 Interface: interface

1. Using interface to define an interface, use implements to implement an interface

2. The properties in an interface can only be public static final type (static constant)

3. Methods in the interface can only be public abstract types

4. A class can implement multiple interfaces, but can inherit only one class

5. Interfaces can also inherit interfaces

7. Exception Handling

Exception handling mechanism for Java

Exception keyword exception

Try,catch,finally,throw,throws keywords

7.1 What is an exception and why introduce an exception

*java program run error, Java throws an exception, the program immediately terminates (also can say the program crashes)

*java to encapsulate the error message in the exception object

* Learn to view exception information: Exception name, exception information, program throw exception location

*java introduces exception handling mechanism to prevent program errors from crashing

Classification of anomalies of the 7.2java

The thrown error of *java is represented by the exception class, where Java has an exception system (with many exception classes and relationships with each other)

All the anomalies inside the *java are throwable subclasses.

*java Virtual machine Exceptions are subclasses of error and are generally not processed (because they cannot be processed)

* There are two types of exception,exception except error: RuntimeException (runtime exception), checked for exceptions (except RuntimeException are checked for exceptions)

*runtimeexception (Run-time exception, can not be caught or declared thrown, compilation will not error, usually caused by improper control), can check the exception (must be caught or declared thrown, such exceptions often need to detect and processing, usually caused by the use of resources)

* Several common exceptions: NullPointerException (null pointer), Indexoutofboundsexception (index out of Bounds), SQLException (Database exception), IOException (file exception)

7.3 How exceptions are handled

* Processed using try,catch,finally

* Do not process, use Throws,throw to others to deal with

The process of running a program in 7.4try,catch,finally

* Try to execute the statement inside the try

* Up to one catch block in one run, if no exception is thrown, the catch block does not execute

*finally always executes, whether or not an exception is thrown

* If there is a return statement inside the try block, finally will also execute

7.5 Distinguishing between runtimeexception and being checked for anomalies

*runtimeexception does not need to be caught or declared thrown (but will not be wrong if you catch or declare a throw)

* Checked exception must be caught or declared thrown

8. Arrays

An array is a reference type and has a length property.

Declaration, creation, assignment

* Array declaration to specify the type of array elements, the dimensions of the array, do not need to specify the length of the array, such as: int[] A; (A is a reference)

* The creation of the array must be the new keyword, and must give the length of the arrays; new Int[5]

* If the type of the array is an array of reference types, the array holds references, not the object itself

New int[] {1,3,4,5}

{1,4,5,6}

Common operations classes for arrays

Arrays provides a common way to manipulate arrays (these methods are static)

* Sorted by: Sort

* Returns the string representation of an array: ToString

Two-dimensional arrays

* Memory analysis of two-dimensional arrays

* Copy of array using System.arraycopy method

9. Common Classes

Common classes: lang package does not need to import, other packages are required

1.Object: Root class for all classes

* ID of the object: Hashcode ()

* Object information: toString (), by default returns the object type @ address information

* object is the same: equals, by default, compares equality by address. = = Compares the address of an object, while equals semantically provides an equal meaning

* Override Equals and ToString method, refer to Money class

2.String: Immutable string, class, Inherit object

*string overrides ToString, which returns the class tolerance of the string. Overridden by equals to compare the contents of a string

* String constant "1234" with new string ("1234"). Constants have only one, and new String () will be a fresh pair of images each time

* String invariant, once the string is created, the content cannot be changed

* Common operations for strings

* Length of string:

* Search for a string: IndexOf ()

* String strings: substring (3,8)

* The character obtained at the specified position: charAt (8);

* Determine what the string begins with (end): StartsWith (), Endwith ()

* Change Case of String, toUpperCase (), toLowerCase ()

* Remove spaces on both sides of the string: trim ()

* Replace some content inside the string: replace ("")

* Split string:

StringBuffer: String buffering, variable string, providing a way to change the string (other methods are basically similar to string)

* Get string from StringBuffer

* Additional append ("abc");

* Inserts insert (3, "inserted string") in the middle of the string

* Delete string Delete (3,6);//do not include 6

Wrapper class: Provides conversions to and from strings. Integer is a wrapper class of type int

Math class: Provides common mathematical operations, note: The methods inside are static

Random: The class, which generates stochastic numbers, and Math.random () can also produce random numbers between 0~1

Date: Date,simpledateformat (date formatting), calendar calendars

Get console input:

*scanner sc = new Scanner (system.in);

*string str = Sc.next ();

10. Collection Framework

Set frame: Conceptually divided into: set (mathematical set), list, Map (dictionary)

1.Collection interface, iterator interface

*set,list inherits collection, uses iterator to iterate (reference testcollection)

2.Set: Elements cannot be duplicated, no order

*hashset: Judging whether objects are duplicated according to Hashcode (overriding Equals and Hashcode)

*treeset: The elements inside are arranged sequentially (elements must implement comparable interfaces)

2.List: Elements can be repeated, in order, index position, on the basis of collection provides a way to operate according to the index location

*arraylist: Using arrays internally to implement list

*linkedlist: Provides a way to manipulate the first and last elements based on the list: Into GetLast (), AddFirst (Object o)

* Array, Aarrylist,linkelist is different

3.map: Set of key-value pairs, key cannot be duplicated, value can be repeated

* Two times put the same key, the latter one will overwrite the previous one

* The way to traverse map: First get keyset, or entryset, and then use Set (Iterator) to traverse

4. Generic:list<integer> List = new arraylist<integer>

* The deposited element can only be a specified type, such as:<integer>

* Removed to not require a cast, automatically a specified type, such as:<integer>

5.List common operation class collections, different from collection, provides a sort of list, random arrangement, reverse method

*arrays used in arrays, providing common operations for arrays, similar to collections,

6.Comparable interface

*compareto ()

* If you need to sort (collections.sort ()), or put in a sorted set (TREESET,TREEMAP), you must implement the comparable interface

One. JDBC

Jdbc:java a set of APIs for manipulating databases (note impersonation)

1.JDBC Drive Mode:

*JDBC-ODBC Bridge driver (data source must be established first, performance is low, not recommended)

*JDBC Pure Drive: The JDBC jar package must be added to the build path, typically using the JDBC pure driver

2.JDBC operation of the database process

* Load driver with Class.forName ("")

* Use Drivermanager.getconnection () to get connection (connection) \

* Create statement with connction (statement with Statement,preparedstatement)

* EXECUTE statement

* Close Connection

3. Performing database operations is divided into two types of JDBC

* Change Database: Executeupdate (), returns the number of rows affected by the database. including Insert,update,delete

* Execute Query: executeQuery (), return result set resultset. Including select

Common operations for 4.ResultSet:

*resultset represents the query-out result set, and contains the concept of a cursor

*resultset.getmetadata can get meta information for each column: column name, column type, column length

*rs.next () causes the cursor to move down one line and returns whether there is a Boolean value for the next line

*rs.getxxx can get the information inside the row that the cursor is currently pointing to

* In the resultset, the data is not allowed to go backwards.

* Common way to traverse result sets: while (Rs.next ()) {rs.getstring (1)}

5.PreparedStatement

* You can set values for placeholders in SQL statements setxxx

* Do not need to pass SQL statements when executing executeupdate (), because SQL statements are specified when creating PreparedStatement

* Note PreparedStatement and statement

6. How transactions are used

* Disable Auto-commit: Set Connection.setautocommit (false);

* In the last manual submission: Connection.commit ();

* Can catch exception in data operation, once catch exception, use Connection.rollback ();

7. Batch SQL

* For a statement to be, you can use Addbatch () to add multiple SQL statements

* You can use ExecuteBatch to execute all joined SQL statements at once

8. We recommend that you use DAO in this way to access the database

* Entity class

* DAO of entity class

9. We recommend that you use Dbutil management to get connected and close the connection

12. Graphics-layout, common swing components

Graphical user interface (swing common components, Layout manager, event model, drawing)

1.AWT and Swing

*AWT is a heavyweight component, swing is a lightweight component, and swing is developed from the AWT Foundation.

*swing still uses AWT's layout and event model

* Components: Each interface element is called a component, such as a button, a text box

* Container concept: Components that can accommodate other elements, add components to the container via add (), and each container can set its own layout manager (layouts)

2. Common components

* Frame: JFrame (with a default content panel), generally, all other components are placed on the default panel of the JFrame. Get the default content panel via Jframe.getcontentpane ()

* Panel: JPanel

* Tags: JLabel

* Text input box: JTextField

* Text field (multiple lines): JTextArea

* Radio button: Jradiobutton

* check box: Jcheckbox

* Drop-down list: JComboBox

* Button: JButton

3. Layout Manager (Flow layout flowlayout, Border layout borderlayout, Grid layout GridLayout)

* Use the setlayout (New FlowLayout ()) method to set the container's layout manager

*flowlayout: When you drag the interface, the size of the element does not change, only the position of the element, can refer to the settlement alignment, left, right alignment, etc.

*borderlayout: The interface is divided into five parts of east.: The element size changes, but the relative position is unchanged. In addition to the middle area (auto-fill), the area does not add components, the default size is 0. If you add multiple components to a region, only the last added component is displayed.

*gridlayout: The size of each grid is equal, the position does not change, the size varies with the size of the container

13. Graphics-Event handling, drawing

Graphical user interface

1. Inner class: Defining a class inside a class is called an inner class.

* Inner classes can access all member variables and member methods of the outer class

* If you want to instantiate an inner class externally, you must use the full name: Outer class. Inner class

2. Event Model:

The *java event takes the delegate model (the authorization model), which means that the event source itself does not handle the event and is given to the event listener to handle it, so the event listener needs to be bound to the event source

* Event source, event, event listener. There are many kinds of events, different events using different listeners to handle

* After the event is triggered, the system automatically invokes the event-handling method (no need to call the event-handling method manually) and passes the event information as a method parameter

* Event Writing steps: 1. Implement listener interface (completion of event handling method); 2. Instantiate and bind to event source

3. How the event is implemented

* External class

* Inner class

14. Multithreading

Thread:

1. Threading Concepts

* Different execution paths within the program, each execution path is called a thread

* For a single CPU, there will only be one thread running at a specific moment, but the CPU is very fast and seemingly a lot of threads executing in parallel

2.java thread creation and start-up

* Two ways to implement threading: Inherit thread, implement Runnable interface

* Start of Thread: Start thread, run thread running method, end of Run method running thread (note that start is only in thread, start is different from run)

* Note A thread object that can only call the Start method at one time

The difference between *thread and runnable: 1:runnable is an interface that is more flexible than thread (because Java can only inherit a single inheritance and implement many interfaces at the same time); 2. A Runnable object can start many threads, Shared objects between threads (thread cannot share objects)

3. Thread Status: New, can run, run, block, die

4. Scheduling of threads

*thread.sleep, causes the thread to sleep

*join: Thread Merge (Results similar to method call)

*yield: Thread yields current CPU, left to other threads to run

* Thread Priority: SetPriority Set Thread Priority

* Background thread: Setdaemon, must be set as a background thread before the thread runs. When all foreground threads are finished, the background thread ends automatically

* Thread can specify the name, get the current thread method Thread.CurrentThread ();

5. Thread Synchronization

*synchronized: At the same time, there will only be one thread executing the synchronized block of code

6. Inter-thread communication

*wait (), notify (), Notifyall is a method defined in the object class

*wait (): Causes the thread running the code to wait for the object's waiting pool to enter the blocking state, the wait thread is blocked, and the other thread is instructed to invoke the object's Notify method to wake it.

*notify (): Wakes the object to wait for a thread in the pool so that the awakened thread enters a running state, and notify does nothing if it waits for no thread in the pool.

*notifyall (): Wake-up object waiting for all threads in the pool

*wait (), notify,notifyall must be placed inside the synchronization code block (synchronized code block).

The thread of the *wait () frees the object's lock, while the Thread.Sleep thread does not release the object's lock

7. Thread-Safe classes: Classes that use a class in a multithreaded environment or that call a method of a class that do not cause synchronization problems are called thread-safe classes

*jdk1.1 Previously, there were some thread-safe classes in the collection framework of Java: vectors (replaced by ArrayList), HashTable (replaced by HashMap)

Io{c}16. {C} network {c}17. {C} class and Object life cycle 18. Supplementary Knowledge points

Code writing Specification

Code Trace debugging

Sometimes it is necessary to know the specific execution of the program, which is useful for tracking procedures

Trace Debugger

* Set Breakpoints

* Debug, TRACE program run

* Program running process, value of variable

Java Basic Knowledge Point Summary, Java Learning Java must be familiar with and grasp, I hope this blog post for you to learn to help

Summary of basic Java Knowledge (complete)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.