Skip to content
Advertisement

Check if input is of Primitive type in Java?

I have to check for each input and print out if it is an instance of a primitive or referenced type. But I am getting same output each time.

Note: I do search SO, but no luck. How can I check if an input is a integer or String, etc.. in JAVA?

Code:

JavaScript

}

Output:

JavaScript

Advertisement

Answer

Before I address your question, you appear to have a number of misconceptions about Java and Scanner.

  1. The stuff you read from the input stream is characters or bytes. Those characters or bytes can be interpreted as representing many things … but it is a matter of interpretation. Furthermore the same sequence of characters could mean different things … depending on how you choose to interpret them; e.g. “12345” could easily be interpreted as a string, an integer or a floating point number. And if you map that to Java types, then that could be String, short, int, long, float or double … and many more besides.

    The point is … you (the programmer) have to tell the parser (e.g. Scanner) what to expect. You can’t expect it to guess (correctly).

  2. Assuming that you had managed to read as reference or (true) primitive types, you would not be able to assign them to the same variable. Integer etcetera are NOT primitive types!

  3. The Scanner.readLine() method reads and returns the rest of the current line as a String. It makes no attempt to interpret it. The Java type of the result is String … and nothing else.


So how should you implement it. Well here’s a sketch of a crude version:

JavaScript

Note that the above entails using exceptions in a way that a lot of people would object to. However, doing a better job is tricky … if you are going to support all possible values of each of the primitive types.

But I would return to a point I made earlier. If you look at the code above, it is making hard-wired choices about how to interpret the input. But how do you know if you are making the right choices? Answer: you have to specify how the input parsing should behave … not rely on something else to give you the “right” answer by magic.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement