I want know that the type of variable in my class for example:
int x=1;
char c=5;
System.out.println(x+c);// out put is 6
but i want to know the type of x+c
, whether it belongs to integer
or character
? and also want to print the result in console.
Is there any method to find the type? please help me with best answers.
Is there any method to find the type?
Well, from a research point of view you could read the Java Language Specification. In particular, section 15.18.2 explains how the +
operator works.
If you want to do this just from an execution-time point of view, there are two options:
You could autobox, and then see what the boxed type is:
Object o = x + c;
System.out.println(o.getClass()); // java.lang.Integer
You could write a method which is overloaded for all primitive types, and see which the compiler picks:
System.out.println(getCompileTimePrimitiveClass(x + c));
...
private static Class getCompileTimePrimitiveClass(int x)
{
return int.class;
}
private static Class getCompileTimePrimitiveClass(char x)
{
return char.class;
}
private static Class getCompileTimePrimitiveClass(byte x)
{
return byte.class;
}
// etc
See more on this question at Stackoverflow