Java basic syntax
1. Notes
There are three types of annotations in Java
- Single line comment / / hello world
- Multiline comment/**/
- Document comments (javadoc) / * * begin with the first line ✳, Finally ✳/ ending
2. Identifier and keyword
Identifier: all components of Java need names. Class names, variable names, and method names are all called identifiers.
2.1. identifier
Keywords, such as public, class, if, long,, static, catch, etc. in public class projectname {}
be careful:
- The identifier consists of 26 English characters, case (azAZ) and underscore () And the dollar sign ($).
- Cannot start with a number or be a keyword
- Strictly case sensitive
- The identifier can be of any length
- The first letter can be followed by any combination of characters such as letters
- It can be named in Chinese, but it is very low. For example, String so and so = "the strongest king"
3. Data type
All variables must be defined before they can be used, unless cast (strongly typed language)
For example, we directly define
String a = 10;
An incompatible type will be reported
The correct is
type varName [=value] [{,varName[=valud]}]; //Data type variable name = value; You can declare multiple variables of the same type separated by commas
The above method includes multiple variables in one line, but we do not recommend this
For example:
int a = 100;
3.1. primitive type
3.1. 1. Value type
-
Integer type
-
-
Byte takes up 1 byte range: - 128 ~ 127
-
short occupies the range of 2 bytes: - 32768 ~ 32767
-
int takes up 4 bytes range: - 2147483648 ~ 2147483647
-
long takes up the range of 8 bytes: - 9223372036854775808 ~ 9223372036854775807
long num2 = 30L; //To add L to tell the computer the long type
-
-
Floating point type
-
-
float takes up 4 bytes
But directly
float num = 10.2; //If it is a floating-point type, the default is double. At this time, the float value range is less than double and cannot be converted automatically. An error is reported. At this time, a forced conversion should be added, such as: float num1 = 10.2F;
-
double takes up 8 bytes
-
-
The character type takes up 4 bytes
The character type is char, for example:
char name = 'A'; //perhaps char name1 = 'meter';
The definition String uses String, but String is a class
String name2 = 'jiyuanjie';
3.1.2.boolean type (boolean type)
It occupies 1 bit, and its values are only true and false
3.2. reference type
- Class (currently we are dealing with String)
- Interface
- array
4. Byte
- Bit: the smallest unit of data storage in the computer. 00000001 is an eight * * * bit * * * binary number
- byte: the basic unit of computer data processing, represented by B
1 bit means 1 bit
1Byte represents a byte 1B=8b
1024B=1KB
1024KB=1M
1024M=1G
...
5. Data type expansion
5.1. integer
int num = 10; //Decimal 10 int num1 = 010; //Octal 8 int num2 = 0x10; //Hex 0 ~ 9 A ~ F 16 int num3 = 0b10; //Binary 2
5.2. Floating point number
Let's start with an example:
float f = 0.1f;double d = 1/10;//The results are all 0.1, but f= d. So there are some problems with floating-point numbers
Floating point numbers have rounding error, and the result is close to but not equal to. Therefore, there may be problems in using floating point numbers for comparison. In learning, try to avoid using floating point numbers for comparison.
If you have to compare, you need the mathematical tool class BigDecimal, which will be introduced later
5.3. character
Sometimes we encounter the following situations
char c = "in";System.out.println(c);System.out.println((int)c);//Output / / medium / / 20013
Therefore, the character type is essentially a number, but some cannot be forcibly converted. We will talk about it later. It uses Unicode coding, and its range is U0000 to UFFFF
char c1 = '\u0032'//The number 2 will be output, which is the encoding of Unicode
5.3. 1. Escape character
For example:
// \t stands for tab / / \ n stands for line feed / /
5.3. 2. String
String a = new String(original:"hello world");String b = new String(original:"hello world");System.out.println(a==b);//The output is false string c = "Hello world"; String d = "hello world"; System. out. println(c==d);// The output is true
This thing involves objects and memory, which we will talk about later, including the previous floating-point numbers and why they are equal or unequal, which will have a great relationship with memory
5.4. Boolean type
boolean flag = true;if (flag == true){ //....}// if(flag) {} is the same as the above, conforms to less is more, and the code should be concise and easy to read
6. Type conversion
In operation, different types of data must be converted to the same type before calculation
Low ---------------------------------------------------------------- > High
byte,short,char -> int -> long -> float -> double
int i = 128;byte b = i;//Cast type required / / byte b = (byte)i// But b will be - 128, because the maximum byte type is 127, and the memory overflows double d = i// No problem because automatic type conversion goes from low to high
Boolean values cannot be converted
There may be memory overflow or precision problems during conversion
(a large number of operations may overflow)
int i = 1000000000;//Billion / / in jdk7, numbers can be separated by underscores, and underscores will not output int i1 = 10_0000_0000;// Such calculations can easily overflow long l = i1*20// However, the right value is of type int, and there is a problem before conversion. long l1 = i1*(long)20;long l2 = (long)i1*20;long l3 = (long)i1*(long)20;// The above three methods are OK
long l4 = 100l;long l5 = 100L;/*You can tell the computer that this is a long type, but we recommend using L instead of L. because l is very similar to 1 in some places, try to form a specification*/
7. Variables
7.1. Variable scope
Scope can refer to c language code block scope, file scope, prototype scope and function scope.
7.1. 1. Local variables
public class Variable{ static int allClicks = 0;//Class variable static keyword String str = "hello world"// Instance variables have no static keyword public void method() {int i = 0; / / local variables are in the method}}
I may not understand the above, which will be covered later
public class hello { //Instance variable: subordinate to the object. The scope is string name in this class; int age; Public static void main (string [] args) {/ / local variables: * * must declare and initialize values * * and only work in this main, that is, the scope is this main int i = 1;}}/* The outermost public class name {} is what we write in the class, and public static void main() {} is what we call the main method. You can also define some attributes, which can now be simply understood as variables. Or the third method is another method, such as public void add() {}*/
7.1. 2. Instance variables
public class hello { String name; int age; public static void main(String[] args) { //new class() write this first, get our class, and return an object hello hello = new hello()// Variable type variable name = new hello()// The value is itself out. println(hello.age); // The value is zero system out. println(hello.name); // The value is null / / but sometimes we see this situation. Final Hello = new hello()/* Start another thread B in thread A. if thread B wants to use the local variable of thread a, the local variable of thread a needs to be defined as final. Reason: local variables are shared within threads. Each thread cannot access local variables of other threads, but the appeal violates this principle. Why can we add final? The reason is that after adding final, when creating thread B, the variable marked final will be passed to thread B as the parameter of the construction method of thread B. this solves this problem * /}}
In the instance variable, if it is not initialized, the value defaults to zero, which is similar to the non initialization of static variables in c language. However, the Boolean value defaults to false. Only the basic type is zero, and the others are null
7.1. 3. Class variable
public class Variable{ static int allClicks = 0;//Class variable static keyword String str = "hello world"// The instance variable does not have the static keyword public void method() {int i = 0; / / the local variable is in the method System.out.println(allClicks);}}
Class variables belong to this class, which will be mentioned later. static can be called directly instead of new (instance variable),
8. Constant
Special variables cannot be changed during program operation after setting.
final Constant name = value;final double PI = 3.14;//Constant names generally use uppercase characters static final double PI = 3.14;final static double PI = 3.14;//static and final modify PI. They are modifiers. There is no order of modifiers
9. Basic operators
- Arithmetic operators: +, -, *, /,%, + +, –
- Assignment operator:=
- Relational operators: >, <, > =, < =, = =,! =, instanceof
- Logical operators: & &, |, |,!
- Bitwise operators: &, |, ^, ~, <, > >, > > (binary operation)
- Conditional operators:?,:
- Extended assignment operators: + =, - =, * =/=
long a = 123L;int b = 1;short c = 2;byte d = 8;System.out.println(a+b+c+d); //long type system out. println(b+c+d); // Int type system out. println(c+d); // Int type
According to 6 For type conversion, if there are operations before int, such as float, double and long types, the resultant is the highest type. If it is under int, byte, short, char, the resultant is of type int
System.out.println(c+dz); //int type
If cast to String type in this formula, it will show that int type cannot be converted to String type
However, you can still turn from low to high, such as double conversion
The operation of logarithm is only as above, but the power operation cannot be 2 ^ 3
Math.pow(3,2);//Math is a mathematical class with many function operations
9.1. Logical operator
//And, or, not
boolean a = true;boolean b = false;System.out.println("a && b:"+(a && b)); //False is logical and true, and the same is true out. println("a || b:"+(a || b)); // True is a logical or, and false is a false system out. println("!(a && b):"+! (a && b)); // True true becomes false, and false becomes true / / short circuit operation d = 5; c = (d<4)&&(d++<5);// In this example, the first half of the calculation is false, the result is false, and no calculation will be made later, that is, short circuit operation
9.2. Bitwise Operators
a = 0011 1100;b = 0000 0010;a&b = 0000 0000 //The same is one, otherwise it is zero, and a|b = 0011 1110 / / one is one or a^b = 0011 0001 / / the same is 0, but the difference is an exclusive or ~ b = 1111 1101 / / take the opposite
How is 2 * 8 the fastest?
Bit operation is the fastest,
< < equivalent to * 2, > > equivalent to / 2
0000 0000 00000 0001 10000 0010 20000 0011 30000 0100 40000 1000 80001 0000 16
x?y: z
a = b?"this":"Ah, this";
If x==true, the result is y, otherwise z
9.3. String connector
a = 10;b = 20;System.out.println(""+a+b); //The result is 1020. Put the two together / * + if there is a String on either side, convert them to String and connect * / system out. println(a+b+""); // The result is 30/*Strig spliced in the front and not spliced in the back * / system out. println(a+b+""+a+b);// The result is 301020
9.4. priority
Try to use more parentheses, which is simple and clear.
10. Package mechanism
In order to better organize classes, java provides a package mechanism to distinguish the namespace of class names.
Its syntax format is:
package pkg1[. pkg2[. pkg3...]]
In order to use the members of a package, we need to import the package.
import package[.package2...].(classname|*)
Generally speaking, the company domain name is inverted as the package name
For example, Baidu, www.baidu.com com
Invert to com baidu. www
If you are under a package, you must mark it with package at the top, otherwise an error will be reported
import java.util.Date;public class hello { Date}
For example, if you want to use Date, an error will be reported if you use it directly. You need to import the package where Date is located
Import must be under package. If this code is not in a package, import will be at the top
import com.baidu.www.*;//.* Represents wildcards, that is, all classes of imported packages. It is suitable for importing many packages
11.javaDoc
[javaDoc help document] Java SE documentation - API and documentation | Oracle China
package com.anjin;/***@author*@since*@version*/public class Doc{ String name; public String test(String name){ return name }}
parameter information
- @Author author name
- @Version version number
- @since indicates that the earliest jdk version is required
- @param parameter name
- @Return return value
- @The throws exception is thrown as follows
package com.anjin;/***@author*@since*@version*/public class Doc{ String name; public String test(String name) throws Exception{ return name }}
For example, the file name is doc java
After writing, open the cmd command through the file location and enter javadoc -encoding UTF-8 -charset UTF-8 Doc,java. Many new things will appear in the original file, but we only use index HTML, you can see the API comments we have written on the web page
-encoding UTF-8 -charset UTF-8 is used to identify Chinese characters without garbled codes