[Core Java] 01 Java basics

Core Java I-Java basics

Java terminology

abbreviation English Explanation
JDK Java Development Kit The software needed to develop Java programs, including JRE and development tools
JRE Java Runtime Environment Used to develop programs. The software that users need to run Java programs, including JVM and core class libraries
JVM Java Virtual Machine Java virtual machine is the running environment of Java programs, used to achieve cross-platform
Java SE Standard Edition Java platform for desktop or simple server applications
Java EE Enterprise Edition Java platform for complex server applications
Java ME Micro Edition Java platform for mobile phones and other small devices

Java data types

Java type of data can be divided 基本数据类型and引用数据类型

Basic data types: char byte shrot int long float double boolean

Reference data type: object, array...

Call method

Java always call by value, that is, call by value ( call by ...refer to call by...).

The formal parameters obtained by all methods are a copy of the actual parameters-which results in no method being able to modify the references of external variables.

Basic data type

Java is a strongly typed language. In Java, there are 8 primitive types.

Four integer types

Types of store range
byte 1 byte -128 ~ 127
short 2 bytes -32768 ~ 32767
int 4 bytes -2147483648 ~2147483647
long 8 bytes -9223372036854775808 ~ 9223372036854775807

Unlike C/C++, the scope of Java integer types has nothing to do with the host environment

The integer value is the inttype by default , and the use longtype needs to be Lsuffixed.

In order to enhance the legibility of numbers, we can also underline the number literals:

For example 1_000_000, 1_000_______000and 1000000both represent 100w.

In addition, binary uses 0b/ 0Bprefix, octal uses 0prefix, and hexadecimal uses 0x/ 0Xprefix.

Two floating point types

Types of store range
float 4 bytes ± 3.40282347E + 38F
double 8 bytes ± 1.79769313486231570E + 308

Floating point numbers are doubletype by default , and the use floattype needs to be added f/ Fsuffixed. (The doubletype also has a suffix d/ D)

Java also allows the use of scientific notation, such as 103E5representation 10300000. There is also hexadecimal scientific notation 0x103p5.

In Java, there are three special floating-point values ​​when floating-point calculations overflow (1d/0) or errors (0d/0):

Double.POSITIVE_INFINITY(Positive infinity, defined as 1d/0)

Double.NEGATIVE_INFINITY(Negative infinity, defined as -1d/0)

Double.NaN(Not a number, defined as 0d/0)

If you want to verify whether a value is infinite or not a number, you should use the method in the Double wrapper class:

boolean isNaN(double v);
boolean isFinite(double d);
boolean isInfinite(double v);

About isNaNthis method:

public static boolean isNaN(double v) {
    
    
    return (v != v);
    // Java 认为任意两个 not a number 都是不相等的
}

Regarding the calculation of floating-point numbers, some computers use 80-bit floating-point registers, and temporarily store the calculation results in the 80-bit floating-point registers during calculations, and then truncated two bytes to 64 bits-this has better calculation accuracy . But for some machines that do not use this kind of calculation method, the calculation results will be slightly different.

Java pursues portability, that is, the results of operations should be the same on different machines, but the above point obviously violates portability. In the very early standard, any intermediate process of floating-point calculations should be truncated to ensure portability, but it has encountered a lot of opposition. Under the pressure of all parties, Java gave a compromise solution.

By default, more precise calculation methods are allowed, but strictfpvariables modified with keywords will be strictly truncated during operations.

Character type

Types of store
char 2 bytes

Unicode given UTF-16

The char type in Java uses the UTF-16 convention to describe a code unit, that is, Java's char uses the UTF-16 encoding method to encode Unicode characters.

Unicode is a standard and agreement. It is a character set. It describes the correspondence between each character it contains and a unique value corresponding to this character, just like one hashmap<int, char>, each character has a unique key.

UTF-16 is a standard encoding method for Unicode (or an implementation of Unicode), which describes the mapping of Unicode characters to a code.

Regarding coding, there are two terms:

Code point ( Code Point ): Unicode implemented, the unique code corresponding to each character code called a dot.

Code means ( Code Unit ): implemented in Unicode, each code point may represent one or more code units, e.g., UTF-8 code unit will be described by one byte, UTF-16 is used and two bytes .

UTF-16 is a collection of relationships from characters to code points, and is a very flexible encoding method with variable length.

Why do we not directly use the Unicode standard but re-encode Unicode?

