I would like to share my notes on the basic part of Java in the process of learning Java, which are more detailed and more content. If you have any questions, please point them out for correction. Thank you. The length is longer and it is recommended to collect and browse.

Some of the highlights will be covered in more detail: collections, threads, JVMS, JMM memory management, and multithreading. Please pay more attention. Lybyte Z takes you through

Java data types: Java data types: Java data types

Basic data types: Basic data types: Basic data types: Basic data types

1.1 CHAR :Unicode encoded characters, or integers of characters, must be quoted in single quotes

Float defaults to 0.0f; Double defaults to 0.0d;

1.2 Basic type literals rules

1. Integer literals are of int type. If the value assigned to the right exceeds the int range, conversion is required

Any of three integers smaller than int that can be assigned directly within their range.

Byte d=1+3 Correct, 1+3 compiler will automatically convert to 4

3. The float value is double; Converting a floating point number to an integer directly abandons the decimal place.

4. Suffix, L, D, F

5. Literal prefix, 0B binary; 0x hexadecimal; Base 0 8; \u char Type in hexadecimal.

1.3 Operation rules of basic types

1. The data type of the calculation result is the same as the maximum type in the operation.

Any of three integers smaller than int that are automatically converted to int when evaluated

When addition is performed, the data type is automatically converted to int. When addition is performed, all non-int types are converted to int except for increment and subtraction. When there is a long type, it all goes to long.

Char added to int.

Java basics notes summary share (super detailed) basic computing

3. Integer calculation overflows. Integer.MAX_VALUE+1 minimum negative value 4. Special value infinity integer divided by 0; Take the square root of a negative Nan

1.4 Type conversion for primitive types

Numeric types can be converted to each other, automatically converted from small to large, and forced to convert from large to small. double d = 245; Float d = 100; Automatic transformation.

Basic data type conversions are essential for getting started

1.5 the operator

&& : logic and (short circuit), on both sides with true result is true, short circuit and: on the left is false, the right to ignore does not perform & : no matter what the result is on the left is to execute the right side (left and right sides are involved in operations &) | | : logic or (short circuit or), as long as there is a true as a result, both sides short circuit or: on the left is the true, the right to ignore does not perform

2. Process control

2.1 Switch: Byte short char int enum STRING after JDK1.7. From the established case unconditionally through all cases including default until the end or break out of the loop; If all conditions are not true, execute default

2.2 a for loop

Java basic knowledge of notes summary share (super detailed) essential to get started

2.3 break and continue

Break breaks, jumps out of the loop, and switch Continue skip the code to Continue to the next execution of the loop

2.4 the for-each loop

Array traversal, collection iteration traversal syntax simplification

Java Basics notes summary share (super detailed) basic Java knowledge notes summary share (super detailed) basic Java knowledge prerequisites 3. Object oriented – encapsulation, inheritance, polymorphism ★ ★ ★ ★ ★ ★

encapsulation

Class 1: templates and drawings. Classes that define the object’s property data (member variables), and methods (member methods) are loaded into the method area 2 object when first used: a concrete instance created from a template, which is a package of data. When a new instance is created, memory space is allocated to the instance in the heap.

Reference variables: understood as “remote control”, store the memory address of an instance (reference variables are stored on the stack), the special value of reference variables: null does not store the memory address of any instance.

Constructor: a special method that is executed immediately when creating an instance object. The constructor must have the same name as the class and have no return value type. A class must have a constructor. If it does not define a constructor itself, the system will add a default constructor. Constructors are used to assign values to attributes.

Java basic knowledge of notes summary share (super detailed) essential to get started

6 Methods Overload: all methods can Overload regardless of the return value type.

7 This keyword: this. XXX special reference refers to the address of the current object.

This (…). : calls between constructors, which must be the first line of code, will pass if there are more than one constructor

This (…). Call all of the following constructors to complete the assignment.

Note that this cannot be used in static methods

inheritance

Java inheritance is single-inheritance multi-implementation, can inherit only one parent class (if not other classes, the default inheritance object class), but can implement multiple interfaces

1. Cannot inherit: constructor, private member

Procedure: First create a parent class object, then create a new child class object, both as a whole object, call the member, first find the child class, then find the parent class

2. Override method

To inherit a method, redefine the method in the parent class in a subclass (overridden only in a subclass). The method name must be the same, the number and type of arguments must be the same, and the return value type must be the same.

Method override returns a value of the same type as the parent if it is a primitive type. Overrides require method names to be exactly the same and return value types to be the same if they are primitive or if there is no return value.

3. Constructor of the parent class

When a new subclass object is created, the parent object is created first, and the constructor of the parent class is executed first

The no-argument construction of the parent class is performed by default, with an implied call to super () by default;

New Student () performs parent class no-argument construction by default

New Student (……) By default, parent class no-argument construction is performed

Manual call of the parent class’s parametric construct, super (parameter) : must be manually called if the parent class has no parameterless construct

When the super super.xxxx () method is overridden, the code that calls the same method in the parent class super (parameter) calls the constructor of the parent class. By default, super () is called without arguments, and super () is manually called with arguments. This must be the first line of code

polymorphism

An object has multiple manifestations. Polymorphism requires inheritance. Void test(parent o1) {}; An instance of a subtype is treated as a parent type. All subtypes can be passed to the method and treated as a parent type. Function: Consistent type

1. Type conversion

A. Upcast the instance of the subclass to the parent type, and use the reference variable of the parent type to reference the instance of the subclass. After upcast, only the general members defined by the parent class can be called, and the subclass-specific members are hidden. Cast down to a subclass instance that has been cast to a parent type, and cast back to a subtype for special handling of the subtype

2. Type recognition of Instanceof runtime

When multiple subtypes are treated as parent types, special treatment for a subtype can be performed by checking the true type and then casting down – return true for both the true type and its parent type. Eg:

if(obj instanceof CustomException){ throw new CustomException(obj.getMessage()); }

An array of 4.

It belongs to object class and is used to store a data structure of a group of data. An array is the most basic data structure but not the basic data type. An array is a collection of the same data types, and the elements in the array are sorted in a linear order

4.1 Array creation

If an initial value is not specified after the array is created, the default value is set based on the array type. Eg: There are 3 ways to start an array:

Create an array of int[], length 6, default value 0, the starting address of the array is stored in variable A.

int[] a = new int[4]; int [] b = {1,2,3,4}; int [] c = new int [] {1,2,3,4,5};

4.2 Array length attribute a.length

Once arrays are created, the length immutable maximum subscript A. length-1 allows arrays of 0 length

4.3 Two-dimensional Array

An array of arrays

int[][] a = new int[3][2]; There are four arrays. The default value of the inner array is 0. The outer array holds the address of the inner array. int[][] a = new int[3][]; I’m just going to create a peripheral array of length 3 and all 3 null positions, and then I’m going to create a new array and put it inside.

4.4 Arrays Utility classes

Arrays. ToString Concatenates array data into strings. The basic types of optimized quicksort; Reference type: Optimized merge sort. Array.binarysearch (array, object index) returns – (insert point +1) The number of copies that make up a new array of the specified length.

4.5 Array Replication

Arraycopy (original array, original array start position, target array, target array start position, number of copies) — No new Arrays are created, the target array has to exist in advance.

5. The variable

Local variables: defined in a method or a local code block, must be initialized (memory is allocated on the first assignment). The scope of a local variable is valid within the curly braces in which it is defined, and cannot be redefined within scope. 2 member variables: defined in a class, default values are automatically initialized, and access to member variables is restricted by access control characters. Local variables can have the same name as member variables.

6. The Object class

If a class does not inherit from another class, the Object class is inherited by default

Internal methods:

ToString () gets a string representation of an object.

The default implementation in Object is that “class name@address” can override the toString method in subclasses.

Equals () Compares the current object to the participating object.

The default implementation in a.equals(b) Object is to compare memory addresses.

Object compares the memory address. The default value of the basic type compares the content.

public boolean equals(Object obj) { return (this == obj); } // The default implementation of equals in Object.

7. The String class

String is an object that encapsulates an array of char[].

7.1 String Creation

Char [] a = {‘ a ‘, ‘b’, ‘c’}; String s = new String(a); >>> Simple Syntax >>> String s = “abcd” 7.2 Constant Pool of Strings String s1 = “abcd” literal writing of strings. The first time a string literal is used, new memory is allocated in the string constant pool, and the next time the same literal is used, objects existing in the constant pool are directly accessed without duplication.

