|
TestOperator.java
|
import java.io.*;
public class TestOperator {
static int sum(int a, int b, int c) {
return (a + b + c);
}
public static void main (String[] args)throws IOException {
// Operator precedence is ordered roughly like this
// unary > (Type) > math (% / * > + -) > shift >
// non-equality-comparison > equality-comparison
// > bitwise (& > ^ > |) > logical(&& > ||) >
// ternary(?:) > assignment
int n = 7;
n <<= 3;
System.out.println("n = " + n); //56
n = (- -1-3*10/5-1);
System.out.println("n = " + n); //-6
n = n&n + 1|n + 2^n + 3;
System.out.println("n = " + n); //57
n>>=2;
System.out.println("n = " + n); // 14
// no exception thrown on floating point number arithmetic
System.out.println(-32.0/0.0); // -Infinity
// shift brain game
System.out.println(-31>>>5>>5>>>5>>5>>>5>>5);// 3
// non-integer mod is allowed in Java
double x = 15.8 % 3.2;
System.out.println(x); // 3.0
// Java resolve the variable reference or value
// ambiguity problems by fixing the order as left to right.
// This solves the inconsitancy problems of other languages.
// In those languages, the evaluation order is undefined.
// Different compilers use different implementation
// and/or optimization methods.
int a[] = {3, 5, 7};
int i = 0, j = 3;
a[i] = i = 1; // = is right associative
System.out.println(a[0]+" "+a[1]+" "+a[2]+" "+i);//1 5 7 1
System.out.println(sum(j + i, ++i, ++j));// 10
// Bad guessing game!!
int k=1;
n = ++k + k++ + ++k;
System.out.println("n = " + n); //8
//compiler need to know the return type of ternary operator
//10 is promoted to double
System.out.println((x>50)?99.0:10);//10.0
// broaden does not changing data
byte b1 = -128;
n = b1;
System.out.println("n = " + n); //-128
byte bb = 1;
char cc = 1;
short ss = 1;
int ii = 1;
ii = bb << ss;
// The extended assignment operators ensure that an implicit
// narrowing conversion makes the result fit back in the
// target variable
bb <<= ss;
ss += ii;
System.out.println("ii=" + ii + " bb=" + bb + " ss=" + ss);
// ii=2 bb=2 ss=3
// even ii is out of range of short
// ss will be truncated
ii = 33333333;
ss += ii;
System.out.println("ii=" + ii + " ss=" + ss);
// ii=33333333 ss=-24488
// cannot implicitly convert int to short
//ss = bb * 2;
// cannot convert int to char
//cc = cc + bb;
//Strange but legal
int []ia[] = {{1, 2}, {1}, {}, {1, 2, 3}};
System.in.read();
}
}
Last updated: 12-10-2002
Copyright © 1999 - 2003 Roseanne Zhang, All Rights Reserved