Search code examples
javatypesprimitive-types

How would one go about finding out the type of System.out.print()


Let say I have set some variable as such :

   byte a = 2;
   short b = 1;
   int c = 30;
   long d = 5;
   char e = 'E'; 
   float f = 2.21f;
   double g = 34.12;
   boolean h  = false;

I want to find out the value of the following calculation :

(short)(g + a) != g == true || h && ! ( d % b >0) && d * f == e

So I would go with :

System.out.println((short)(g + a) != g == true || h && ! ( d % b >0) && d * f == e;

This would return true. I know it's most likely a boolean. Let's say I wanted to make sure and have a command to print both the result and the type how would I do it? I want it to be a solution that can be reproduced over and over again.


Solution

  • System.out.println() is heavily overloaded. You may do the same with your own method.

    static void printValueAndType(int i) {
        System.out.println("" + i + " int");
    }
    
    static void printValueAndType(boolean b) {
        System.out.println("" + b + " boolean");
    }
    
    static void printValueAndType(Object obj) {
        System.out.println("" + obj + ' ' + obj.getClass().getName());
    }
    

    There are 8 primitive types in all: boolean, byte, short, char, int, long, float and double (you mentioned the all in the code in the question already). You will probably want a method for each.

    Let’s try it out, why not?

        printValueAndType((short)(g + a) != g == true || h && ! ( d % b >0) && d * f == e);
    

    Output:

    true boolean