-4

How get premtive variable data type in print statment . tell method that tell about data type of variable?

4 Answers4

1

If you are invoking a method like

System.out.printf("%d", 5);

then System.out.printf doesn't actually receive a primitive argument: the variadic parameter is of type Object[], so the 5 will be autoboxed to Integer in this case.

However, there is no token listed in the formatter syntax documentation which will print the parameter's type in the string.


You can write overloaded methods which are specialized for each of the primitive types:

String typeName(boolean _) { return "boolean"; }
String typeName(byte _) { return "byte"; }
String typeName(short _) { return "short"; }
String typeName(int _) { return "int"; }
String typeName(long _) { return "long"; }
String typeName(float _) { return "float"; }
String typeName(double _) { return "double"; }
String typeName(char _) { return "char"; }

You can then invoke this like:

int a = 5;
float f = 4.5f;
System.out.print(typeName(a));  // outputs "int"
System.out.print(typeName(f));  // outputs "float"
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

You can't do this with primitive types, only objects.

SamTebbs33
  • 5,507
  • 3
  • 22
  • 44
0

You can print Wrapper Type, not primitive type. Hope this will help :

int i=5;
System.out.println(((Object)i).getClass().getName());
Rahman
  • 3,755
  • 3
  • 26
  • 43
-1

For any object x, you could print x.getClass().getName()

Idos
  • 15,053
  • 14
  • 60
  • 75
shas
  • 703
  • 2
  • 8
  • 31