Java basic syntax-B2

Basic grammar (1)

The basic structure of the program

The basic form of Java programs

Java language is an object-oriented language. Java programs mainly exist in the form of classes, also called Class, and classes are also the smallest program units of Java programs.

Java programs require that all execution statements and methods must be placed in a class.

The simplest Java program:

class Hello {
}

In the above Hello class, it is just a definition of an empty class, without any class components, it can be compiled, but it will report an error when it is executed.

Because it stipulates that if a class needs to be directly interpreted and executed by the interpreter, it needs to include the main () program entry method, and it must be decorated with public static, the return value type must also be set to void, and the parameter of this method must also be String [] args String array.

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

In the future, even if our Java program gradually becomes more complicated, for a Java program, you only need to have a main method as an "entrance" in a class, and other classes will be directly or indirectly by the main () method. transfer.

Java program operating mechanism

There are two types of computer high-level languages ​​according to program execution methods: compiled and interpreted.

Compilation type:
There are special compilers for different operating systems, the source code is directly compiled into machine code executed by the current system hardware, and then packaged into a program format that the current system can recognize and execute. The generated executable program can run on a specific system platform without being restricted by the development environment. If you want to execute on different system platforms, you need to put the source code directly into the compiler in different system platforms and compile it again before it can be executed.
Common compiled languages ​​are: C, C ++, Swift, Kotlin, Objective-C, etc.

Interpretation type:
a special interpreter that interprets the source program line by line into the machine code of the current system platform and executes it immediately. An interpreted language requires a compilation every time it is executed, which is equivalent to mixing the compilation and interpretation processes in a compiled language and completing them at the same time. Therefore, its efficiency is relatively low, and it cannot run independently from the interpreter. But its advantage is that cross-platform operation is particularly simple, as long as there is a relevant interpreter on the corresponding platform.
Common interpreted languages ​​are: JavaScript, Ruby, Python, etc.

JVM

The Java language is very special, and the Java source program will also be compiled, but after compilation, it will not generate machine code for a specific platform, but will generate a platform-independent bytecode file. However, the bytecode file cannot be executed. If you want to execute it, you need to use the Java interpreter to interpret it. Therefore, the execution process of the Java program must go through two steps: first compile and then explain. It can be considered that the Java language is both a compiled language and an interpreted language.

working process:

  1. The Java source file (xxx.java) is compiled through the javac instruction to obtain the bytecode file (xxx.class).

  2. The bytecode file is interpreted and executed by the java command, and the bytecode is processed by the JVM (interpreter) to generate machine code that can be directly executed by the computer, so that the java program can be correctly run.

Programming specification

Java source file naming rules

  • The extension of the source file of the Java program is: xxx.java

  • If the class is decorated with public, the file name must be the same as the class name. In a Java source file, you can define multiple classes, which are completely independent of each other, but there can only be one public decorated class in a class.

  • In general, it is recommended that a Java source file only define a Java class. Moreover, it is best that the source file name matches the class name modified by public.

Java case

The Java language is strictly case sensitive and case sensitive.

The "keyword" words specified in the Java language are all lowercase.

Problems with spaces in the path

When naming a folder, there must be no spaces in the folder name. (Remember !!! Remember !!! Remember !!!)

main () method issue

A Java program, if you want to run it, must include the main () method, the specific format is as follows:

public static void main(String[] args) {
  // 需要执行的代码语句
  System.out.println("hello lucaswangdev");
}

Identifier

Common separators:

In the Java language, the common separators are: semicolon, curly brackets, square brackets, parentheses, spaces, dots, etc.

semicolon

When writing code, the end of each sentence needs to be marked with a semicolon.

System.out.println("每一句代码,都是用分号来结束的");

curly braces

Curly braces are mainly used to define a code block. The code block refers to the use of the "{" symbol as the beginning and the "}" symbol as the end.

The segment code is logically a whole.

{
  	System.out.println("I");
    System.out.println("Love");
    System.out.println("Java");
}

Square brackets

Square brackets are mainly used to access array elements, often followed by array variable names. The square brackets mainly specify the index values ​​of array elements.

