This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
I am not sure why you would want to do this. In any situation (at least that I can think of!), you would know the type of variable by looking at the source code.
Anyway, one possible use would be for debugging/troubleshooting, since it would be easier to dump out the type of variable to a console or logfile, as opposed to having to always cross reference back to the source.
So, with that in mind, here is simple solution which really just lets the compiler/JVM sort it all out. The class which actually determines the type of primitive is simply called "PrimitiveTester". All is does is have a bunch of static methods overloaded and returning a simple integer which represents the type of argument it was called with. As you can see, it would be easy to extend this type of solution, say with an overloaded getMax function which would return the max value for whatever type of variable it was called with (such as byte, short, int, long ).
Here is a short sample program which drives it:
And here is the sample output:
Anyway, hope this helps.
[ December 15, 2005: Message edited by: Don Morgan ] [ December 15, 2005: Message edited by: Don Morgan ]
Sorry to hijack this thread, but since the original poster's question was about something no one would ever use, and not on the exam anyway, I thought I'd respond to a comment that is relevant to the exam:
[Junilu]: This may interest you: Class Literal. This is used primarily when invoking methods using reflection but as far as I know, it is not part of the requirements for SCJP.
As a matter of fact, class literals can appear on the 5.0 exam. They are of interest in relation to synchronization - it's useful to understand that a static synchronized method is equivalent to a static method with a synchronized block, if that block acquires a lock on the Class instance for whatever class you're in. Which makes it useful to be able to refer to that instance with a class literal. I.e.
is equivalent to
[ December 15, 2005: Message edited by: Jim Yingst ]