== == == == == == == == == == The instructions are as follows:

char[] a = {‘a’,’b’,’c’,’d’}; String s1 = new String(a); String s2 = “abcd”; String s3 = “abcd”; System.out.println(s1==s2); //false compare memory address system.out.println (s2==s3); System.out.println(s1.equals(s2)); //true compares string contents system.out.println (s2.equals(s3)); 7.4 String is immutable and string concatenation is inefficient. Each concatenation creates a new string object 7.5 string

CharAt (I) Returns the length of the string at the specified position, and the number of characters. SubString (start) truncates start to end subString[start,end) truncates range [start,end) trim () removes whitespace from both ends Matches () : a mutable sequence of characters that encapsulates an array of char[]. This StringBuilder provides a set of methods for modifying characters that are internally encapsulated. It is often used to perform efficient string concatenation instead of strings.

Append () appends character content, internal array default initial capacity 16, when full double +2; Delete (start,end) Deletes the interval (start,end); DeleteCharAt (I) deletes the specified position I; Insert (I, content) Inserts content at the specified position; InsertCharAt (I, character) Inserts a single character at the specified position; Replace (start, end, content) replaces the content of the specified range; StringBuilder and StringBuffer StringBuilder: Threads are unsafe and efficient. New classes after JDK1.5. StringBuffer: Thread-safe, older version of the class.

Regular expressions

It is used to determine whether the user input meets the format requirements

Matches () {dosomething} split (re) : String s = “aaa, BBB, CCC “; String[] a = s.split(“,”); Replace Replaces all matched substrings

9. Basic types of wrapper classes

Use byte — byte short — short int — Integer long — long float — float double — double char — Character Boolean to treat basic types as objects – Boolean

Subclasses: Byte, Short, Integer, Long, Float, Double, BigDecimal, BigInteger

ByteValue (), shortValue (),intValue (),longValue (),floatValue (),doubleValu()

9.2 Intger class

Create an Integer object: a= {value: 6}

Integer a = new Integer(6);

Integer a = Integer.valueOf(6);

There are 256 Integer cache objects in the Integer class, encapsulated in -127 to 128; If a value within the specified range is accessed, the cached object is accessed, and if it is outside the range, a new object is created.

9.3 Methods of the Integer class

String parsed to int

Integer. The parseInt (); Byte. ParseByte ()…

Integer.tobinarystring () is converted to a binary string

Integer.tooctalstring () converts to an octal string

Integer.tohexstring (255) converts to a hexadecimal string

9.4 BigDcimal and BigInteger Precise floating-point operations of the BigDcimal class BigInteger Operations of large integers

BigDecimal bd = BigDecimal.valueOf(2);

Methods:

Add (BigDecimal BD) Multiply (BigDecimal BD) divide(BigDecimal BD) Divide (BigDecimal BD) Divide (BigDecimal BD) SetScale (reserved digits, rounded) 9.5 Automatic packing, automatic unpacking

Basic type value that is automatically boxed into a wrapper object

Integer a = 6; Integer a = integer.valueof (6); Automatic unpacking (Note null value for automatic unpacking)

int i = a; Int I = a.int value ();

10. Abstract class

Semi-finished, unfinished; Abstract methods: There is no code, only method definitions. Abstract classes cannot create instances and are mainly used to be inherited.

// The class that contains the abstract method must be the abstract class public abstract class A {public abstract void f(); // Abstract method}; What abstract methods do:

As a generic method, defined in the parent class; To subclass, you have to implement this method.

1) Abstract classes can have their own constructors.

2) Abstract classes can have concrete methods.

3) The class containing an abstract method must be abstract and must be modified with the abstract keyword. The method must be implemented by a subclass.

4) An abstract class cannot use the new keyword to create an instance.

5) Whenever there is an abstract method in a class, the class must be abstract.

6) Abstract classes can define instance variables and static variables as well as constants.

7) Abstract classes can inherit from abstract classes as well as from ordinary classes.

11. Keyword final

Memory addresses are immutable and can be modified for constants, classes, and methods

