aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes data type Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "data type" Watch "data type" New topic
Author

data type

bhavneet kaur
Ranch Hand

Joined: Apr 08, 2012
Posts: 32


why its showing error in b2=b1+1; treating b2 it as int???
Rameshwar Soni
Ranch Hand

Joined: Feb 03, 2011
Posts: 247
bhavneet kaur wrote:

why its showing error in b2=b1+1; treating b2 it as int???


It is not treating variable "b2" as int, infact it is byte as you have declared.

But b1 + 1 which you are assigning to byte variable "b2" is int. So how can you assign an int to a byte variable.

SO you need to do type casting



Rameshwar Soni
Ranch Hand

Joined: Feb 03, 2011
Posts: 247
Read this (<---click) for more details.
bhavneet kaur
Ranch Hand

Joined: Apr 08, 2012
Posts: 32
but how then b1 + 1 is a int , i have declared bi also byte???
Rameshwar Soni
Ranch Hand

Joined: Feb 03, 2011
Posts: 247
bhavneet kaur wrote: but how then b1 + 1 is a int , i have declared bi also byte???


Yes you declared b1 and b2 both as byte. The range of byte data type is -127 to 128. So when you are writing


i.e. you are storing 5 in b1. Here there won't be any error, since 5 is in the range of -127 to 128

When you wrote


Here the Java compiler has no idea about what is the answer of "b1 + 1" which you are storing in byte variable b2.

The answer of "b1 + 1" can be 50 or 20 or 129 or 300 etc. depending on the value of b1. Fine.

So compiler thinks what if the answer of "b1 + 1" is greater than 128 (i.e. the range allowed in byte variable.).

Therefore compiler gives you an error, saying that variable "b2" in which you are storing "b1 +1" has to int or you explicitly do the type casting i.e.


bhavneet kaur
Ranch Hand

Joined: Apr 08, 2012
Posts: 32

is this in cases of all data type???
Rameshwar Soni
Ranch Hand

Joined: Feb 03, 2011
Posts: 247
For the data type byte and short it happens the same way, since the default data type for integer literals is int. For long it doesn't since we have to write or append an L at the end of number i.e.
long value = 123456L

For float, you have to write F at the end since by default its double, so this case doesn't arises.
bhavneet kaur
Ranch Hand

Joined: Apr 08, 2012
Posts: 32
thank you very much , you explained so well

hey i have also submitted a question on increment and decrement can you also explain ?
Rameshwar Soni
Ranch Hand

Joined: Feb 03, 2011
Posts: 247
Are you talking about this (<--Click here) one ?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: data type