• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to check a datatype of a variable  RSS feed

 
Kok Lum Chan
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I am wondering is there a way to check for a variable data type ?



Thanks in advance.


 
Hauke Ingmar Schmidt
Rancher
Posts: 436
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java has strong, static typing. If you declare a "float m" it *is* an float. No exception.

Do you think you may have different types because of the different literals in line 5 and line 6, i.e. "8" vs. "8f"?
 
Kok Lum Chan
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Hauke,

I would expect both in line 5 and 6 be float.

In foxpro language, there is a function called VARTYPE() to confirm such claim and wondering does Java has something similar.

Understand that "instanceof" can be used to test the class type but what about primative type ?

 
Hauke Ingmar Schmidt
Rancher
Posts: 436
2
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java has the distinction between "primitive" types and object types. Objects are of one or several types, namely of their class, all parent classes (one at a time, of course) and all implemented interfaces (and all interfaces implemented by parent classes). You can test with instanceof if a specific type is among these.

Primitive types behave completely different*. They are. Just think of a type as "how to interpret this pattern of bits directly". You can't inspect the type of the "bit pattern", it is defined by the type of the variable. You can't just interpret the pattern as something else, even if you want to. That is why Java is static and strongly typed.

You can, of course, convert from one type to another, e.g. a char as an int (casting), which is sometimes done automatically, sometimes needed to be done specifically.

So, in short, a float variable is of type float. No chance for anything else, so no need (and possibility) to check.

* Autoboxing hides some of the distinctions.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the better question is why would you need to? What situation do you have that requires you to test this sort of thing?
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!