wood burning stoves 2.0*
The moose likes Java in General and the fly likes Cannot convert char to byte Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Cannot convert char to byte" Watch "Cannot convert char to byte" New topic
Author

Cannot convert char to byte

Shainaz Tamboli
Greenhorn

Joined: Jun 09, 2010
Posts: 11

Hi,

Can you please tell me why the below code giving me compilation error : Type mismatch


In above code method m1() working fine but method m2() giving compilation error.

So can you please tell me why?

Regards,
Shainaz


-Shainaz
Mina Daoud
Ranch Hand

Joined: Sep 24, 2010
Posts: 88
Your method m2 is declared to return a bye value (8 bits size), and it is returning a char (16 bits size)!
naveen yadav
Ranch Hand

Joined: Oct 23, 2011
Posts: 384


size of the type does not matter the range of the values matter.

as range of character is 0 to 65536 and range of byte is -127 to 128.

byte to chat conversion
say
byte bt = -10 ;
char ch1 = bt ; //-------error , why -10 does not lie in the range of char.
char ch1 = (char) bt; //---------It is a narrow conversion Always cast.


similarly char to byte conversion
char ch = 666 ;
byte bt = ch ; //-------error , why 666 does not lie in the range of byte.
byte bt = (byte) ch; //---------It is a narrow conversion Always cast.




Mina Daoud
Ranch Hand

Joined: Sep 24, 2010
Posts: 88
naveen yadav wrote:
size of the type does not matter the range of the values matter.

as range of character is 0 to 65536 and range of byte is -127 to 128.

byte to chat conversion
say
byte bt = -10 ;
char ch1 = bt ; //-------error , why -10 does not lie in the range of char.
char ch1 = (char) bt; //---------It is a narrow conversion Always cast.


similarly char to byte conversion
char ch = 666 ;
byte bt = ch ; //-------error , why 666 does not lie in the range of byte.
byte bt = (byte) ch; //---------It is a narrow conversion Always cast.


Yes, i am sorry. You are right.
Bhasker Tiwari
Greenhorn

Joined: Jul 15, 2010
Posts: 1
Hi Naveen,

You are right, But it actually does not answer the question properly,
The complete code is like below, shainaz is my friend.


So, here my question is even if the user supplies the same value as in m1(), then based on your explanation, it should cause the error.
As it is not throwing in m1().
So, as per me there is something to do with the interpretation of this in JVM, where JVM says, if the value is expected to come at runtime, then it falls in your explanation.

Please feel free to correct me.
Thanks.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Cannot convert char to byte
 
Similar Threads
compile-time constant
Guys Help me Out
Problem returning a byte (was:Why it gives Compiler error?)
complie-time constants
Hi