String[] names = {"张三", "李四", "王五"};
System.out.println(names[1]); // 李四

Parentheses

  • When defining a method, it can be used to declare all formal parameters.

    public void setName(String name){...}
    
  • When calling a method, it can be used to pass actual parameters.

    setName("jiajia");
    
  • When calculating, increase the priority of calculation.

    int num = 2 * (3 + 5);
    
  • Cast the type.

    int num2 = (int) 3.14;
    

Space

Spaces are mainly used to separate different parts of a sentence.

Dot

The dot, generally used as a class / object and its members (including the separator between member variables, methods, and inner classes), indicates that a specified member of a class or an instance is called.

Identifier naming rules

Identifiers are mainly used to name variables, classes and methods in programs. Java language identifiers must start with letters, underscores, and dollar signs, followed by any number of letters, numbers, underscores, and dollar signs.

When writing, pay special attention to capitalization.

The specific writing rules are as follows:

  1. Can be composed of letters, numbers, underscores, and dollar signs, which cannot start with a number.
  2. Cannot be Java keywords and reserved words, but can contain keywords and reserved words.
  3. Cannot contain spaces.
  4. Can only contain dollar signs, not other special symbols such as @ , # ,%, etc.

Agreement:

  1. Identifiers must match semantic information

  2. All letters in the package name are lowercase

  3. Each first letter of the class name is uppercase and other lowercase

  4. Variables and methods First word lowercase Second start capital

  5. All capital letters of the constant

Keyword

Keywords in Java are words with special purposes, also called keywords. All keywords are lowercase, so pay special attention when writing. In addition, true, false and null are not keywords, but special direct quantities.

image-20200409171817681

type of data

Data type classification

The Java language is a strongly typed language, and strongly typed mainly refers to:

  • All variables must be declared before use;

  • The specified variable can only be accessed with a value that matches the type.

Each variable and each expression has been determined to have a corresponding type at compile time. Types can limit the values ​​that a variable can be assigned, and can limit the values ​​that an expression can produce, which can limit the operations and the meaning of operations that can be performed on these values.

Syntax format:

type varName [= varValue];

int age;
String name = "lucaswangdev";

Java data types supported are mainly two: ** ** basic data types and reference data types .

Basic data types

how to use?

  1. When you represent an integer, use int (age, quantity of goods, etc.), if it is a decimal, use double (commodity price, height, etc.).
  2. When you represent the time value, file, memory size (the size of the program in bytes), use long, and use long for those larger data.
  3. If I / O operations and network programming involve content transfer or encoding conversion, use byte.
  4. If in logical judgment, you need to use boolean value as the judgment condition, either true or false.
  5. When you need to deal with Chinese, use char.

image-20200409174315442

Integer

Integer types mainly refer to the following four types: byte, short, int, and long.

[Note] When specifying a long integer, you need to add the letter L after the integer value, which can also be lowercase l.

// 100为byte类型
byte num = 100;

// 777L为long类型
long bigNumber = 777L;

What is a variable? What is the use of variables?

The essence of programming is to access and modify data in memory. The data used by the program is stored in memory, and developers need a way to access or modify the data in memory.

What happens when data overflows?

    public static void main(String[] args) {
        // 最大值和最小值
         int max = 2147483647;
         int min = -2147483647;
        // 最大值 +1
         System.out.println(max + 1);
        // 最小值 -1
         System.out.println(min - 1);
    }
// 解决方法1:		
public static void main(String[] args) {
    // 最大值和最小值
    long max = 2147483647;
    long min = -2147483647;
    // 最大值 +1
    System.out.println(max + 1);
    // 最小值 -1
    System.out.println(min - 1);
}
// 解决方法2:		
public static void main(String[] args) {
    // 最大值和最小值
    int max = 2147483647;
    int min = -2147483647;
    // 最大值 +1
    System.out.println(max + 1L);
    // 最小值 -1
    System.out.println(min - 1L);
}

Character

Character type, generally used to represent a single character, and need to be enclosed by a pair of single quotes ('').

