Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Implicit Narrowing Conversion

 
V Bose
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


If I understand right, in the above code, a copy of the value of c in Line 1 is copied into the final variable c in the method parameter in Line 2.
If Line 3 is uncommented, the compiler complains that c is a final variable.
However when I return c (In line 4), the implicit narrowing conversion from a 'compile time constant char' to a byte, does not happen. Why ?
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compiler does not know that every character c passed into the method m1 is going to fit in to a byte. So it gives the "possible loss of precision" error.

The compiler does not "run" your code to see that you do final char c = 'a'; //Line 1 before you do the call m1(c);
 
Jerry Zhang
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From char to any of byte or short, and vice verse, you need explicit cast
 
Vicken Karaoghlanian
Ranch Hand
Posts: 522
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jerry Zhang:
From char to any of byte or short, and vice verse, you need explicit cast


Well that is not entirely accurate. See the following code



The compiler does an implicit cast if the RHS is a compile time constant.
 
Jerry Zhang
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vicken,
thanks.
jerry
 
V Bose
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Barry Gaunt:
The compiler does not know that every character c passed into the method m1 is going to fit in to a byte. So it gives the "possible loss of precision" error.

But in the case of

the compiler does not worry that every character c may not fit into a byte?
Am I the only one who feels that the behaviour was not very intiutive Oh well, I'll just remember the scenario for the exam...
 
Vicken Karaoghlanian
Ranch Hand
Posts: 522
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by V Bose:

the compiler does not worry that every character c may not fit into a byte?


Yes, that is correct, because 'c' is a compile time constant.

This might help you understand compile time constant more
http://www.coderanch.com/t/193475/java-programmer-SCJP/certification/strange-things-happen-Check
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vee wrote:
Am I the only one who feels that the behaviour was not very intuitive


Nope, no way.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic