Java core fundamentals Part 2 - basic Java syntax

Java basic syntax

This chapter discusses the basic of Java vb.net tutorial Grammar. Mainly from the following aspects:

  • Java keyword
  • Java identifier
  • Java variables
  • Java data type
  • Java operator

After learning this chapter, we will have a deeper understanding of Java c# tutorial At the same time, you can also use Java to complete basic operations.

1, Keywords

1.1 meaning

It is given special meaning by java for special purpose python basic tutorial String of.

For example:

  • Public: indicates public
  • Class: define class

1.2 features

1.3 keyword list

Java provides many keywords, as shown in the following table:

Keywords used to define data types
classinterfaceenumbyteshort
intlongfloatdoublechar
booleanvoid
Keywords used to define data type values
truefalsenull
Keywords used to define process control
ifelseswitchcasedefault
whiledoforbreakcontinue
return
Keywords used to define access modifiers
privateprotectedpublic
Keywords used to define class, function and variable modifiers
abstractfinalstaticsynchronized
Keywords used to define the relationship between classes
extendsimplements
It is used to define keywords for creating and referencing instances and judging instances
newthissuperinstanceof
Keywords for exception handling
trycatchfinallythrowthrows
Keywords for packages
packageimport
Other modifier keywords
nativestrictfptransientvolatileassert

2, Identifier

2.1 Java identifier meaning

The character sequence used by Java when naming various variables, methods, classes and other elements is called sql tutorial identifier

Any place where you can name yourself is called an identifier.

2.2 naming rules of Java identifiers

1.It consists of 26 English letters in case and number: 0-9 ,_or $ form  
2.A number cannot begin.
3.Keywords and reserved words cannot be used, but they can be included.
4.Java Case sensitive and unlimited length.
5.The identifier cannot contain spaces.

Note: the name should meet the requirements of knowing the meaning of the name, and the length should not be too long. Less than 30 characters;

2.3 lifeline rules for Java identifiers

Many companies have strict requirements for naming

1.Package name: xxxyyyzzz
	All names are lowercase;
	Multiple words are lowercase;
	have access to.Create multi tier package name
2.Class name and interface name XxxYyyZzz
	Initial capitalization;
	It is composed of multiple words with capital letters;
3.Variable and method names xxxYyyZzz
	The first word is lowercase;
	It is composed of multiple words. Except that the first word is lowercase, the other words are capitalized;
4.The name of the constant XXX_YYY_ZZZ
	The names of constants are capitalized;
	Multiple words are composed using underlined links;

3, Variable

3.1 concept

  • A storage area in memory;
  • This area has its own name (variable name) and type (data type);
  • Each variable in Java must be declared before use;
  • The data in this area can change continuously within the same type range;
  • Variables access this area by using variable names;
  • Scope of variable: valid between a pair of {}

3.2 definition format

Data type variable name = [initial value];

//for example
int num1 = 90;

3.3 classification of variables

a. According to the location of declaration (creation)

1.Member variable|global variable|attribute
	a.It is defined outside the method and inside the class;
	b.The scope can be used everywhere under this class,Including multiple internal methods;
2.local variable
	a.The content defined in a method or code block;
	b.Only in defined methods or code blocks{}Inside use;

Differences between:
	a.Different definition positions;
	b.Local variables must be assigned before use. Global variables generate default values for the corresponding data types;

b. By data type

1.Basic data type
	Numerical type:	
			Integer type:
				byte: 
				short: 
				int: 
				long: 
				The default type is int
			float :
				float
				double:
				Java The default floating point constant is double Type, declaration float Type constant, must be added later 'f' or 'F'. 
	character:
		char:
			a.use '' Single quotation mark definition content;
			b.Can store a Chinese
			c.Can store Java Escape characters are also allowed in'\'To convert subsequent characters into special character constants. For example: char c3 = 				'\n';  -- '\n'Indicates a newline character
			d.Direct use Unicode Value to represent a character constant:'\uXXXX'. Among them, XXXX Represents a hexadecimal integer. For example:				  \u000a express \n. 
			e.char Types can be manipulated. Because it all corresponds to Unicode Value.

	Boolean:
		boolean:
		boolean Only values are allowed for type data true and false

2.Reference data type
	In addition to the above 8 basic types, the rest are reference data types. include: String,Object Packaging, etc

3.4 variable initialization

After declaring a variable, the variable must be explicitly initialized with an assignment statement. Never use uninitialized local variables.

For example, the Java compiler considers the following statement sequence to be wrong:

public static void main(String[] args) {
    String username; //Variable 'username' might not have been initialized
    System.out.println("username = " + username);
}

To assign a value to a declared variable, you need to put the variable name to the left of the equal sign (=) and the Java expression of the corresponding value to the right of the equal sign

public static void main(String[] args) {
    String username;
    username = "Zhu Xiaoming"; //assignment
    System.out.println("username = " + username);
}

