Java operators and type conversion
1 arithmetic operator
The arithmetic operators in Java mainly include + (addition), - (subtraction), * (multiplication), / (division), % (remainder), and they are all binary operators.
2 Increment and decrement operators
The self-increment and self-decrement operators are unary operators, which can be placed before or after the operand.
++a(--a) //表示在使用变量a之前,先使a的值加(减)1
a++(a--) //表示在使用变量a之后,使a的值加(减)1
3 comparison operators
Comparison operators are binary operators that are used for comparisons between variables, between variables and independent variables, and between other types of information in a program.
4 Ternary operator
Basic format:
条件式 ? 值1 : 值2
For example
boolean a = 10 < 15 ? true : false;
The operation result of the above program expression "10 < 15" returns true, then the value of the boolean variable b is true. On the contrary, if the operation result of the expression returns false, the boolean variable b takes the value false.
5 Operator precedence
The precedence of operators determines the order in which operations in an expression are performed.
the code
public static void main(String[] args) {
int a = 100;
double b = 20.0;
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a/10);
System.out.println(b/10);
System.out.println(a*b);
System.out.println(a%2);
System.out.println(b%2);
System.out.println(10.0/3);
System.out.println('f'+a);
System.out.println("今年小明岁数是"+10+"岁");
}
120.0
80.0
10
2.0
2000.0
0
0.0
3.3333333333333335
202
今年小明岁数是10岁
6 Implicit type conversion and explicit type conversion
6.1 Implicit type conversion
The conversion from low-level types to high-level types will be automatically performed by the system, and the programmer does not need to perform any operations. This type of conversion is called an implicit conversion. The following basic data types involve data conversion, excluding logical types and character types. The order of these types in descending order of precision is byte < short < int < long < float < double.
Conversion rules:
Use arithmetic operations to implicitly convert data types.
6.2 Explicit type conversions
When assigning the value of a high-precision variable to a low-precision variable , an explicit type conversion operation (also known as a cast) must be used.
int a=(int)3.14; //输出为a的值为3
int b=(int)'d'; //输出b的值为100