Three representations of character types:

  • Specify a single character, such as 'A', '1', 'i', etc.
  • Specify escape characters, such as '\ n', '\ r', etc.
  • Specify the Unicode value, such as '\ uXXX', etc.

Common escape characters:

  • \ b backspace
  • \ f form feed
  • \ n Wrap
  • \ r Enter
  • \ t next tab
  • \ ' apostrophe'
  • \ " Double quotes"

Floating point

There are two types of floating point in Java: float and double.

Double

The floating-point type of the Java language is double by default. You can also add d or D after a floating-point number (but it is not necessary).

Double is a double-precision floating-point number. A double-type numeric value occupies 8 bytes and 64 bits.

Double type value, the first bit is the sign bit, the next 11 bits represent the exponent, and the next 52 bits represent the mantissa.

Float

float is a single-precision floating-point number, and a numeric value of type float takes 4 bytes and 32 bits.

For float type values, the first bit is the sign bit, the next 8 bits represent the exponent, and the next 23 bits represent the mantissa.

If you want to use a floating-point number as a float type, you need to add f or F after it.

Boolean

Boolean, also called boolean, has only two values: true and false. The value or variable of boolean type is mainly used as a flag for process control, and is commonly used in the following processes:

  • if conditional flow control statement
  • while loop flow control statement
  • do… while loop control statement
  • for loop flow control statement
  • Trinocular operation

Basic data type conversion

Automatic type conversion

If the system supports assigning values ​​of one basic type directly to variables of another basic type, this method is automatic type conversion.

For example, there are two bottles, and the water filled in the small bottle is introduced into the large empty bottle, and will not overflow.

image-20200409235205085

int ii = 88;
// int ii 转float
float ff = ii;

byte bb = 5;
// byte转char会报错
char cc = bb;

// byte可以转换成double,输出 5.0
double dd = bb;
System.out.println(dd);

note:

Any basic type value + string value will be automatically converted to a string type (reference data type).

// 不管是什么数据类型,只要跟字符串相连,最终都变成字符串
String str = 6.66f + "";
System.out.println(str);
// 从左往右运算,打印 6Java
System.out.println(1 + 2 + 3 + "Java");
// 从左往右运算,全都转成字符串了,打印 Java123
System.out.println("Java" + 1 + 2 + 3);

Automatic conversion :

// 一个整数,默认就是 int 类型
// 一个浮点数,默认就是 double 类型

// 左边是 long 类型,右边是默认的 int 类型,左右不一样
// 等号代表赋值,将右侧的int常量,交给左侧的long变量进行存储
// int -> long,符合了数据范围从小到大的要求
// 这一行代码发生了自动类型转换。
long num1 = 100;
System.out.println(num1);
System.out.println(Utils.getType(num1)); //class java.lang.Long

// 100 // 左边是double类型,右边是float类型,左右不一样
// float -> double,符合从小到大的规则
// 也发生了自动类型转换
double num2 = 2.5F;
System.out.println(num2); // 2.5
System.out.println(Utils.getType(num2)); //class java.lang.Double

// 左边是float类型,右边是long类型,左右不一样
// long --> float,范围是float更大一些,符合从 小到大的规则
float num3 = 30L;
System.out.println(num3); // 30.0
System.out.println(Utils.getType(num3)); // class java.lang.Float

Type conversion

Forced conversion, similar to directing water from a large bottle into an empty small bottle, will cause overflow and data loss.

image-20200409235534660

Mandatory conversion:

//左边是int类型,右边是long类型,不一样
//long --> int,不是从小到大
//不能发生自动类型转换!
//格式:范围小的类型 范围小的变量名 = (范围小的类型) 原本范围大的数据;
int num = (int) 100L;
System.out.println(num);

// long强制转换成为int类型
int num2 = (int) 6000000000L;
System.out.println(num2);// 1705032704

// double --> int,强制类型转换
int num3 = (int) 3.99; // 3,这并不是四舍五入,所有的小数位都会被舍弃掉
System.out.println(num3);

// 这是一个字符型变量,里面是大写字母A
char c1 = 'A'; // 66,也就是大写字母A被当做65进行处理
System.out.println(c1 + 1);
// 计算机的底层会用一个数字(二进制)来代表字符A, 就是65
// 一旦char类型进行了数学运算,那么字符就会按照一 定的规则翻译成为一个数字

byte num4 = 40; // 注意!右侧的数值大小不能超过 左侧的类型范围
byte num5 = 50;
// byte + byte --> int + int --> int
int result1 = num4 + num5;
System.out.println(result1); // 90

short num6 = 60;
// byte + short --> int + int --> int
// int强制转换为short:注意必须保证逻辑上真实大小 本来就没有超过short范围,否则会发生数据溢出
short result2 = (short) (num4 + num6);
System.out.println(result2); // 100

Type judgment

9 pre-defined basic types of Class objects, 8 basic types and void, these are created by the Java virtual machine and have the same name.

//public native boolean isPrimitive();

System.out.println(byte.class.isPrimitive()); // true
System.out.println(short.class.isPrimitive());// true
System.out.println(int.class.isPrimitive());// true
System.out.println(long.class.isPrimitive());// true
System.out.println(float.class.isPrimitive());// true
System.out.println(double.class.isPrimitive());// true
System.out.println(char.class.isPrimitive());// true
System.out.println(boolean.class.isPrimitive());// true
System.out.println(void.class.isPrimitive());

Type judgment method:

//获取变量类型方法
public static String getType(Object object){
    return object.getClass().toString();
}

Operator

Arithmetic operator

Arithmetic operators are mainly basic mathematical operations: addition, subtraction, multiplication, division and remainder, etc.

// 加法
int a = 11;
int b = 12;
int sum = a + b;

//减法
int c = 15;
int d = 10;
int sub = c - d;

// 乘法
int e = 2;
int f = 3;
int multiply = e * f;

// 除法
int g = 18;
int h = 9;
int div = g / h;
System.out.println("div = " +div);

double i = 3.0;
double j = g / i;
System.out.println("j = " + j);

//如果除数是0.0,则得到正无穷大, Infinity
//如果除数是-0.0,则得到负无穷大, -Infinity
double k = g / 0.0;
System.out.println("k = " + k); // k = Infinity

// java.lang.ArithmeticException: / by zero
//int l = g / 0;
//System.out.println("l = " + l);

// 取余
// 前者除以后者,得到一个整除的结果后剩下的值就是余数
int m = 5;
int n = 2;
int o = m % n;
System.out.println("o = " + o);

// 对 0.0 求余,则得到非数
Object p = m % 0.0;
System.out.println("p = " + p);

Self-increasing and self-decreasing

Self-addition, denoted by ++, it is a monocular operator and can only operate on one operand. The self-add operator can only operate on a single numeric (integer, floating point, etc.) variable, and cannot operate on constants or expressions.

Operators can appear on the left or on the right of the operand, but pay special attention to the final effect of the left and right.

If you put ++ on the left, add 1 to the operand first; then put the operand into the expression.

If you put ++ on the right, you first put the operand into the expression and then add 1 to the operand.

++a
a = a + 1;
return a;

a++
temp = a;
a = a + 1;
return temp;

x++ increments the value of variable x after processing the current statement.
++x increments the value of variable x before processing the current statement.

So just decide on the logic you write.
x += ++i will increment i and add i+1 to x. 
x += i++ will add i to x, then increment i.

Example:

int a = 66;
// 先将 a 的值,放入表达式中进行运算,然后再给 a 加 1
int b = a++ + 10;
// 先将 a 加上 1,然后将新得到的值,再放入表达式中进行运算
int c = ++a + 10;
System.out.println("a = " + a); // 68
System.out.println("b = " + b); // 76
System.out.println("c = " + c); // 78

Complex mathematical operations

Generally, we use the tool methods of java.lang.Math class to complete complex mathematical operations, such as power and square.

The Math class contains a lot of static methods used to complete various complex mathematical operations.

