aspose file tools
The moose likes Beginning Java and the fly likes Can you cast a method argument? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Can you cast a method argument?" Watch "Can you cast a method argument?" New topic
Author

Can you cast a method argument?

David Junta
Ranch Hand

Joined: Dec 10, 2000
Posts: 86
I have a method:
public static void methodName( long x , int y )
If I want to use this method but some of my y's are longs, can i do this in those cases:
methodName( sampleInteger , ( int )( sampleLong ) );
I got a compile error but I'm wondering if there is another way to do this. If not, do you have to make a new, slightly different method for these cases?
Any help would be much appreciated
Steve Fahlbusch
Ranch Hand

Joined: Sep 18, 2000
Posts: 492
    
    2

Is the below an example of what you are discussing? If so
it works fine.

John Bateman
Ranch Hand

Joined: Mar 09, 2000
Posts: 320
Originally posted by David Junta:
If I want to use this method but some of my y's are longs, can i do this in those cases:
methodName( sampleInteger , ( int )( sampleLong ) );

Hi
IMHO if some of your "y's" are long, then make the parameter long. Then just cast the result to an int if and when you need it. This will guarantee you don't 'lose' information when converting a potentially long 'long' into an int.

Since an int is 32 bit and a long is 64 you could run the risk of losing information when you perform a 'narrowing cast' (64 bits pushed into 32 bits), or, casting your long variable to an int in the method call. But if you have a 32 bit (int) and cast it into a 64 bit (long) you NEVER will lose any information.
Hope this helps.

[This message has been edited by John Bateman (edited March 15, 2001).]


SOURCE CODE should be SURROUNDED by "code" tags.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can you cast a method argument?
 
Similar Threads
howto call action in webapp from action
Please help with sorting multiple columns
Return type void..
Method Invocation Problem
Significance of Overloading