• Post Reply Bookmark Topic Watch Topic
  • New Topic

Doubt on Type casting  RSS feed

 
Anil Pattnaik
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Everybody,
I have one doubt on Type casting,How can a byte can be type casted to an int as byte holds 8-bits memory but int holds 32 bits memory.Example:byte b=6;Please explain...
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A byte is a signed, 8-bit integer in Java, so it can hold values between -128 and 127.

The Java compiler is smart. When you initialize a byte variable with a literal integer value, the compiler checks if it is in the range -128 to 127. So a statement like:

byte b = 6;

works without problems. If the literal integer value doesn't fit into an int, you will get an error message. Try this and see what the compiler says:

byte b = 130;

You can ofcourse force it, by doing this:

byte b = (byte)130;

But the variable b will not contain the value 130, because that's impossible - it will be wrapped around and you'll get a strange, negative value.
[ July 12, 2006: Message edited by: Jesper Young ]
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Anil Pattnaik:
Hello Everybody,
I have one doubt on Type casting,How can a byte can be type casted to an int as byte holds 8-bits memory but int holds 32 bits memory.Example:byte b=6;Please explain...


This is called assignment conversion.

It includes a narrowing primitive conversion.

This is from the Java Language Specification.

In addition, if the expression is a constant expression (�15.28) of type byte, short, char or int :

* 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!