int a = 12;
// 乘方
double b = Math.pow(a, 10);
// 平方根
double c = Math.sqrt(a);
// 随机数
double d = Math.random();
// 三角函数:sin
double e = Math.sin(2.34);
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
//        a = 12
//        b = 6.1917364224E10
//        c = 3.4641016151377544
//        d = 0.24282712973853993
//        e = 0.7184647930691261

Special + sign

In particular, note that in addition to the plus sign, it can also be used as a concatenation operator for strings.

int year = 2020;
String str = "年";
System.out.println(year + str);

Assignment operator

Java uses the = sign as an assignment symbol to assign variable values ​​to variables.

int a = 12; 
char b = ‘h’; 
boolean c = true; 
// 将变量 a 赋值给 d 变量 
int d = a;

In particular, the assignment operator performs calculations from right to left. The program first calculates the value on the right = and then "hands" the value to the variable on the left. The variable is equivalent to a container that can receive the assigned value.

Bitwise operator

& : Bitwise AND, only return 1 when both of them are 1.

| : Bitwise or, as long as one bit is 1, it can return 1.

~ : Bitwise NOT, monocular operator, invert all bits of the operand (including the sign bit).

^ : XOR by bit, return 0 when the two bits are the same, and return 1 when they are different.

<< : Left shift operator, shifts the binary code of the operand to the left by the specified number of digits, and the left side is empty after the left shift

The bits that come out are filled with 0s.

>> : Right shift operator, after shifting the binary code of the first operand to the right by the specified number of digits, the left side is vacant

The incoming position is filled with the original sign bit.

>>> : Unsigned right shift operator. After shifting the binary code of the first operand to the specified number of bits to the right,

The positions vacated on the left are always filled with 0.

Comparison operator

It is mainly used to judge the size of two variables or constants. The result of the comparison operation is a Boolean value (true or false).

> : Greater than

> = : Greater than or equal to

< : Less than

<= : Less than or equal to

== : equal to.

If the two operands being compared are both numeric types, even if their data types are different, as long as their values ​​are equal, true will be returned.

If both operands are reference types, then only if the types of the two reference variables have parent and child

The relationship can only be compared, and the two references must point to the same object to return true.

! = : Not equal

Logical Operators

&& : AND, the two operands before and after must be true to return true, otherwise return false.

& : No short-circuit and, the effect is the same as &&, but no short-circuit.

|| : Or, as long as one of the two operands is true, you can return true, otherwise return

false。

| : No short circuit or, the same effect as ||, but no short circuit.

! : No, only one operand is required. If the operand is true, true is returned.

^ : XOR, it returns true when the two operands are different, and returns false when they are the same.

System.out.println(6 > 3 && '7' > 22);
System.out.println(6 >= 7 || 'h' > 'b');
System.out.println(6 >= 7 ^ 'h' > 'b');
int a = 6;
int b = 12;
if (a > 3 | b++ > 12) {
    System.out.println("a 的值:" + a);
    System.out.println("b 的值:" + b);
}
int c = 6;
int d = 12;
if (c > 3 || d++ > 12) {
    System.out.println("c 的值:" + c);
    System.out.println("d 的值:" + d);
}

Trinocular operator

Syntax format:

Expression? If the condition is met, the value here returns A: If the condition is not satisfied, the value here returns B

Rule: Evaluate the expression first. If the expression returns true, return the value at A; if the expression returns false, return the value at B.

int a = 6;
int b = 9;
System.out.println(a > b ? "a 比 b 大" : "a 比 b 小");

Comment

When programming, it is recommended to add some comments, which can be used as descriptive text of a piece of code, or the purpose of a class, what function a method has, etc.

Single-line comments, indicated by double slashes "//", can be added by adding at the front of the statement that requires comments.

// 这是单行注释 
// System.out.println(“注释之后的语句,不能再被执行了”); 

Multi-line comments, you can comment all the content of multiple lines at once. Mainly start with / * and end with * / , and include the content that needs to be annotated.

/*
我可以注释很多内容 System.out.println(“Hello World”); 
*/

Guess you like

Origin www.cnblogs.com/lucaswangdev/p/12688805.html