aspose file tools*
The moose likes Beginning Java and the fly likes (cast)ing rules Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "(cast)ing rules" Watch "(cast)ing rules" New topic
Author

(cast)ing rules

Leroy J Brown
Ranch Hand

Joined: Dec 02, 2007
Posts: 71
So,
I'm reading about casts which is a subject that I find odd and was wondering if anyone knew of a resource where I could find say a table or explicit list of what primitives require an explicit cast statement when their operated on ie



Ideally I'd like to print the sucker out and stick it on my wall next to my Precedence of Operators table.
Any ideas?
[ June 17, 2008: Message edited by: Tristan Rouse ]
Ashish Hareet
Ranch Hand

Joined: Jul 14, 2001
Posts: 375
Tristan,

The simplest rule to follow with primitive casting is that the result of an arithmetic operation(excluding ++ & -- operators) will atleast be of type int or of the larger primitive type used in the operation.

For more you can read the following in the JLS
* http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.2
* http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.3

HTH
Ashish Hareet
Leroy J Brown
Ranch Hand

Joined: Dec 02, 2007
Posts: 71
Thanks friend
Yoogesh Patil
Greenhorn

Joined: Jun 24, 2008
Posts: 1
class Casting {
public static void main (String [] args){
long ln = 130L;
byte by = (byte) ln;
System.out.println ("\n Casting value is: "+by);
}
}

The answer is: -126
My question is: how does it works conceptually?
means how does jvm handles this code if long is greater that 127 (byte value limit)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39784
    
  28
Welcome to JavaRanch, Yoogesh Patil.

Please don't ask new questions on somebody else's thread.

If you write out the bits for 130 in 16 bits, which are the same as a long only with fewer 0s, you get
0000 0000 1000 0010.
When you cast to a byte you lose all but the rightmost 8 bits, leaving
1000 0010.
In two's complement that is -126.

If you want any more information please start a new thread.
[ June 25, 2008: Message edited by: Campbell Ritchie ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: (cast)ing rules