Java-2.2 Arithmetic Operators
This section describes Arithmetic Operators.
1. automatic conversion result type.
package com.ray.ch01;public class Test {public static void main(String[] args) {int a = 2, b = 3;int c = a / b;int d = b / a;System.out.println(c);System.out.println(d);}}
According to the code above, the result of B/a is 1.5, which is obviously of the float type. However, because d is of the int type, it is directly converted to int, and the fractional part is directly removed during the conversion process.
2. the variables or constants in the expression are automatically transformed and converted to the type that can accommodate larger data.
Transformation direction: byte-> shot (char)-> int-> long> float-> double
Package com. ray. ch01; public class Test {public static void main (String [] args) {byte a = 2, B = 3; int c = a/B; int d = B/; // a = c + d; // It can only be converted up. It cannot be converted down. The error "System" is returned here. out. println (c); System. out. println (d );}}
The Code shows that d = B/a is correct, but a = c + d does report an error, which is a type conversion problem.
3. One-dollar addition and one-dollar reduction
Unary subtraction: returns the inverse value. For example,-(+ 1) =-1,-(-1) = 1
Mona1 addition: It only promotes the type to int, and does not work for data larger than int type.
The following is an example of code:
Package com. ray. ch01; public class Test {public static void main (String [] args) {byte a = 2; double c = 2.1; int B = 1 *-; // equivalent to int B = 1 * (-a) double d = 2 *-c; System. out. println (getType (+ a); System. out. println (getType (+ d); System. out. println (B); System. out. println (d);} public static String getType (Object o) {return o. getClass (). toString ();}}
Output:
Class java. lang. Integer
Class java. lang. Double
-2
-4.2
From the above example, we can see that 1 *-a is true in the compiler, So we generally write 1 * (-a) for readability)
Summary: This chapter discusses three points of attention for arithmetic operators.
This chapter is here. Thank you.
-----------------------------------
Directory