• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

type conversion

 
Jason Attin
Ranch Hand
Posts: 232
2
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI guys, given this codefrom Glenn, Mitchell. OCAJP Oracle Certified Associate Java SE 8 Programmer Practice Exams (Kindle Locations 10550-10552). Enthuware. Kindle Edition,

apparently compiles because a char (b) is essentially a number. SO that got me thinking and I tried something:

That is essentially the same as above, but it doesn't compile. I mean a char is 16bits and a byte is only 8 so fair enough if it doesn't compile, but then why does it work in the switch statement?


 
Henry Wong
author
Marshal
Pie
Posts: 22094
88
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

First, these are two different java statements/features, which have different rules, so comparing why one works while the other is a compiler error, doesn't make too much sense.

However, if you are asking why the compiler knows that the first is a valid comparison while the other is not a valid assignment... In the first case (no pun intended), the value being checked is a compile time constant, and hence, can be confirm to be in range. In the second case, neither is a compile time constant, and hence, can't be implicitly converted.

Henry
 
Jason Attin
Ranch Hand
Posts: 232
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK thanks for clarifying it
 
Mala Gupta
Author
Ranch Hand
Posts: 363
11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An interesting observation, Jason.

I modified your code. Do you think the following modified version of your code will compile?


Thanks.

With much respect,
Mala
 
Jason Attin
Ranch Hand
Posts: 232
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Without trying the code, probably not because char is a 16 bits and byte is 8
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic