001package types.coercion;
002class Main {
003        private Main() {}
004        @SuppressWarnings("cast")
005        public static void main(String[] args) {
006                int i0 = 1;
007                float f0 = i0;         // compiles ok, runs ok (implicit up-coercion)
008                float f1 = (float) i0; // compiles ok, runs ok (explicit up-coercion)
009
010                float f2 = 1.42f;
011                //  int i2 = f2;       // compiler error (implicit down-coercion)
012                int i3 = (int) f2; // compiles ok, runs ok (explicit down-coercion)
013
014                // Note that coercion changes the actual value, not just the
015                // declared type.
016                float f3 = i3;
017                System.out.println("f2=" + f2);
018                System.out.println("f3=" + f3);
019        }
020}
021class CoercionOrdering {
022        private CoercionOrdering() {}
023        public static void showingCoercionOrder() {
024                // booleans and object types do not coerce
025                // use ?: to convert booleans to other types
026                // use ?: also for object types
027                boolean p = false;
028                int j = p ? 1 : 0;
029                Object o = null;
030                int k = (null==o) ? 0 : 1;
031
032                // char and short are both 16 bit, but mutually incomparable
033                char  c = '\0';
034                short z = 0;
035                z = (short) c;
036                c = (char) z;
037
038                // number types from bottom to top
039                byte   b = 0;
040                short  s = b;
041                int    i = s;
042                long   l = i;
043                float  f = l;
044                double d = f;
045
046                // number types from top to bottom, losing precision
047                f = (float) d;
048                l = (long) f;
049                i = (int) l;
050                s = (short) i;
051                b = (byte) s;
052        }
053}