Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an explicit cast not needed here?

class MyClass {
    void myMethod(byte b) {
        System.out.print("myMethod1");
    }

    public static void main(String [] args) {
        MyClass me = new MyClass();
        me.myMethod(12);
    }
}

I understand that the argument of myMethod() being an int literal, and the parameter b being of type byte, this code would generate a compile time error. (which could be avoided by using an explicit byte cast for the argument: myMethod((byte)12) )

class MyClass{
    byte myMethod() {
        return 12;
    }

    public static void main(String [ ] args) {
        MyClass me = new MyClass();
        me.myMethod();
    }
}

After experiencing this, I expected that the above code too would generate a compile time error, considering that 12 is an int literal and the return type of myMethod() is byte. But no such error occurs. (No explicit cast is needed: return (byte)12; )

Thanks.

like image 903
PrashanD Avatar asked Dec 17 '12 13:12

PrashanD


2 Answers

Java supports narrowing in this case. From the Java Language Spec on Assignment Conversion:

A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

like image 175
McDowell Avatar answered Oct 07 '22 15:10

McDowell


From Java Primitive Data Type reference:

byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).

Try returning 128 : ))

like image 30
moonwave99 Avatar answered Oct 07 '22 15:10

moonwave99