We just compared the Unicode standard to one hashmap<int, char>. Just imagine if the number of characters in this character set exceeds 65535, then we have to replace int with long (we use C/C++ to describe the problem) to prevent overflow.

This is obviously unfair to ASCII. People originally only need one byte to save, but now they are forced to use two or even four bytes, which greatly wastes bandwidth and storage space.

So UTF-8 appeared, and it realized the matter of "using different numbers of code units to describe different Unicode characters" through a very clever encoding method. For example,'A' uses a code unit in UTF-8 (ie One byte) description, while a Chinese character is described using two to three code units.

In addition, this article is good . It is clearer and more detailed than what I explained. It also gives the specific encoding methods of UTF-8 and UTF-16.

Boolean type

Types of store range
boolean 1 byte true or false

Unlike C/C++, in Java, there is no implicit conversion from a non-Boolean type to a Boolean type.

Array

Array initialization

Declare an array: int[] arr;(This style can also be used int arr[];).

int[] arr;
int arr[];

Initialize the array:

Boolean arrays will be initialized to false, numeric arrays to 0, and object arrays to null.

new int[10];
new int[]{
    
    1, 2, 3, 4};

Apply for a memory space, which will arrpoint to this memory:

int[] arr = new int[10];

Short form of declaring array and initialization:

int[] arr = {
    
    1, 2, 3, 4};

Array copy

Static methods in Arrays:

static int[] copyOf(int[] original, int newLength);

E.g:

int[] arr2 = Arrays.copyOf(arr1, arr1.length);

variable

variable name

Java allows the use of a lot of Unicode characters as a variable name, if you want to know which characters can be used as named by Characterthe class isJavaldentifierStartand isJavaldentifierPartdetecting methods.

! Note that $it is legal as a variable name, but don't do this, because Java generates internal class bytecode $as part of the file name, which may cause some troublesome problems.

statement

In C/C++, it extern int a;is called a declaration and int a = 10;is called a definition .

In Java, there is no distinction between declaration and definition, and uninitialized variables are not allowed to be used , which is a compile-time error.

constant

By finalindicating constants, for example final int a = 10;. Constants can only be assigned once and cannot be changed afterwards.

In addition, finalmethods and classes can be modified to indicate "final" and cannot be overridden or inherited.

final class className {
    
    
    // ...
    final public void method() {
    
    
        // ...
    }
}

!!! Note that finalunlike in C++ const, it focuses on the data directly saved by the variable. For reference types (he is a pointer), the finaladdress change is prohibited, but the data at the address is not prohibited.

Reference data type

Classes and objects, will be discussed in object-oriented

Java type conversion

Implicit conversion

Binary operation

When performing operations, the two operands are converted to the same type, and the conversion to higher precision is followed.

E.g:

int + double → double + double

int + long → long + long

int long float double
→ → → → → → → →
if 存在 double
	则另一个转换为 double
else if 存在 float
	则另一个转换为 float
else if 存在 long
	则另一个转换为 long
else 
	两操作数一起转换为 int

In other cases, implicit conversions are rare. Java is more strict than C/C++. For example, long is not implicitly converted to int.

Explicit conversion

It is exactly the same as C/C++ style type conversion.

Java IO

Read input

Scanner

The Scanner object is used to read user input, or read files.

structure:

Scanner(InputStream source)

Input data:

String next(); 
// 读入下一个字符串

int nextInt(); 
// 读入下一个整行
// ... nextDouble, nextFloat, nextBoolean...

Determine whether there is the next data:

boolean hasNext(); 
// 下一个读入的数据是否可以认为是字符串

boolean hasNextInt(); 
// 下一个读入的数据是否可以认为是 int
// ... hasNextDouble, hasNextFloat, hasNextBoolean...

Console

The Console object can be used to read data that is not echoed, such as passwords.

There is only a single instance of this class, which System.console()is returned by the method.

Console console = System.console();

Common methods:

char[] readPassword([String fmt, ... args]);
// 读取用户输入,以回车结束,不回显

char[] readPassword();
// 提供一个可格式化的字符串提示

Formatted output

Regarding output, we usually call methods to manipulate System.outobjects, which are actually PrintWriterinstances of classes and PrintWritercan also be used for file writing.

C-style formatted output:

PrintWriter printf(String format, Object... args);

Common output methods:

void println(type param);

void print(type param);

Format string:

static String format(String format, Object... args);
// 将字符串格式化后返回而不输出

