A summary of the seven-----of Java's basic knowledge review

Source: Internet
Author: User
Tags modifier modifiers new set visibility volatile wrapper

Objective

In the previous Java Fundamentals Review, we reviewed the underlying data types, modifiers and strings, three features, collections, multithreading, and Io. This article summarizes the knowledge that you have previously learned. In addition to the simple review, it will add some corresponding understanding.

Underlying data type

The basic data types are:
BYTE, short, int, long, float, double, char, Boolean
They can be divided into three categories:

    1. Numeric types:byte, short, int, long, float, double
    2. Character type:char
    3. Boolean type:boolean

Where byte is 8 bits, short is 16 bits, int is 32 bits and long is a 64 integer, and float 32 bit, double 64 bit floating point number.
The level of the numeric type is from low to high, respectively:
Byte,char,short (these three-lateral)-->int-->float-->long-->double
It is the automatic type conversion , which is automatically converted by the system, from low to high level. At the time of calculation, if the level is less than int, the final data type is automatically converted to int, and if higher than int, the final data result will be the highest one.
A high-level transition to a low level is a forced type conversion . forcing type conversions requires attention to the range of values and the accuracy of the data.

Char is a character type and can store any character.
Boolean is a Boolean type, only false or true.

A more detailed description of the underlying data type: http://www.panchengming.com/2018/03/18/pancm76/

In general, we use the basic data type, but also the type of packaging.
Here by the way the packaging type, but also to make up for the previous article on insufficient.

What is a wrapper type? The relationship between the wrapper type and the underlying data type.
A wrapper class is a type of basic type data that is converted to an object.

Each base type has a corresponding wrapper class in the Java.lang package.
Underlying data type:
Boolean, char, Byte,short,int, Long, float,double
The corresponding package data type:
Boolean,character,byte,short,integer,long,float,double

What is the use of packing type ?

    1. Facilitates the conversion between basic types;
      Because we understand that the conversion of the basic data types into automatic type conversion and coercion type conversion, automatic type conversion is OK, but forced type conversion is prone to problems. So there is the packaging type, it can be very convenient to help convert.
      For example, a type string of type int can be converted to int by Integer.parseint () , or converted to an Integer type using integer.valueof () .

    2. convenient function transfer value;
      Why do we say the value of the aspect function? If the argument of a method is of type object, but your entry is an int type, you cannot call this method directly, so you can wrap the data of type int into an integer type and make the call. In fact, in addition to this example, the more common is our Pojo type, generally use the wrapper type, so that you can use NULL to judge. More than that, the types in generics, such as list, map, set, and so on, are in the package type, for example:Map<String,Integer> map=new HashMap<String,Integer>();

Note: When using the wrapper data type for value comparisons, compare with equals and do not use = =. For example:

    Integer a=127;    Integer b=127;    Integer c=128;    Integer d=128;    System.out.println(a == b);    System.out.println(a.equals(b));    System.out.println(c == d);    System.out.println(c.equals(d));

Output Result:

truetruefalsetrue
Modifier

Java modifiers fall into two main categories:

    • Access modifiers
    • Non-access modifiers

Where access modifiers mainly include private, default, protected, public.
Non-access modifiers mainly include static, final, abstract, synchronized.

Access modifiers

Access to the access modifier:
| Modifier | Current Class | In the same package | Sub-Class | Other Packages |
| :-----: | :-----:| :------: | :----:| :---: |
| Public | Y | Y | Y | Y |
| protected | Y | Y | Y | N |
| Default | Y | Y | N | N |
| Private | Y | N | N | N |

Non-access modifiers

static: Used to modify class variables and class methods.
Modifier variables

When static modifies a class variable, it has only one copy of its static variable, no matter how many times the class is instantiated. Static variables are also known as class variables. A local variable cannot be declared as a static variable.

Modification methods

Static methods cannot use non-static variables of a class when modifying a class method. Static methods can be called directly from the class name, so the this and Super keywords cannot be used in static methods.

final : Used to modify classes, methods, and variables.

The final modified class cannot be inherited, the decorated method cannot be redefined by the inheriting class, the modified variable is constant, and is not modifiable.

