1 //THINGING IN JAVA P123 2 3 package java_test; 4 5 //Tests all the operators on all the primitive data types: 6 //to show which ones accepted by the Java compiler. 7 8 //This file will compile without error because 9 //the lines that fail are commented out with a //! 10 public class AllOps { 11 // To accept the results of a boolean test: 12 void f(boolean b) { 13 } 14 15 void boolTest(boolean x, boolean y) { 16 // Arithmetic operators: 17 // !x=x*y; 18 // !x++; 19 // !x+=y; 20 // !... 21 // Relational and logical 22 // !f(x>y) 23 // !... 24 f(x == y); 25 f(x != y); 26 f(!y); 27 x = x && y; 28 x = x || y; 29 // Bitwise operators 30 // !x=~y; 31 x = x & y; 32 // ... 33 // !x=x<<1; 34 // !... 35 // Compound assignment 36 // !x+=y; 37 // !... 38 // !x<<=1; 39 // !... 40 x &= y; 41 // ... 42 // Casting 43 // !char c=(char)x; 44 // !... 45 } 46 47 void charTest(char x, char y) { 48 // Arithmetic operators 49 x = (char) (x * y); 50 // ... 51 x++; 52 x = (char) +y; 53 // Relational and logical 54 f(x > y); 55 // ...; 56 // !f(!x); 57 // !f(x&&y); 58 // !f(x||y); 59 // Bitwise operators 60 x = (char) ~y; 61 x = (char) (x * y); 62 // ... 63 x = (char) (x >> y); 64 // ... 65 // Compound assignment: 66 x += y; 67 // ... 68 x <<= 1; 69 x &= y; 70 // ... 71 // Casting 72 // !boolean b1=(boolean)x; 73 byte b = (byte) x; 74 short s = (short) x; 75 // ... 76 } 77 78 // byte short int long 类似 79 80 void floatTest(float x, float y) { 81 // Arithmetic operators 82 x = (x * y); 83 // ... 84 x++; 85 x = +y; 86 // Relational and logical 87 f(x > y); 88 // ...; 89 // !f(!x); 90 // !f(x&&y); 91 // !f(x||y); 92 // Bitwise operators 93 // !x = ~y; 94 // !... 95 // Compound assignment 96 x += y; 97 // ... 98 // !x<<=1 99 // !... 100 // Casting 101 // !boolean b1=(boolean)x; 102 byte b = (byte) x; 103 short s = (short) x; 104 // ... 105 } 106 // double 类似 107 }
Note that boolean is quite limited. You can assign to it the values true and false, and you can test it for truth and falsehood, but you cannot add booleans or perform any other type of operation on them.
in char,byte,and short, you can see the effect of promotion with the arithmetic operators.Each arithmetic operation on any of those types produces an int result,which must be explicitly cast back to the original type(a narrowing conversion that might lose information) to assign back to that type.With int values,however,you do not need to cast,because everything is already an int .