Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

java - Why i am getting type mismatch: cannot convert from int to byte

class Test
{  
   public static void main(String[] args) 
   { 
     byte t1 = 111;
     byte t2 =11;
     byte t3 = t1+t2;

     System.out.println(t1+t2);   

   }  
}  

In eclipse it is showing error cannot convert from int to byte.Here sum is 122 which range in the byte range.So why i am getting this error here.

Thanks in advance...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you do mathematical operations on byte, Java do Widening( automatic type promotion) to byte(implicitly up casted) to integer this case. so when you perform

 byte t3 = t1+t2; //  t1+t2; will be evaluated as integer.

As t1+t2 result is wider than byte so you need to downcast it to byte.

To remove compilation error.

 byte t3 = (byte) (t1+t2); // typecast to byte

For more information please read JLS 5.1.2


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...