This is the first day of my participation in the August Challenge. For details, see:August is more challenging

Language foundation | More challenging in August

preface

The purpose of this article is to quickly pass through the Java basics (divided into two parts) in order to reasonably arrange the 31 days. JVM, Spring, MQ will definitely have (not too deep), Node, Vue will see the progress, maybe

This is the first day of the August update. Some unadded titles will be updated later. If there are inappropriate places, please correct

Here’s the point. If there is a job for this year’s internship, push it, HXDM, I have been looking for two weeks! Updates in the nugget are also synchronized to the corresponding GitHub repository, where there may be minor differences

The core of this text is the complement and the displacement operations, which are actually the components of the principle. Or, look at parameter passing from the stack perspective, borrow from Rust documents, understand value passing and reference passing, and learn about neglected memory Pointers

Environment to prepare

JDK Environment Configuration

He that would do a good job must sharpen his tools. At the moment, the most mainstream JDK is the Oracle JDK, and that JDK distribution is used here for the full tutorial

  1. Go to the Oracle official website, download the JDK file, and decompress it. (You are advised to use the compression package to install the JDK.
  2. Write the following information in the system variable (it is not recommended to write the path variable directly, which is unfavorable for JDK version switchover)
    • The variable name:JAVA_HOME
    • Value: the directory where the JDK is stored, for example D:\JDK\JDK11
  3. In system variablePath(%% for environment variable parsing)
    • %JAVA_HOME%bin
  4. Open the CMD window and typejava -version, confirm the version

For location of environment variables: File Explorer – This computer (right click properties) – Advanced System Settings – Switch to advanced TAB – Environment variables

If you are tired of Oracle account registration (login and download JDK), you can choose Open JDK in the learning stage, there is no big difference in use

Of course, it is recommended to register an Oracle account and download Oracle JDK. I am not sure whether the two implementations of the source code are the same, and whether they will affect the reading and analysis of common Java classes

The IDEA of installation

A powerful and intelligent IDE is the best partner for your career, humanized IDEA is a good choice

The following is a Windows platform (can’t afford a Mac, don’t need Linux)

Download at www.jetbrains.com/zh-cn/idea/…

On the installation page, select the following items (for zip and EXE installation) :

  1. Select the operating system bits
  2. Select the PATH environment variable (IDEA is recommended).
  3. Other according to need, can choose by oneself

IDEA plug-in, configuration is very important, here only introduce a few plug-ins, configuration, one of the most core is the Chinese plug-in

  1. Chinese: the official provide a Chinese plug-in support
    1. Top navigation bar File
    2. Drop-down option Settings… (Ctrl, Alt, S)
    3. Select Plugins and switch the TAB to Marketplace
    4. Enter “Chinese (Simplified)” in the search box, download, and restart
  2. Expanded memory: smooth IDEA use experience, need enough memory as support
    1. Help -> Change memory Settings
    2. Adjust the allocated memory size according to your own needs, save and restart
    3. View -> Appearance -> Status bar Widgets
    4. Check the memory indicator and view the current memory usage in the lower right corner of IDEA
  3. IDEA plug-in: Plug-in can extend the function of IDEA, extremely important, here is only one early general plug-in (very important)
    1. Code scan: Alibaba Java Coding Guidelines, used to correct development specifications
  4. Formatting: IDEA may have problems with the default formatting of code, such as the indented position of comments
    1. File -> Settings -> Editor -> Code style
    2. More custom configuration, please feel free to explore, not a description
    3. The options provided in the Settings appear to be invalid for automatic whitespace of comments and can be resolved using the template

Of course, there are more details of IDEA operation, which will be explained in detail in the following articles. For example, when analyzing the container source code, how to quickly view the class attributes, methods, internal class information, a series of shortcut keys

For students, JetBrains offers a free license (valid for all products, all versions)

Application address: www.jetbrains.com/zh-cn/commu…

There are large fluctuations in the access speed of foreign servers, such as GitHub and JetBrains

The JetBrains website requires patience to access and load, but the IDE download is fast and unimpeded. Computer learners are recommended to explore scientific Internet access and use a range of productivity tools such as Google search whenever possible

The following is the procedure for applying for a student permit. Each permit is valid for one year and can be renewed

  1. Go to the Education License application home page and select the individual license application interface for students and teachers
  2. Switch to the third TAB (OFFICIAL DOCUMENT), where the information will be reviewed by a human
  3. When filling in the personal application information, pay attention to the submitted proof materials, that is, the official documents, it is strongly recommended to choose the xuexin net student status report, enter the xuexin net personal home page, the student status report can be exported in PDF format
  4. After filling in all the information, you can wait. If you submit a personal student status report of Xuexin.com, the review speed and success rate are extremely high. Do not submit photos of your student id card taken by yourself
  5. After receiving the email that the license application is approved, follow the link given in the email to complete the license binding activation under the account (there may be problems).

When they leave school, they are no longer eligible to apply for an education permit. Of course, by this time, you should be able to maintain your own open source project, and you can apply for the JetBrains open source license, which is also free, and the process is not covered

A full set of JetBrains product licenses (for individuals) will cost around 1,500 YUAN in the first year and 800 yuan in the third year, not including other concessions, which is fully affordable for an active or permanent practitioner

Document the blog

Every computer practitioner, especially in software development, should have a long-term, stable and maintained blog

It is fair to say that the Java ecosystem is too large to rely solely on the memory of an individual brain. Moreover, repeated review will lead to meaningless waste of time. What is more terrible is that it is difficult to intuitively know yourself and sort out the fragments of knowledge. The more the future, the more chaotic

Take a simple Linux environment setup as an example, if you do not record the process. The next time you build, the problems you encounter will still take longer than necessary (the solutions on the Internet are patchy)

I will make a brief introduction to the platforms and tools for writing (personal understanding).

MarkDown: A grammar that every software engineer must master to support a range of platforms such as GitHub, and its importance is self-evident. MarkDown still has writing norms, and don’t bring TXT and word ideas into MarkDown

VSCode: Excellent for writing software, supports the native MarkDown syntax. The writing experience is good, the plugins are rich, it’s a code editor after all, and the performance is excellent. Refer to Typora, which handles multi-document, large documents extremely badly

GitBook, mdBook, VuePress: Static website generator, can be combined with GitHub Pages, quickly build their own personal website, but the style is monotonous, customization is difficult. Importantly, maintenance costs remain high

Sparrow, Nugget: blogging platform. The collection of sparrow is poor, but it provides a good client software; Digger’s collection is good, which the web – side editor can also do, but easy pigeon

It is not recommended to choose CSDN as a writing platform. Yes, it can solve problems for us, there is a very high search engine inclusion, and the writing experience is good. This is like Baidu search and Google search, can solve the problem, but in the overall efficiency is not worth it

Finally, the key recommendation blog garden, its page support custom, some big guy open source very nice theme template. The individual is currently using awesCNB

The other, and the two most important, are my personal impressions

  1. Do not arbitrarily paste, copy. If you think your understanding of an issue isn’t as good as the blog post you were referring to at the time, be sure to post a link to it. Don’t be original
  2. Long-term and stable maintenance. The blog record is extremely vexed, will oneself at that time in the heart of knowledge in the vernacular really feel unnecessary at the moment. Write for a long time and maintain regularly

Deep or shallow, short or long, right or wrong, it doesn’t matter. Itself is not the practice of big guy, but also the means of small white timely consolidation

Of course, only a knowledge point thoroughly, and then record when it will not appear embarrassed, you can add their own understanding. Do not learn a little fur, and think you own the sea

Remember, blindly collecting, does not help. Freely reprint other people’s articles, do you really understand? When choosing an article, don’t just focus on its popularity. GitHub’s top learning projects are a collection of the intrepid. “The Logic of Java programming”, can be said to be the best domestic basic books, but sales are dismal, even if it itself also exists the size of the problem. “Beginner to master,” on the other hand, is selling like hot cakes

Hello, Java

public class HelloJava {
    public static void main(String[] args) {
        System.out.println("Hello Java!)}}Copy the code

Now, begin a brief analysis of this introductory Java code (a brief description of the structure)

public class HelloJava

  1. publicIs an access modifier, which is public
  2. classClass, declaring that this is a Java class
  3. HelloJavaThe name of the class
  4. Multiple Java classes can exist in a Java class, but only one is allowed to be a public class, i.epublic class
  5. Java is case-sensitive, and Hello and Hello refer to two different Java classes
  6. Also, the Java filename must be the same as the public Java class name in it

public static void main(String[] args){}

  1. The main entry function for a Java program from which the Java virtual machine starts executing program code
  2. Among themstatic voidFor the time being, I’ll just call it static, no return value
  3. mainIs the method name of the function. Be case sensitive
  4. String[] argsStored as an array of strings, program instructions are left alone

Master methods must be public, static, and have no return value!

Public static void is an immutable prefix, and String[] args is not recommended

System.out.println() prints the content to the console and feeds it

The meaning of call, reference, class, method, attribute call to each other

; Identifies the end of a line of code

{} identifies the end of a block of code

Variable & Type

What computers actually deal with is data, and any number of data needs to be classified by type. And, the data is essentially stored in memory while the computer processes it. At this point, the computer in order to facilitate developers, accurately find a copy of the data in memory, can set a visual name for the data, this is the data variable name

Data, types, variables. With the development of computer hardware, the development of programming language can give more performance, make programming development user-friendly, reduce the developers’ processing costs. After all, the most efficient way to manipulate binary zeros and ones is to kill the developer. No need to blindly pursue computer efficient processing, but also to balance the cost of developers

variable

Variable, is stored in the memory of the data in the visual symbol, can facilitate developers for the operation of data in memory

int age = 12; This is an example of a local variable in Java. It represents an integer number 12, and the variable name is age. It can be clearly understood that the data represented by this variable is age, which clearly reflects the meaning represented by this data

For the use of variables, it is necessary to pay attention to the scope of the variables themselves, which can be roughly divided into global scope and local scope (only for understanding here).

Note that variables can only be used after initial assignment, that is, the variable has the corresponding in-memory data. Be extra wary of null data (primitive types do not allow null)

int a = 10;
System.out.println(a);
Copy the code

In the example above, the variable a is defined, the data is the integer 10, and is printed in the console. More detailed use of variables will come later, but don’t worry about anything else here

Variable naming

The naming of variables is a big problem, and I have highlighted two points as I understand them (extremely important)

  1. There are different naming formats, such as local, global, and constant, according to the region and property of the variable
  2. According to the data referred to by the variable, the meaning must be known by the name. The function of the data represented by the variable can be understood only by the name of the variable

Next, a brief introduction to variable naming format and how to do the meaning of the name (the rest of the section can refer to the Ali code protocol)

Local variables, such as userName and userPassword, are named according to the small hump principle (lowercase first letter)

First, variable names are not allowed to start with numbers, underscores, and dollar signs. Avoid all three as much as possible

In addition, Java supports the use of Chinese names for variables, but should be avoided, and can write in Chinese alongside comments that cannot be explained in English

See the name to know the meaning, is to let the name of the variable fully reflect the role of the data it represents. Of course, the IDE will not correct the user’s name by referring to the variable name age, but this can cause unnecessary confusion. Also, as much as possible, avoid using meaningless names such as A, b, and aa

Small hump names, pure letters, meaningful names, this is the introduction to local variable naming. The following global variables, constants, class names, method names and so on are similar, and can also refer to the Ali specification, no more examples

immutability

A variable in Java, which defaults to a variable. If you want to make a variable immutable, you need to prefix the variable name with the keyword final. An immutable variable, also called a constant

If a variable is prefixed with the final modifier, the definition of the variable must be synchronized with data initialization, at least in local variables

Of course, if a final variable is immutable, it means that it cannot be assigned twice. There is no problem in separating the definition of a variable from the assignment

/* Correct, definition is synchronized with assignment */
final int a = 10;
/* Correct, definition separated from assignment */
final int b;
b = 20;
Final variables can only be assigned once */
final int c = 30;
c = 30;
Copy the code

A variable that is defined as immutable and can only be assigned once during use. So, as much as possible, make the definition and assignment synchronized and easy to understand. Constants are often used to represent some kind of immutable data, such as the number of hours in a day

For constants, they are mostly defined globally and exist as attributes of the class. They are named as follows: All letters are uppercase and words are separated by an underscore

It is important to note that it is not recommended to do any abbreviations when naming constants. Try to express the meaning of constant data as much as possible. And for variables, most of the use of the release, can do a certain shorthand

The original type

Earlier, it was mentioned that variables are used to refer to data stored in memory. And data, also must exist type, in order to distinguish, management

In Java, data types are divided into two types: primitive type and reference type. Among them, there are four types and eight types of primitive type. The rest data types are regarded as reference types

Format: Chinese name English name Memory storage (one byte and eight bits binary) Type Default value

Integer types

type The name of the byte The default value
Byte type byte 1 0
Short integer short 2 0
The integer int 4 0
Long integer long 8 0L

Floating point types

type The name of the byte The default value
Single precision float 4 0.0 F
double double 8 0.0 D

Boolean type

type The name of the byte The default value
Boolean boolean controversial false

Character types

type The name of the byte The default value
Character types char 2 ‘\u0000’

These eight data types have their own details. Here is a brief introduction to Boolean and character

In the case of a Boolean, its actual memory footprint is uncertain, but when it’s an array element or a single variable, it takes up different sizes of bytes

For characters, it is assigned using the single quotation mark ” instead of the double quotation mark ”. Also, a character type can receive an integer and be converted to the corresponding character

char a = 122;
char b = 'z';
System.out.println(a);
System.out.println(b);
Copy the code

For more details on data types, refer to Chapter 2 of the JVM Virtual Machine Specification (not recommended for beginners).

Literals refer to data received directly by a variable, not through another variable. For example int a = 10; Int b = a; It’s no longer literal

Integer literal constant whose default type is int; A floating-point number plane constant whose default type is double

int a = Integer.MAX_VALUE;
long b = a + a;
long c = Integer.MAX_VALUE * 2L;
System.out.println(b);
System.out.println(c);
Copy the code

When a long variable receives twice the maximum value of an int. If you receive a literal, you need to cast it, and you will be prompted in the IDE, which involves casting

Of course, if a variable is received out of range, it will also produce unknown output. It’s just that, for literal reception, the IDE can intelligently prompt. All you need to know is that long must have the suffix L when it accepts an integer that exceeds the maximum value of int

For floating point, the same is true, but the suffix is F, because the actual default is Double, which is larger than Float

annotation

In the case of comments, it can make parts of the content invisible to the computer, that is, not compiled as code

So, the actual service object of annotation content, is the developer, is the human, good annotation habit, is the inevitable of team cooperation

For individuals, comments allow them to quickly recall the functional location of that part of the code; For others, through comments, they can also quickly take over the project and do secondary development and maintenance

Like a blog, comments are comments to code. After all, the human brain is small, good annotation style is essential!

Form of comments

In Java, comments come in three forms: single-line comments, multi-line comments, and document comments

For single-line comments //

  • Comment on a single line of content, used in the method body, since // after the line is commented

For multi-line comments /* */

  • Comment multiple lines of content, used in the method body, and all content in // is commented

For documentation comments / */

  • Annotations for classes, properties, and methods, primarily documenting the characteristics or information of the methods, classes, and so on
  • You can generate JavaDoc documentation in HTML format, similar to the official Java API manual

For these three types, there are different application scenarios. Single-line and multi-line comments are similar. If there is too much content, use multi-line comments instead of single-line comments (never use document comments, it is not the norm).

The use of comments should keep a space between the comment symbol and the comment content. However, the comment generation in IDEA cannot be solved. It is recommended to use code templates to define the style of comments

The use of annotations

Below, introduce the use of three kinds of annotations in Java, part of the code excerpted from the JDK source code, temporarily do not need to understand, only for example use

For single-line and multi-line comments, it is easy to understand that they are used in the body of the method to do some interpretation

// ArrayList can be subclassed and given arbitrary behavior, but we can
// still deal with the common case where o is ArrayList precisely
Arraylists can be subclassed or given arbitrary behavior
// But we can still handle the usual case where o is an arraylist
/* Arraylists can be subclassed and given arbitrary behavior, but we can still handle the usual case of o being arraylists */
booleanequal = (o.getClass() == ArrayList.class) ? equalsArrayList((ArrayList<? >) o) : equalsRange((List<? >) o,0, size);
}
Copy the code

The equals variable above, which is more complex, can be explained with single-line or multi-line comments. For better reading experience, consider using multiple single-line comments or a single multi-line comment instead of a single line comment if there are too many items to be commented

Simply put, when a single line requires too much comment, consider multi-line comments instead

Next, the more specific comments, documentation comments, are introduced

/** * Default initial capacity. */
private static final int DEFAULT_CAPACITY = 10;
Copy the code
/** * Returns the number of elements in this list. * *@return the number of elements in this list
  * @returnThe number of elements in this list */
public int size(a) {
    return size;
}
Copy the code

The two examples above illustrate the use of document comments. Documentation comments that apply to a class, its properties, or its methods, and explain or use them

When you use Java’s API manual queries, you can see that it provides the function of a class method, the parameters passed in, the return type, and so on. This is all done based on documentation comments

In the example, @return is followed by a description of the value returned by the method. The corresponding document comment parameters are many, but I won’t repeat them here

With specific commands, documentation comments in Java programs can be extracted into API instruction manuals. In most cases, consideration is given to the use of third-party technology to produce a program instruction manual

summary

The use of comments, ending the paragraph. It mainly introduces the three annotation forms and their application scenarios

One of the document comments, more special, single-line, multi-line comments are complementary. In addition, there are some special annotation parameters

  1. TODO: Functions to be implemented
  2. FIXME: Features to be fixed
  3. XXX: The function needs to be improved

Three special annotation keywords, can be captured by the IDE, display, convenient program maintenance, management

One thing to note is that the content of a comment can appear to be executed, which violates the previous iron law of comments: the content of a comment is invisible to the computer

For example, // \u000a comments are newline, which will be parsed, but the IDE will not find this problem in advance, which involves the character set encoding problem, which will not be covered for now

The content of the notes should be short and frightening. The necessary language refinement can shorten the reading time

Some details

In basic programming, there are certain details that need to be paid attention to. Here, we start with the four primitive types in turn. Of course, a lot of this knowledge, in the computer basic subjects, can be found

Conversion of types

Compatible types can be converted to each other, and the size of compatible types is compared according to their memory space

  1. Automatic implicit conversion: no declaration is required. For example, an int variable accepts a byte variable
  2. Mandatory explicit conversions: Requires declarations such as byte variables that receive int variables

For conversions between primitive data types, it is important to note whether variables or literals are involved

For literals

For example, an integer literal whose default literal type is int receives the integer literal as a byte

byte a = 100;

At this point, an automatic implicit conversion occurs. 100 does not exceed the value of byte and can be converted from int to byte

However, if the integer literal received by byte exceeds the value range, for example, byte a = 200.

Byte a = (byte) 200; byte a = (byte) 200;

The simple idea is that when a byte receives an integer literal of a compatible type, there are two cases

  • Value not exceeding byte: Integer literals are automatically and implicitly converted from int to bytebyte a = 100;
  • Byte value exceeded: Explicit cast must be performedbyte b = (byte) 200;

Based on how literals behave in type conversions, there is a caveat

The default literal is int. If a long variable receives an integer literal that is larger than int and smaller than long, it must have the suffix L and promote the literal to long

The variable

In the case of conversion of variables, default literals of integer and floating point types are not concerned

Any different types of variables, from large to small conversion, must be mandatory declaration, cast

int a = 100;

byte b = (byte) a;

Int is a 32 bit binary and byte is an 8 bit binary

Red solid line: memory storage from small to large conversion, no loss, automatic conversion

Blue dashed line: Memory storage large to small conversion, precision loss, cast

Integer overflow

In casting, there is a confusing problem known as data overflow

The simplest example would be byte a = 400;

The default type of an integer face value is int, and the assigned literal exceeds the value of byte and cannot be automatically converted

At this point, here’s what happens

Understand four concepts

  • Sign bit: In binary, the highest bit exists as a sign bit. 0 is positive and 1 is negative
  • Source code: direct binary representation of data, using decimal 127 as an example, with an octet binary target
    • +127:01111111 Source code
    • -127:11111111 Source code
  • Inverse code: on the basis of the original code, all the inverse, including the highest sign bit
    • +127:10000000 Source code -> Invert
    • -127:00000000 Source code -> invert
  • Complement: On the basis of the inverse code, the binary number is added by 1
    • +127:10000001 take the inverse -> complement
    • -127:00000001 Take the inverse -> complement

Data overflow is composed of binary truncation, symbol bit, source code, inverse code and complement code

Simple understanding: the binary representation of a negative number is the complement of its corresponding positive number

  • The binary of a positive number is its source code representation
  • The binary version of a negative number is the complement representation of its corresponding positive number

The final result of the cast, in the case of byte type, consists of octet binary

If the binary representation of the received data exceeds eight bits, truncate the excess (note the highest sign bit)

Now, the thing to notice here is that the highest bit, the sign bit, a positive number can turn negative when you cut it off, and that’s why you get a negative number when you overflow a positive number, right

If the binary symbol bit is 0, then directly according to the original code, to find the result

If the binary sign bit is 1, it is regarded as the complement code and is pushed back to the original code. According to the corresponding positive number, the negative result is obtained

The true binary representation of a negative number is the complement representation of its corresponding positive number

byte b = (byte) 400;
System.out.println(b);
/* b = -112 -> 10010000; /* b = -112 -> 10010000; 01110000 -> inverse 10001111 -> complement 10010000
Copy the code

Floating-point operation

Boolean memory

Nature of characters

The operator

Arithmetic operator

  • Plus, minus, plus (+, -, *)
    • It’s like +, -, and * in mathematics
  • Division sign (/)
    • When dividing an integer, only the integer is retained and the rest is discarded
    • Divide integer and floating point with decimal
  • Mod (%)
    • Integer mod, the result is integer representation
    • Integer, floating point mod, the result is a floating point representation
  • Increase, decrease (++, –)
    • If it is on the left, the variable itself is calculated first
    • If located on the right side, first participate in the operation of the expression

Logical operator

  • Logic and, or, (&, |,!)
    • The result is true if the results of both: and: expressions are true
    • Or: if both results are false, the result is false
    • Non: Inverts the result of the expression
  • Short circuit and, or, &&, | |)
    • When the left expression can get the result, the right side is directly skipped and no longer involved in the operation

The short-circuited content does not participate in the calculation, does not mean that it does not participate in the compilation, will still throw an exception

Logic and, or, not, can also be called bit and, bit or, bit not

An operator

If the actual value, rather than a Boolean value, is compared, it is different from the short circuit and, or, or

The bit and, or, and not, are the corresponding binary bits to compare, pay attention to the positive and negative by the bit

Bitwise and & : the corresponding binary is 1 if both are 1; otherwise, it is 0

Bitwise or | : corresponding binary At the same time is 0, 0, or 1

By bit not ~ : the corresponding binary 0 is 1,1 is 0

Bitwise exclusivity or ^ : The corresponding binary is 1 for the same and 0 for the different

// If both bits and '&' : are 1, it is 1; otherwise, it is 0
System.out.println(12 & 3);
/* 12:00 001100 3:00000011 ------------ : 00000000 12&3 Result: 0 */
System.out.println(13 & 4);
/* 13:00 001101 4:00000100 ------------ : 00000100 13&4 Result: 4 */

/ / bitwise or ` | ` : at the same time is 0, 0, or 1
System.out.println(14 | 3);
/ * then 001110, 3:00000011 -- -- -- -- -- -- -- -- -- -- -- -- : 00001111 | 3 results: 14 15 * /

// not '~' by bit: 0 is 1,1 is 0
System.out.println(~3);
/* 3:00000000 00000000 00000000 00000011 ------------ 11111111 11111111 11111100 Binary negative form, can be reversed to the corresponding positive number, then the actual negative positive result: 00000000 00000000 00000000 00000100 (+ 4) The result of -4 ~3 is -4 */

// By bit xOR ^ : 0 for the same, 1 for the different
System.out.println(7 ^ 3);
/* 7:00000000 00000000 00000111 3:00000000 00000000 00000000 0000011 ------------ : 00000000 00000000 00000100 7^3 00000000 00000100 7^3 // Source code 16:00 000000 00000000 00000000 00010000 // Source code 7:00 000000 00000000 00000000 00000111 00000000 00000000 00000000 00010111 */
Copy the code

Displacement operator

  • Shift to the left<<
    • The binary sign bit is moved to the left, and the low zero is filled
  • Moves to the right>>
    • The binary sign bit moves to the right, and the positive number fills the high zero, and the negative number fills the high one
  • Unsigned right shift>>>
    • The binary sign bit is moved to the right, and the positive and negative digits are filled with zeros
/ / shift to the left
System.out.println(10 << 2);
/* Binary of 10:00001010 Shift two digits left: 00101000 10 Shift two digits left: 40 */

/ / moves to the right
System.out.println(10 >> 2);
/* Binary 10:00001010:00000010 10:2 */

// Unsigned right shift
System.out.println(-3 >>> 2);
/* 3 binary: 00000000 00000000 00000000 00000011 11111111 11111111 11111111 -3 unsigned right shift two: 0011111111 11111111 11111111 -3 >>> 2 00111111 11111111 11111111 (+ 1073741823) The unsigned right shift of a negative number is equivalent to the right shift of the corresponding positive number's complement, and the high-order zero complement */
Copy the code

Note that the default integer value is int, which is a four-byte, 32-bit binary

If the unsigned right shift of a negative number occurs in the case of a large number, note the memory bytes of the current number type, and the corresponding binary bits

Ternary operator

Writing method: expression? Branch 1 is satisfied: Branch 2 is not satisfied

It can be nested, but frequent use is not recommended for readability

Operators have a priority for execution and can be modified and controlled most of the time using ()

Process control

An array of

An array of concepts

Array: a fixed – length contiguous array of data of the same type

Arrays are reference data types, and reference data types must be created with the keyword new

There are three types of array declarations. Take an int array as an example

/* Determine the length of the array, declare and assign */
int[] array1 = new int[3];
/* Declare and assign, and determine the length of the array */ from the assigned data
int[] array2 = new int[] {1.2.3};
/* * * * * * * * * * * * * *
int[] array3 = {1.2.3};
Copy the code

Once the type and length of an array are determined, they cannot be changed, which needs to be distinguished from arrays in other languages

Multidimensional array

Array, there is a one-dimensional array, two-dimensional array, and so on, more than two-dimensional array, collectively called multidimensional array

Essentially, a multidimensional array can still be viewed as a one-dimensional array

The simple way to think about it is, you have three elements in a one-dimensional array, three arrays, and you treat the array type as the elements in the array

Stack analysis

Memory analysis of array storage: stack memory analysis

Arrays are reference types and are stored differently in memory than primitive types

The simple understanding is that an array has two memory Spaces, one in the stack and the other in the heap

  • Stack memory: The actual reference address of heap memory
  • Heap memory: Stores the actual data

Primitive type variable names, data contents are stored in the stack memory

The actual data for the reference type is stored in the heap memory and is pointed to by the variable name

The above image is referenced from Rust, here

As you can see, the array data is stored in heap memory (block 2), and the variable names point to the actual heap memory addresses

When arrays of the same type with different lengths are assigned to each other, you only need to change the pointing address

If a heap memory is no longer pointed to by the stack memory, the heap memory is automatically released and reclaimed by the VM

function

A function, also called a method, is used to extract and encapsulate a piece of functional code

composition

public static void main(String[] args) {} modifier returns value Function name (argument list) {function body}Copy the code

A standard function consists of the following parts

  • Modifiers: indicate different purposes, for examplepublic,static
  • Return value type: Specifies the return value type of the functionvoid
  • Function name: The name of a function
  • Parameter list: Specifies the parameters that can be received when the function is called. They can be primitive types or reference types
  • Function body: the concrete block of code in a function
  • Return value: the result of function execution

Parameter passing

Several arguments of any type can be passed simultaneously during a function call

For the parameters passed in, there are also two types: primitive type and reference type

Integers, floating-point numbers, characters, or arrays of reference types, custom classes, are all acceptable

It is worth noting that in Java, only value passing exists in function argument passing

Value passing: When a parameter is passed, the parameter receives a copy of the actual data of the argument

Pass by reference: When a parameter is passed, the parameter receives a copy of the address referenced to the argument

Parameter passing in Java is very confusing, and Java officially defines that only value passing exists in Java

Java is all about value passing, except that a reference to an object is passed to a method as a value, i.e. by reference in value passing

Value passing example (primitive type) :

public static void main(String[] args) {
    int a = 10;
    int b = 20;
    set(a, b);
    System.out.println("= = = = =");
    System.out.println(a);
    System.out.println(b);
    /* 20, 10, =====, 10, 20 */
}

public static void set(int a, int b) {
    a = 20;
    b = 10;
    System.out.println(a);
    System.out.println(b);
}
Copy the code

Value passing example (reference type) :

public static void main(String[] args) {
    int[] ints = {1.2};
    System.out.println(Arrays.toString(ints));
    set(ints);
    System.out.println(Arrays.toString(ints));
    /* [1, 2], [2, 2] */
}

public static void set(int[] array) {
    array[0] = 2;
}
Copy the code

In both of the above examples, the actual parameter of the primitive type is not affected by the parameter change and is not considered

When passing a reference parameter, the argument is changed as the parameter is changed, which seems to be inconsistent with the definition of pass-by-value

When a reference type is passed, the copy of the copy is the reference address of the object

In simple terms, a parameter gets a copy of the argument, indirectly gets the address of the reference, and modifies the data in the heap

The reference type passed by value, at this point, is very similar to passing by reference

The difference is that in real reference passing, the parameter directly gets the address of the reference and can make changes to that address

The figure above is a simple description of passing value and passing by reference. In the real sense of passing by reference, you can refer to Rust language to explain clearly

In value passing, reference object 2 only obtains a copy of the heap memory address, and only has access to and modification of the heap memory data

In reference passing, reference object 2 directly obtains root permission of the heap memory and can change its reference address directly

For now, pass by value is subdivided into pass by value and pass by reference

Just two things to keep in mind

  • Value is passed, and parameters can change the content
  • The reference is passed, and the parameter can modify the reference address

In Java, only value passing exists, and only copies of reference addresses are passed, and only in-memory data can be manipulated

Variable length parameter

When the number of arguments passed to a function is uncertain, you can define it with variable-length arguments, such as sorting methods

The following code is a use case for variable-length parameters

public static void main(String[] args) {
    get(12.12.23.34.45.34.23);
}

public static void get(int. a) {
    System.out.println(Arrays.toString(a));
}
Copy the code

For the use of variable-length parameters, two points need to be noted:

  1. Variable-length arguments must be placed at the end of the argument list
  2. The argument list of a function can have only one variable – length argument

Method variable length parameters, is essentially the embodiment of an array, it is recommended to use an array object to pass parameters, also easier to understand

public void get(int[] a, String[] b) {}
Copy the code

In the argument list of a function, two variable-length arguments of different types cannot coexist, as an array can

overloading

Method overloading occurs when there are multiple methods of the same name in a class

Function overloading: Overloading is only the same method name. Parameter list, access modifier, return value type can be different

The following is an example code for method overloading

public static void main(String[] args) {
    get((byte) 1);
    Integer integer = get((short) 1);
    get(1);
    get((long) 1);
}

private static void get(byte. a) {
    System.out.println("byte");
}

public static Integer get(short. a) {
    System.out.println("short");
    return 0;
}

public static void get(int. a) {
    System.out.println("int");
}

public static void get(long. a) {
    System.out.println("long");
}
Copy the code

It is important to note that no overloaded function can exist with the same argument list

Simple to understand, the function name is the same, the argument list is different

Recursive calls

Recursive functions, simply understood, call their own functions

The following is a recursive call to the function, taking the factorial

public static void main(String[] args) {
    System.out.println(get(5));
}

public static int get(int a) {
    if (a == 0) {
        return 1;
    } else {
        return a * get(a - 1); }}Copy the code

Complete the following steps

  • get(5) = 5 * get(4)
  • get(4) = 4 * get(3)
  • get(3) = 3 * get(2)
  • get(2) = 2 * get(1)
  • get(1) = 1 * get(0)
  • get(0) = 1

The final result of get(5) is 120

The last

The next day, I’ll be writing about classes and objects, probably a lot more than this one. The important classes String and Integer will not be singled out as a separate article, but will only exist as a three-level heading. Of course, for the cache pool, equales rewrite, these important parts, will not be ignored, you can rest assured

Plus, my GitHub repository already has this written down.

Finally, there is a new internship work of the old brothers, push, push, push