Abstract: Used to create abstraction classes and abstract methods.
Modifier class

Makes this class an abstract class that will not generate an object instance, but can be used as the type declared by the object variable (see later instance), which is the compile-time type. Abstract classes are equivalent to a class of semi-finished products, which require subclasses to inherit and overwrite the abstract methods.

Modification methods

Will make this method an abstract method, that is, only the declaration and not the implementation, the subclass must inherit the implementation.

synchronized: The modified method can only be accessed by one thread at a time.

transient: the Java Virtual machine (JVM) skips that particular variable when the instance variable is modified by transient.

Native: The method modified by native is actually a native method implemented by another language

Modifier more detailed Description: http://www.panchengming.com/2018/03/24/pancm77/

Three main features Package

Encapsulation can be thought of as a protective barrier against random access to code and data of that class by code defined by external classes. To access the code and data for this class, you must pass strict interface control.

Benefits of using encapsulation

    1. Good encapsulation can reduce coupling.

    2. The structure within the class can be freely modified.

    3. You can have more precise control over member variables.

    4. Hide information and implement details.

Inherited

Inheritance is a cornerstone of Java object-oriented programming technology because it allows classes of hierarchical hierarchies to be created.
Inheritance is the child class inherits the characteristics and behavior of the parent class, so that the subclass object (instance) has the parent class's instance domain and method, or the subclass inherits the method from the parent class, so that the subclass has the same behavior as the parent class.

Advantages and Disadvantages

Although inheritance greatly improves the reusability of code, it also improves the coupling between classes!

Polymorphic

Polymorphism refers to the existence of different state of things in the course of operation.

The advantages of polymorphism

    1. Replaceable (substitutability). Polymorphism is replaceable for existing code. For example, polymorphism works on the Circle Circle class and works on any other circular geometry, such as a ring.
    2. Extensibility (Extensibility). Polymorphism has extensibility for code. Adding new subclasses does not affect the polymorphism, inheritance, and the operation and manipulation of other attributes of existing classes. In fact, new subclasses are more likely to get polymorphic functions. For example, it is easy to add the polymorphism of sphere class on the basis of realizing the multi-state of cone, semi-cone and hemispherical body.
    3. Interface (interface-ability). Polymorphism is a superclass that, by way of signature, provides a common interface to subclasses, which is implemented by subclasses to refine or overwrite the class.
    4. Flexibility (flexibility). It embodies the flexible operation in the application, and improves the use efficiency.
    5. Simplification (simplicity). Polymorphism simplifies the process of coding and modifying the application software, especially when dealing with the operation and operation of a large number of objects.

Three major features more detailed description: http://www.panchengming.com/2018/03/24/pancm78/

Collection List

The List interface is inherited from the collection interface and defines an ordered set of allowed duplicates. This interface is not only able to process a part of the list, but also adds a location-oriented operation.

List of common classes
    • ArrayList: The interior is implemented by an array, which allows for fast random access to elements. When inserting or deleting elements from the middle of a ArrayList, it is necessary to copy, move, and cost the array. Therefore, it is suitable for random lookups and traversal, and is not suitable for insertions and deletions.
    • LinkedList: It is the linked list structure to store data, it is suitable for dynamic insertion and deletion of data, random access and traversal speed is relatively slow. In addition, he provides methods that are not defined in the list interface, specifically for manipulating the header and footer elements, and can be used as stacks, queues, and bidirectional queues.
    • Vector: Implemented by an array, the difference is that it supports thread synchronization. Access speed ArrayList slow.

A single thread is recommended for querying and traversing using ArrayList, LinkedList for insertion and deletion.
Multithreading uses the Collections.synchronizedlist method to lock the list to a higher efficiency than a vector.

Map

the Map interface is not an inheritance of the Collection interface . Map provides a key-to-value mapping. A map cannot contain the same key, and each key can only map one value. The map interface provides views of 3 collections, and the contents of the map can be treated as a set of key sets, a set of value collections, or a set of key-value mappings.

Map Common Classes
    • HashMap: The key of HASHMAP is obtained according to Hashcode, so the corresponding value can be obtained quickly according to the key. However, its key object can not be duplicated, it allows the key to be null, but there can be only one record, but it is allowed to allow multiple records of the value is null. Because the HashMap is non-threaded, it is highly efficient.
    • TreeMap: You can sort the saved records by key by default, which is the ascending sort (natural order) of the key values. You can also specify a sort comparer, and when you traverse treemap with iterator, the resulting records are sorted out. It also does not allow the key value to be empty, and is not thread safe.
    • linkedhashmap: Linkedhashmap Basic and HashMap consistent. But the difference between with Linkedhashmap is to maintain a doubly linked list, which can be read in the order in which the data is written. It can be thought that Linkedhashmap is hashmap+linkedlist. That is, it uses HASHMAP to manipulate data structures, and linkedlist to maintain the order in which elements are inserted. It is also not thread-safe.
    • Hashtable: Hashtable is similar to HashMap, and can be said to be a thread-safe version of HashMap. However, it is not allowed to record the key or the value is null. Because it supports thread synchronization and is thread-safe, it also causes the Hashtale to be less efficient.
    • concurrenthashmap: Concurrenthashmap introduced in Java 1.5 as an alternative to Hashtable. The use of lock segmentation technology to ensure thread safety can be seen as an upgrade to Hashtable.

Recommended single-threaded random queries with HashMap, natural order or custom order with TreeMap, insertions and deletions with Linkedhashmap.
Multithreading recommends the use of Concurrenthashmap.

Set

Set is a collection that contains no duplicate elements, that is, any two elements E1 and E2 have E1.equals (E2) =false,set have a maximum of one null element. Because set is an abstract interface, it is not possible to instantiate a set object directly. Set s = new Set()this writing is wrong.

Recommended single-threaded random queries with HashSet, natural order or custom order with TreeSet, insertions and deletions with linkedhashset.

A more detailed description of the collection: http://www.panchengming.com/2018/04/19/pancm80/

Multithreading

Multithreading refers to the execution of multiple sequential streams in the same program. Simply put, there are multiple tasks running in a program.

The state of the thread

Create (new) state: A Multithreaded object is prepared
Ready (runnable) state: Call the Start () method, waiting for the CPU to dispatch
Run (running) state: Execute Run () method
Blocking (blocked) state: Temporarily stops execution and may give resources to other threads for use
Terminating (dead) state: Thread Destruction

Creation of Threads
    • By implementing the Runnable interface;
    • By inheriting the Thread class itself;
    • By implementing the callable interface, then with the future and creating threads.

Note: The thread starts with start instead of run.
It is recommended to create a single thread when creating threads using the inherited thread class, using the runnable, callable interface to create the creation threading.

Common Methods of threading
    1. Sleep: Allows the currently executing thread to hibernate (suspend execution) within the specified number of milliseconds, without releasing the object lock.
    2. Join: Refers to waiting for the T thread to terminate.
    3. Yield: Pauses the currently executing thread object and executes other threads.
    4. SetPriority: Sets the priority of a thread.
    5. Interrupt: Whether a thread is a daemon thread.
    6. Wait: Forces a thread to wait. It is a method of object and is often compared to sleep. It is important to note that wait frees the object lock for other threads to access it, and the wait must be caught with exception, and the object in synchronized must be used for the current call.
    7. IsAlive: Determine if a thread is alive.
    8. Activecount: The number of active threads in the program.
    9. Enumerate: Enumerates the threads in the program.
    10. CurrentThread: Gets the current thread.
    11. Setdaemon: Sets a thread as the daemon thread. (The difference between a user thread and a daemon thread is whether to wait for the main thread to end up relying on the end of the main thread).
    12. SetName: Sets a name for the thread.
    13. Notify (): Notifies a thread to continue running. It is also a method of object, often used in conjunction with the Wait method.

Multithreading more detailed Description: http://www.panchengming.com/2018/05/28/pancm84/

These keywords synchronized,lock , and volatileare often used in multiple threads.
synchronized: Synchronized is JVM-level, which is explained by the JVM at run time. It is a blocking lock (i.e. only one thread is held at the same time) and an unfair lock (that is, the principle of not following first served, when a thread a holds a lock and thread B and C are in a blocking state, if thread a releases the lock, the JVM will randomly select a thread from thread B, c to hold the lock and make it execute). can guarantee atomicity, visibility and order.

lock: Lock is implemented by encoding. It is a non-blocking lock, and also a fair lock. can guarantee atomicity, visibility and order. More flexible and powerful than synchronized.

volatile: a lightweight lock. The primary user guarantees that the shared variable is visible to all threads, as well as prohibit command reordering. Because there is no guarantee of atomicity, thread safety is not guaranteed.

Thread safety and shared resources
1. The basic data type (8 types) in local variables is always thread-safe.
2. Object types in local variables are thread-safe as long as they are not accessible to other threads.
3. When an object instance is accessed concurrently by multiple threads, his member variables may be thread insecure.

IO stream

The name of IO is also the abbreviation for input and output, which is the inputs and outputs stream. The input stream is used to read data from the source, and the output stream is used to write data to the target.

Character Stream

There are two abstract classes of character streams:Writer and Reader class.
Its corresponding subclass FileWriter and FileReader can realize the file read and write operation.
bufferedwriter and BufferedReader can provide buffer functions for increased efficiency.

BYTE stream

Byte stream also has two abstract classes:InputStream and outputstream classes.
The corresponding subclasses have FileInputStream and FileOutputStream to implement the file read and write operation.
bufferedinputstream and bufferedoutputstream provide buffer function

It is recommended to read text with a stream of characters , to read binary files such as pictures, videos and pictures with byte streams .

IO Stream more detailed description: http://www.panchengming.com/2018/06/16/pancm85/

Speaking of Io Stream, incidentally it's a couple of twins, NIO, bio and AIO.

Io:

Blocked, when reading data from the hard disk, the program waits until the data is read and continues to operate.
One byte of read data at a time, one output stream output one byte of data at a time, one output stream consumes one byte of data at a time, the data reading and writing efficiency is not good.
I/O is the underlying operation, performance dependent and system environment.

Nio:

Synchronous non-blocking I/O, when reading data, the program can continue to execute, read playing data, notify the current program (that is, hardware interrupts, software callbacks), and then the program immediately or after the completion of processing data. Selector (selector), buffer (buffer), pipeline (channel) oriented block (buffers). Take a "read-ahead" approach. One step in the operation is to generate or consume a block of data, processing the data by block, while the data is read to a buffer that may be processed later, and can be moved before or after the buffer if needed.
The method is suitable for architectures with a large number of connections and a relatively short (light operation) connection. such as chat tools. After all, easy to use framework Netty and Mina.

BIO:

Synchronization and blocking, the server implementation mode for a connection to a thread, that is, the client has a connection request when the server needs to start a thread to process, if the connection does not do anything will cause unnecessary thread overhead, of course, can be improved through the thread pool mechanism.
method is suitable for a small and fixed number of connections

Aio:

Asynchronous non-blocking, the server implementation mode for a valid request for a thread, the client I/O requests are completed by the OS before notifying the server application to start the thread for processing.
The schema is used for a number of connections and for long connections (re-operation).

This is a simple introduction to this knowledge. You can view this article in more detail: 75577091?ref=myread

Other

Java basic knowledge of the summary of the introduction here, the future of the post is mainly written in the direction of Java advanced Knowledge, the main content for the design mode, source code parsing and concurrent programming this piece bar! As for the post, these posts do not have the confidence to write well, after all, these are relatively difficult to understand. So later these related blog post I will follow their own understanding of the written, if not written well, please more guidance!

Original is not easy, if feel good, hope to give a recommendation! Your support is my greatest motivation for writing!
Copyright Notice:
Empty Realm
Blog Park Source: http://www.cnblogs.com/xuwujing
CSDN Source: HTTP://BLOG.CSDN.NET/QAZWSXPCM
Personal blog Source: http://www.panchengming.com

A summary of the seven-----of Java's basic knowledge review

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.