11.1 Final Constants: Values are immutable, but reference types can change content because they hold addresses.

Final Point a = new Point(3,4);

a.x = 30; / / for

a.y = 40; / / for

11.2 Final methods cannot be overridden in subclasses, but can be inherited. ; Final cannot be used to modify constructors, and private member methods of a parent class cannot be overridden by subclass methods, so methods of private type are final by default.

11.3 Final classes cannot be inherited and have no subclasses

Static – Statically shared data

Static members belong to classes, not instances

Static members

Class to call the static member Soldier.count

Instance members

Instance member s1.id is called with instance

Utility methods

Math.Random() Arrays.toString() String.valueOf()

A member of an instance cannot be called directly in a static method (non-static), only with the instance.

class A { public static void main(String[] args) { f(); } static void f() {g(); A A = new A(); a.g(); } void g(){}}

Static variables are stored in the space of the method area class and only hold a single copy of data that can be shared across all instances

★ ★ ★ ★ ★ ★ ★ ★ ★

Loading a class:

1. Load the parent class and allocate memory for static variables of the parent class – background execution is not visible

  1. Load the subclass and allocate memory for the subclass static variables

  2. Performs the assignment of the parent static variable, and the static initialization block

  3. Performs subclass static variable assignment, and static initialization block

Create a new instance:

  1. Create a new instance of the parent class and allocate memory for the parent instance variable

  2. Create a new subclass instance and allocate memory for the subclass instance variable

  3. Performs an instance variable assignment of the parent class

  4. Execute the constructor of the parent class

  5. Performs an instance variable assignment of a subclass

  6. Executes the constructor of a subclass

Collection of 12.

Disadvantages of an array of data structures used to hold a set of data: fixed length; Single access mode only subscript access; Add and delete data in front of the complex set of inheritance structure :(beginners understand the common can be used)

A Collection is a Collection of objects. A Collection has two subinterfaces: List and Set.

List can be subscripted (1,2…) Values can be repeated, whereas a Set can only be evaluated by a cursor, and values cannot be repeated

ArrayList, Vector, LinkedList are the List implementation classes

ArrayList: is thread-safe, Vector is thread-safe, both of which are implemented by arrays at the bottom

LinkedList: is thread-unsafe. The underlying implementation is a LinkedList

Map: is a collection of key-value pairs

HashTable and HashMap are Map implementation classes

HashTable: is thread-safe and cannot store null values

HashMap: Not thread-safe and can store NULL values

ArrayList

Arraylist, encapsulates an array, and its operation code and more convenient methods, internal array default initial capacity of 10 after full, 1.5 times growth

Methods:

Add (data) – Add data; Get (int I) – Accesses specified subscript data; Remove (int I) Removes data at a specified location and returns the removed data. Remove (data) – If the first equal data is found, remove and return true if it is found, false if it is not found; Size () number of elements; Iterator () assists in creating new iterators

Efficiency:

The efficiency of accessing any location is high, but the efficiency of adding and deleting data may be reduced.

LinkedList – The LinkedList method has the same method as ArrayList addFirst (data); AddLast (data); GetFirst (); GetLast (); RemoveFisrt () removeLast ();

Efficiency The efficiency at both ends is high

★ ★ ★ ★ ★ ★ ★ ★

Store key-value pairs of data, with keys to quickly locate the data, to extract the corresponding value of the key

Keys: do not repeat, unordered

Key-values in a Hashmap are stored in an array of entries

The implementation of Hashmap is not synchronous, meaning it is not thread-safe

An instance of a Hashmap has two parameters that affect its performance: the initial capacity, and the load factor

Methods:

Put (key,value) Puts key-value pair data. Duplicate keys overwrite old values

Get (key) retrieves the value of the key, which does not exist, and returns NULL

Remove (key) Removes key-value pair data and returns the removed value

Size () number of key-value pairs.

Hash operation

Inside the HashMap, use the entry[] array to store data. The default initial size of the array is 16

Key.hashcode () gets the hash value of the key using the hash value and the length of the array to generate the subscript value I Create an entry object to encapsulate the key-value pair data Entry object, put it in I if it’s empty, put it in if it has data, compare equals () to find the same, Overwrite old values not equal, join lists together load rate, load factor over 0.75 Create a new array that doubles the capacity of all data, re-hash values, store new arrays Jdk 1.8 List length to 8, convert to red black tree tree data reduced to 6, convert back to list hashCode ()

HashCode () is an object method. The default implementation uses the memory address as the hash value,

Methods can be overridden to get the same hash value

The hash must have the same hash value in order to evaluate the same subscript value, and equals () must also be equal (the equals method must also be overridden) in order to override the old value, otherwise the list joins.

Rewrite hashCode’s idiomatic algorithm :(x.y is the value of the variable)

13. Exception Encapsulates the error information of the object, including the type, message, and line number

The inheritance structure of exceptions

Java basics notes summary share (super detailed) getting started must catch exceptions

Try {} catch(AException e) {} catch(BException e) {} catch(parent type Exception e) {} finally { In addition, there is a return statement in catch. The return statement will be executed first, and then the result will be stored in the cache to check whether there is finally. If there is finally, the finally statement will be executed first, and then the value of the return in the cache will be returned. If there is also a return in finally, then the return in finally overwrites the previous return in the cache. That is, the return in finally is eventually returned. Throw Throws an exception manually. When a program has a logical error and does not automatically create and throw an exception, you can manually identify the logical error and create an exception object and throw an exception. Exceptions from the bottom layer are thrown to the top layer, where they are processed.

if(…) { AException e = new AException(); throw e; } Abnormal packaging

Multiple types are simplified into one type. Exceptions that cannot be thrown are packaged into exceptions that can be thrown.

RuntimeException and other exceptions

RuntimeException – Non-check exception, the compiler does not check for exception handling code, there is a default throw pipe

Other exceptions – The compiler checks to see if there is any handling code. If not, it cannot compile.

14. Interface extreme abstract class, structure design tool, used to decouple, isolated reality

Implements instead extends

Interface instead of the class

Interface definition:

Exposes abstraction methods according to system logic. Exposes constant queues, which expose inner classes and interfaces

1) Interfaces can only define constants

2) Interfaces can only define abstract methods

3) Interfaces can only inherit interfaces, not common classes and abstract classes

4) Interface has no constructor

Note:

1) When defining constants in interfaces, you do not need the final static modifier because the compiler automatically adds it at compile time.

2) You can omit the abstract keyword when defining abstract methods in the interface, and the compiler will add it at compile time.

3) Interfaces in JDK1.8 can be implemented with default methods, see Interface Map for details.

