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

casting

 
usha prithvi
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

In the below code, why doesn't the compiler show casting error?Instead itz compiling without error.Can you explain why? public class One
{
private final int i =10;
private byte k = i;
}
Here int value is assigned to byte.Then compiler should say type mismatch.right?Please correct me!

Thankz
 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compiler's smart enough to know that the final int variable cannot be changed and therefore its value of 10 will always fit into a byte.
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yep, it only starts to complain when you set the final int to a value that would be greater than what a byte can fit.

The private is a key to the answer.

Mark
 
usha prithvi
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am glad to get replies from great guys like u.
Thankz
 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The private is a key to the answer.
How does the "private" modifier affect this? I would expect the same behavior if the int was public and final...

Example:
[ July 14, 2005: Message edited by: Steve Morrow ]
 
Ganesh Hariharan
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

its all because of final key word.
this code also works.
public class One {
public final int i =10;
public byte k = i;
}
if you remove final keyword
public class One {
private int i =10;
private byte k = i;
}
it will show "Type Mismatch: Cannot convert from int to byte"
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic