Determining the type of a variable in Java
Introduction
The instanceof operator helps determine whether an object belongs to a certain type
Example
Print the type of the object to the screen
public class Main { public static void main(String[] args) { int varD = 1.1; test(varD); // Convert double to int test(int(varD)); } public static void test(Object value) { if (value instanceof Integer) { System.out.println("This is Integer"); } else if (value instanceof String) { System.out.println("This is String"); } else if (value instanceof Float) { System.out.println("This is Float"); } else if (value instanceof Double) { System.out.println("This is Double"); } } }
This is Double This is Integer
In other languages
- C : there is no such function.
-
C++
:
a similar problem is solved by the function
typeid()
Read the article: «How to determine the type of a variable C++»
- C# : there is a similar function GetType()
-
Go
:
the function
typeof()
is available from the reflect library
-
JavaScript
:
this task is solved by
typeof()
Read the article: «How to determine the type of a JavaScript variable»
- Python : functions type() and isinstance()
Article author: Andrei Olegovich