Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Below is the code which implements a method to compare the object type of a given object: 

public void test(Object value) {

        if (value.getClass() == Integer) {

            System.out.println("This is an Integer");

        }else if(value.getClass() == String){

            System.out.println("This is a String");

        }else if(value.getClass() == Float){

            System.out.println("This is a Float");

        }

}

I call the method like below: 

test("Test");

test(12);

test(10.5f);

But it’s not working. Can anyone tell me how to work on this?

1 Answer

0 votes
by (19.7k points)

You need to add the .class file to the code like below: 

if (value.getClass() == Integer.class) {

    System.out.println("This is an Integer");

else if (value.getClass() == String.class) {

    System.out.println("This is a String");

}

else if (value.getClass() == Float.class) {

    System.out.println("This is a Float");

}

Interested in Java? Check out this Java tutorial by Intellipaat.  

Related questions

0 votes
1 answer
0 votes
1 answer
asked Apr 15, 2021 in Java by Jake (7k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...