This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "casting" Watch "casting" New topic
Author

casting

usha prithvi
Ranch Hand

Joined: Jun 22, 2005
Posts: 31
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

Joined: May 22, 2003
Posts: 657

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

Joined: Feb 05, 2001
Posts: 17249
    
    6

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


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
usha prithvi
Ranch Hand

Joined: Jun 22, 2005
Posts: 31
I am glad to get replies from great guys like u.
Thankz
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

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

Joined: Jul 08, 2005
Posts: 4
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"
 
 
subject: casting
 
Similar Threads
Why is a good idea do casting if there is a possibility of lose precision?
Question about ~ operator
forward refrerences
Casting rules
AutoBoxing - Compilation Error