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

disabling automatic type casting

raj kothari
Greenhorn

Joined: Nov 21, 2005
Posts: 24
I am writing an method which take int as input. I want to ensure that the argument received is exactly of int type and not of byte, short, char.
Like that I am writing many methods in which I expect the exact variables. How can I disable the automatic type conversion at the method level, and how do I check the exact type else give the error to calling function and return.
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
You can't.

If the formal parameter is an int, the actual parameter can be an int or any smaller integral type. You can't tell what it was.

What is the higher-level thing that you're trying to achieve? Since your suggested approach is impossible, you will have to think of another approach to achieve the same higher-level feature.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Hmmm... I suppose you could overload the method to "catch" narrower types.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39436
    
  28
What would happen if you used Integer instead of int? You would get autoboxing, so an int would be acceptable. I tried it with a short, and it wouldn't compile.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14273
    
  21

Can you explain why you have this requirement that the argument must be exactly of a specific type? I'm curious why you would need this, and I can't think of what problem this would solve.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
Seems like I missed some possible approaches that, while not what the original poster asked for (which remains impossible), are quite close. Well done other bartenders!

However, the requirement still seems bizarre and pointless. Unless it's an interview/homework question, we need to know what the real higher-level requirement is.
 
 
subject: disabling automatic type casting