Class A implements B implements X,Y,Z {} class A implements B implements X,Y,Z { Interface and interface inheritance 15 File and character operation flow File encapsulates a disk path string. It provides a set of operations on files and folders. You can encapsulate folder paths, File paths, and non-existent paths. } {path = “d: / ABC” method

GetName () gets the file name

GetPatrent () gets the parent directory

GetAbsolutePath () The full path

Length () Specifies the number of bytes in a file, which is invalid for folders and returns false data

IsFile () checks whether it is a file

IsDirectory () is a folder

Create, delete

CreateNewFile () Creates a new file, the file already exists will not be created, returns false; An exception occurs when the folder does not exist

Mkdirs () creates a multi-level folder layer by layer

Delete () Deletes files or empty directories

Directory listing

List () returns String[] containing all file names [” a.txt “, “b.p3”, “c.jpg”]

ListFiles () to get the File [], containing all of the File wrapper File object [{…}, {…}, {…}]

Flow Stream

Read and write operations (IO operations) of data, abstracted as data flowing through pipes

Unidirectional flow

Queue Input stream, which can only be used to read data (read into memory)

Queues an output stream, which can only be used to output data (memory data is exported)

The flow can only be sequential once from beginning to end, not repeated. If you want to repeat the flow, you can create a new flow

InputStream, the abstract parent of the OutputStream stream

Methods:

[1][2][3][4] — > [4]

Write (byte[], start, length) Outputs the length byte value starting from start in byte[]

Read () reads a byte value, adding three zeros, making it int [4] — > [1][2][3][4], and returns -1 after reading.

Read (byte[] buff) Read (byte[] buff) Reads a batch of byte values based on the length of the array, stores them in the specified array, and returns the number of bytes in the batch.

FileInputStream, FileOutputStream – file stream

ObjectInputStream, ObjectOutputStream – Object serialization, deserialization

Serialization Outputs the information of an object as a sequence of bytes in a fixed byte format

Basic Knowledge of Java notes summary share (super detailed)

WriteObject (Object obj) Outputs an Object as a sequence of bytes

ReadObject () reads the serialized data and deserializes the recovery object

Serializable interface — Serializable objects must implement the Serializable interface

Unserialized variables

Static – Belongs to the class and does not serialize output with the object

Transient – Temporary, exists in memory only while the program is running and will not be serialized and persisted

A character encoding

Asc-ii 0 to 127, English, instruction characters

Iso-8859-1 Latin-1 Western European encoding, extending ASC-II to 255

CJK code Asian code, China, Japan and South Korea

GBK gb code English single byte, Chinese double byte

Unicode common list of universal codes, two bytes rare words three or four bytes

Utf-8 Unicode Transformation Format Specifies the Unicode Transformation format in English. Chinese, three bytes; Special symbol, four bytes

The Java char type is Unicode

Java transcoding operations

Java basic knowledge of necessary InputStreamReader notes summary introduction to share (more detailed), OutputStreamWriter character encoding conversion flow OutputStreamWriter – the Java Unicode characters, InputStreamReader – Reads other encoded characters and converts them to Unicode characters

16 Inner class A class defined inside a class, method, or local code block to assist external instance operations, encapsulate local data, or local operational logic.

Non-static inner classes, inner classes that belong to instances Non-static inner class instances must depend on an instance of an external class to exist. Static inner class A static inner class, no different from a normal class.

Local inner class a locally defined type, similar to a local variable, has scope and can only be used within a local code block.

Java Basics Notes summary share (super detailed) essential anonymous inner classes

Weapon w = new Weapon() {… }; Explanation {} – anonymous class new – new instance of anonymous class (explanation: super()) – the parent type of Weapon, which passes the parameter super(1,2,3)

Java memory management

Heap memory is used to hold object instances and arrays created by new. The Java heap is an area of memory shared by all threads, created at virtual machine startup, whose sole purpose is to hold object instances. Note that the created objects contain only their own member variables, not member methods.

The stack memory holds the address of the heap memory space, or the variable in the stack refers to the variable in the heap memory (pointer in Java).

Stack: store values of local variables, including: 1. Used to store values of basic data types; 2. Save an instance of the class, a reference (pointer) to the heap object. It can also be used to save frames from loading methods. Constant pools exist in the heap (new after 1.7b).

A regular variable holds its value on the stack, whereas a reference variable holds a pointer to the heap through which you can find the object corresponding to the instance in the heap. Therefore, ordinary type variables occupy only one block of memory in the stack area, while reference type variables occupy one block of memory in the stack area and one in the heap area.

A method area is an area of memory shared by threads that stores data such as class information that has been loaded by the virtual machine, constants, static variables, and code compiled by the just-in-time compiler.

Threads run parallel tasks in a process, creating threads (either way) to implement Runnable, inheriting Thread queues

Inheriting the Thread

Subclass Thread and override the run() method. Once started, the code in the run() method is automatically run

Implement Runnable

Implement Runnable interface, implement its run() method, Runnable encapsulates the code executed in the thread, create a thread object, put the Runnable object in the thread, start

Thread state

Summary of Notes on Java Basics sharing (super detailed) essential thread methods for getting started

Thread.currentthread () gets the executing Thread instance

Thread.sleep allows the executing Thread to pause for a specified number of milliseconds

GetName (), setName() thread name

The pause status of a thread interrupted

Join () Suspends the current thread and waits for the called thread to finish

SetDaemon (true) Background thread, daemon thread

The JVM exit condition is that all foreground threads end. When all foreground threads end, the VM automatically exits

For example, the garbage collector is a background thread.

Thread synchronization

Synchronize execution when multiple threads share access to data. When one thread makes a change, other threads wait until the change is complete. Any instance accessed by one thread while the other threads wait for the access to complete has a “synchronized lock,” which requires a thread to acquire in order to execute

Static void f() {} static void f() {} static void f() {

From: Lebyte