How can I check a variable's type in Java 8, similar to typeof in JavaScript?

In JavaScript, we use typeof to check a variable’s type, but what’s the closest equivalent to typeof Java in Java 8? While instanceof works for object types, it doesn’t support primitives.

Are there better or more flexible ways in Java 8 to determine the type of a variable at runtime?

Ah yes, I ran into this when switching from JavaScript to Java too.

In Java 8, instanceof is your go-to for checking if an object is of a certain type:

java
Copy
Edit
if (myVar instanceof String) {
    System.out.println("It's a String!");
}

But yeah, this won’t help with primitives like int or double.

For those, you usually already know the type at compile time because Java is statically typed.

If you really need to check dynamically, boxing them into their wrapper classes helps.

@mehta_tvara Good question! In Java 8, I usually use .getClass().getSimpleName() if I want to print the type of an object dynamically:

java
Copy
Edit
Object obj = "hello";
System.out.println(obj.getClass().getSimpleName()); // Outputs "String"

Just be careful, it only works for non-primitives. For primitives, you’d have to wrap them (e.g., use Integer instead of int).

It’s not exactly typeof like in JavaScript, but it’s the closest runtime equivalent I’ve used.

Coming from JavaScript, I missed typeof too!

In Java 8, everything’s more rigid. If you’re working with objects, you can check the type like this:

java
Copy
Edit
if (myObj instanceof List) {
    // Do something
}

For primitives, I typically use method overloading or reflection if I absolutely need to check types dynamically.

But in most Java apps, type checks are less common because you know the type ahead of time thanks to static typing.