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:

public class Demo {

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    for(int i=0; i<9; ++i){
        String input = br.readLine();
         showPremitive(input);//check for every input
    }     
}
public static void showPremitive(Object input){
    try{
            if (input instanceof Short)
                System.out.println("Primitive : short");
            else if(input instanceof Integer)
                System.out.println("Primitive : int");
            else if(input instanceof Long)
                System.out.println("Primitive : long");
            else if(input instanceof Float)
                System.out.println("Primitive : float");
            else if(input instanceof Double)
                System.out.println("Primitive : double");        
            else if(input instanceof Boolean)
                System.out.println("Primitive : bool");
            else if(input instanceof Character)
                System.out.println("Primitive : char");
            else if(input instanceof Byte)
                System.out.println("Primitive : byte");
            else  
                System.out.println("Reference : string");
         }  
    catch (InputMismatchException e){
        System.out.println("Exception occur = "+e);
    }
}

}

Output:

Reference : string
Reference : string
Reference : string
Reference : string
Reference : string
Reference : string
Reference : string
Reference : string
Reference : string

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:

     String input = br.readLine();
     showPrimitive(input);  // Note spelling!

     public void showPrimitive(String input) {
         if (input.equalsIgnoreCase("true") ||
             input.equalsIgnoreCase("false")) {
             System.out.println("Primitive : boolean");
             return;
         }
         try {
             long num = Long.parseLong(input);
             if (num >= Byte.MIN_VALUE && 
                 num <= Byte.MAX_VALUE) {
                 System.out.println("Primitive : byte");
             } else if (num >= Short.MIN_VALUE &&
                        num <= Short.MAX_VALUE) {
                System.out.println("Primitive : short");
             } else if (num >= Integer.MIN_VALUE &&
                        num <= Integer.MAX_VALUE) {
                System.out.println("Primitive : int");
             } else {
                System.out.println("Primitive : long");
             }
             return;
         } catch (NumberFormatException ex) {
             // continue
         }
         // deal with floating point (c.f. above)
         // deal with char: input length == 1
         // anything else is a String.
     }

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.

Advertisement