You can also put the declaration and initialization of variables on the same line. For example:

String username  = "Zhu Xiaoming"; //assignment

3.5 constants

In Java, the keyword final is used to indicate constants. For example:

public static void main(String[] args) {
    final double PI = 3.14;
    //PI = 3.10; // Exception Cannot assign a value to final variable 'PI'
    System.out.println("PI = " + PI);
}

The keyword final indicates that this variable can only be assigned once. Once assigned, it cannot be changed. Traditionally, constant names are all capitalized.

4, Java data type

Java is a strongly typed language. This means that a type must be declared for each variable, and different sizes of memory space are allocated in memory. In Java, there are eight primitive types, including four integer types, two floating-point types, a character type char for representing Unicode encoded character units, and a boolean type for representing true values.

 

4.1 integer

Each integer type of Java has a fixed data range and field length, which is not affected by the operating system OS to ensure the portability of Java programs.
And Java provides four integers (byte,short,int,long) to represent values without decimal parts, and allows them to be negative numbers.

The Java integer is of type int by default. If you declare a long integer, you must add L or l after the value

int num1 = 100;
long num2 = 100L;

In general, the int type is most commonly used. However, if you want to represent the number of people living on the planet, you need to use the long type, because the largest range of int type values is the 31st power of 2 (just over 2 billion). In this case, if you use int, it will certainly exceed the range.

4.2 floating point

Similar to integer types, Java floating-point types also have a fixed table number range and field length, which are not affected by the specific OS.
Floating point types are often used to represent numeric values with fractional parts. Float means single precision; Double means double precision, which is twice as high as float

The floating-point constant of Java is double by default. If a floating-point constant is declared, it must be followed by 'f' or 'f'.

double d1 = 10.5;
float d2 = 10.5F;

Floating point values are not suitable for financial calculations that cannot accept rounding errors. For example, the command system out. Printin (2.0-1.1) will print 0.899999999999999 instead of 0.9 as people think.

The main reason for this rounding error is that floating-point values are represented in binary system, and fraction 1 / 10 cannot be accurately represented in binary system.

It's like the decimal system can't accurately represent the fraction 1 / 3. If no rounding error is allowed in the numerical calculation, the BigDecimal class should be used, such as amount

4.3 char character type

char data is used to represent "characters" in the usual sense.
There are three forms of character constants:

  • A character constant is a single character enclosed in single quotation marks (''), covering all the characters of written languages in the world. For example: char c1 = 'a'; char c2 = 'medium'; char c3 = '9';
  • The escape character '\' is also allowed in Java to convert subsequent characters into special character constants. For example: char c3 = '\n'; -- '\n 'indicates a newline character
  • Use Unicode values directly to represent character constants: '\ uXXXX'. Where XXXX represents a hexadecimal integer. For example: \ u000a means \ n.

char type can be operated on. Because it all corresponds to Unicode values.

4.4 boolean

boolean type is suitable for logical operation and is generally used for program flow control:

  • if conditional control statement;
  • while loop control statement;
  • Do while loop control statement;
  • for loop control statement;

boolean type data can only take values of true and false. 0 or non-0 integers cannot replace true and false, which is different from C language.

4.5 basic data type conversion

It is often necessary to convert one value type to another, but in the process of conversion, we must pay attention to the possible loss of data precision. For example, if double type is changed to int type, the value after the decimal point will be lost;
Java improves two numerical conversion methods according to the actual situation: automatic type conversion and forced type conversion

4.5.1 automatic type conversion

Types with small capacity are automatically converted to data types with large capacity. The data types are sorted by capacity:

When there are multiple types of data mixed operation, the system will automatically convert all data into the data type with the largest capacity first, and then calculate.
Byte, short and char will not be converted to each other. They are first converted to int type during calculation.
When you concatenate the value of any basic type with the string value (+), the value of the basic type will be automatically converted to the string type.

4.5.2 cast type

Convert data types with large capacity to data types with small capacity. Cast character (()) should be added when using, but it may cause precision reduction or overflow, so pay special attention.
Generally, a string cannot be directly converted to a basic type, but it can be converted to a basic type through the wrapper class corresponding to the basic type. For example:

String a = "43"; int i = Integer.parseInt(a); 

boolean type cannot be converted to other data types.

4.6 large values

If the basic integer and floating point precision cannot meet the requirements, you can use Java Two useful classes in the math package: BigInteger and BigDecimal.

These two classes can handle numeric values that contain sequences of numbers of any length.

  • BigIntcger class implements integer operation with arbitrary precision,
  • BigDecimal implements floating-point operations of arbitrary precision.

Using the static valueOf method, ordinary values can be converted to large values:

BigInteger bigInteger = BigInteger.valueOf(10);
BigDecimal bigDecimal = BigDecimal.valueOf(2.0);

Unfortunately, you can't handle large numbers using familiar arithmetic operators such as: + and *. Instead, you need to use the add and multiply methods in the large value class.

4.6.1 BigInteger

The BigIntcger class implements integer operations of arbitrary precision. Common methods are as follows:

BigInteger method namemeaning
static valueOf()Convert parameter to BigInteger
add()Add
subtract()subtract
multiply()Multiply
divide()Division and rounding
remainder()Surplus
public static void main(String[] args) {

    //int to BigInteger
    BigInteger num1 = java.math.BigInteger.valueOf(100);
    BigInteger num2 = java.math.BigInteger.valueOf(12);

    //Add
    BigInteger add = num1.add(num2);
    System.out.println("Add:" + add);

    //subtract 
    BigInteger subtract = num1.subtract(num2);
    System.out.println("subtract :" + subtract);

    //Multiply
    BigInteger multiply = num1.multiply(num2);
    System.out.println("Multiply:" + multiply);

    //Division and rounding
    BigInteger divide = num1.divide(num2);
    System.out.println("be divided by:" + divide);

    //Fetch | remainder
    BigInteger remainder = num1.remainder(num2);
    System.out.println("Surplus:" + remainder);
}

Final result:

Add:112
 subtract :88
 Multiply:1200
 be divided by:8
 Surplus:4

4.6.1 BigDecimal

BigDecimal implements floating-point operations of arbitrary precision. Common methods are as follows:

BigDecimal method namemeaning
static valueOf()Convert parameters to BigDecimal
add()Add
subtract()subtract
multiply()Multiply
divide()Division and rounding
remainder()Surplus
public static void main(String[] args) {

    //int to BigInteger
    BigDecimal num1 = BigDecimal.valueOf(100.5);
    BigDecimal num2 = BigDecimal.valueOf(12.3);
    //Add
    BigDecimal add = num1.add(num2);
    System.out.println("Add:" + add);

    //subtract 
    BigDecimal subtract = num1.subtract(num2);
    System.out.println("subtract :" + subtract);

    //Multiply
    BigDecimal multiply = num1.multiply(num2);
    System.out.println("Multiply:" + multiply);

    //Two decimal places shall be reserved for division, and the last digit shall be rounded. Of course, other modes can also be used
    BigDecimal divide = num1.divide(num2,2, RoundingMode.UP);
    System.out.println("Divide by two decimal places/rounding:" + divide);

    //Fetch | remainder
    BigDecimal remainder = num1.remainder(num2);
    System.out.println("Surplus:" + remainder);
}

Final result:

Add:112.8
 subtract :88.2
 Multiply:1236.15
 Divide by two decimal places/rounding:8.18
 Surplus:2.1

5, Java operator

Java provides a variety of operators to meet normal requirements. We can divide operators into the following categories:

  • Arithmetic operator
  • Assignment Operators
  • Comparison operator (relational operator)
  • Logical operator
  • Bitwise Operators
  • Ternary operator

5.1 arithmetic operators

operatoroperationexampleresult
+Plus sign+33
-minus signb=4; -b-4
+plus5+510
-reduce6-42
*****ride3*412
/except5/51
%Take mold5%50
++ ++Auto increment (front): operation before value taking. Auto increment (rear): value taking before operationa=2;b=++a; a=2;b=a++;a=3;b=3 a=3;b=2
- - - -Self subtraction (front): take value after operation. Self subtraction (rear): take value before operationa=2;b=- -a a=2;b=a- -a=1;b=1 a=1;b=2
+String addition"He"+"llo""Hello"

5.2 assignment operator

operatoroperationexampleresult
=assignmentb=55
+=, -=, *=, /=, %=Assign value after calculationb = 5;b+=27

5.3 comparison operator (relational operator)

operator**Operation**exampleresult
==Equal to4==3false
!=Not equal to4!=3true
<less than4<3false
>greater than4>3true
<=Less than or equal to4<=3false
>=Greater than or equal to4>=3false
instanceofCheck whether it is an object of class"Hello" instanceof Stringtrue

5.4 logical operators

operatoroperationexampleresult
&And (and)false & truefalse
|Or (or)false|truetrue
^XOR (exclusive or)true^falsetrue
!Not!truefalse
&&And (short circuit)false&&truefalse
||Or (short circuit)false||truetrue

5.5 ternary operators

Ternary operators are mainly used to select results that cannot be based on different conditional expressions

Just type if Like else branch statements, you can achieve one of two results.

For example, if the score is greater than or equal to 60, it means passing, otherwise it means failing

//Grammar
(conditional expression)? Expression 1: expression 2
-If the conditional expression is true, the result of the operation is expression 1;
-If the conditional expression is false, the result of the operation is expression 2;

//example     
int num1 = (100>1)?666:250;
Because 100>1 Returned is true,So eventually num1 The result is 666

Added by lilwing on Wed, 19 Jan 2022 21:55:10 +0200