! Note that %syou can format any object, and Formattablethe formatTo()method of the interface will be called in its implementation , otherwise the toString()method will be called .

File IO

Scanner

Construct a Scanner for scanning files:

Scanner(Path source [, String charsetName]);
Scanner(File source [, String charsetName]);

Path (Path is an interface type) and File objects can be returned by Paths.get()methods and Fileconstructors respectively .

Regarding the path, if we want to use a relative path, we must first know the current working path, which is located in the working directory of the environment where the Java program is started.

We can also String dir = System.getProperty("user.dir");get this path through without the end of the path \.

PrintWriter

The aforementioned System.outis PrintWriteran example, for file reading and writing, we can directly construct an PrintWriterobject.

PrintWriter(String fileName, String csn);
// 指定文件名与字符集

PrintWriter(File file, String csn);
// 指定文件对象与字符集

Then you can use common methods to output the file.

! Note that after the PrintWirter object is constructed, the target file will be rewritten. If you want to add content to the file, you should use it FileWriter.

FileWriter

FileWriter((File file | String filename) [, boolean append]);
// 第二个可选参数决定了追加 or 重写

This class implements the Writerinterface:

void write(String str);

Writer append(CharSequence csq);

Java flow control

Block scope in Java

Unlike C++, Java does not allow redefining variables outside the block within the block.

The following Java code cannot be compiled:

//...

int var;
{
    
    
    int var;
    //...
}

//...

Condition, loop

Exactly the same as C/C++.

for each loop

For an array or a Iterablecollection that implements an interface, we can use the for each loop to traverse the collection.

for (Type e : collention){
    
    
    //...
}

switch statement

It is exactly the same as the switch of C/C++.

However, Java provides switch statements with lambda expressions, for example:

switch(/* expression */) {
    
    
    case /* constant */ -> {
    
    
        //...
    }
    case /* constant */-> {
    
    
        //...
    }
    default -> {
    
    
        //...
    }    
}

Labeled break

Although the goto statement has been criticized many times, it is unexpectedly concise when it breaks out of the deep loop.

Java certainly does not introduce the goto statement, but it provides a labeled break - as an alternative to goto to jump out of the deep loop.

The usage is roughly like this:

loop1:
while(/* condition */) {
    
    
    loop2:
    for(/* expression */) {
    
    
        loop3:
        for(/* expression */) {
    
    
            //...
            if(/* condition */) {
    
    
                break loop2;
                // 将会跳出第二层循环
            }
            //...
        }
    }
}

In addition, the labeled break can implement some of the functions of goto.

For example, the following code is legal:

//...

lable:
{
    
    
    //...
    if(/* condition */) {
    
    
        break lable;
    }
}

//...

You can jump out to the outer block, but you are not allowed to jump into the inner block.

Java command line parameters

The string array parameter of the main method will receive the parameters from the command line.

java {
    
    class} {
    
    params}

The values ​​in the string array will come from the above {params}, with spaces as separators.

Java program running

Java project structure

Project → Module → Package → Class

Project module package class

Package is used to classify classes (details about packages will be expanded later).

definition:

Indicates which package the current class is in

package {
    
    packageName};

Import:

import {
    
    packageName}

In Java, .javathere is one and only one publicclass in each file, and this class is the only interface provided by the class.

Java mainstarts to run the program through the main method of a certain class .

Compile

javac *.java

java MainClass

*.javaSource code, after javac.execompiled into bytecode java file, then java.exerun.

javac.exeIs the compiler. java.exeIt is an interpreter.

jshell

Enter jshellrun in the shell jshell.

jshellIt is an immediate interaction environment with Java.

RAM

Java's memory is divided into five areas:

Stack, heap, method area, local method stack, register area.

When the method is called, the method in the method area will be copied to the stack for execution.

Java IDE - intelliJ IDEA

Commonly used shortcut keys

key Description
Ctrl + Alt + Space Call up code completion
Ctrl + Shift + 方向 Move the entire line
Ctrl + D Copy entire line
Ctrl + Y Delete row
Ctrl + W Extended selection
Ctrl + Shift + W Cancel extension selection
Ctrl + Alt + L Format code
Shift + Alt Multiple choice
鼠标中键 Column selection
Shift + Alt + Insert Toggle row selection and column selection
Shift + F6 Refactor
Alt + Enter Import the package, automatically correct the code
Ctrl + Alt + M Extraction method

Guess you like

Origin blog.csdn.net/qq_16181837/article/details/107315921