Why does Java require an explicit cast on a final variable if it was copied from an array?

前端 未结 4 673
长发绾君心
长发绾君心 2021-01-01 08:28

Starting with the following code...

byte foo = 1;
byte fooFoo = foo + foo;

When I try compiling this code I will get the following error...

4条回答
  •  长情又很酷
    2021-01-01 09:02

    This occurs because of

    byte foo = 1;
    byte fooFoo = foo + foo;
    

    foo + foo = 2 will be answered but 2 is not byte type because of java has default data type to integer variables it's type is int. So you need to tell the compiler by force that answer must be a byte type explicitly.

    class Example{
        public static void main(String args[]){
    
            byte b1 = 10;
            byte b2 = 20;
            byte b1b2 = (byte)(b1 + b2); 
    
            //~ b1 += 100;  // (+=) operator automaticaly type casting that means narrow conversion
    
            int tot = b1 + b2;
    
            //~ this bellow statement prints the type of the variable
            System.out.println(((Object)(b1 + b2)).getClass());  //this solve your problem
        }
    }
    

提交回复
热议问题