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

Article author: Andrei Olegovich