How to determine the type of an Object in Java

4 Answers

0 votes
public class MyClass {
    public static void main(String args[]) {
        Object obj = "java";
        
        if (obj instanceof String) {
            String str = (String) obj;
            System.out.print(str);
        }
    }
}
 
 
 
/*
run:
 
java
 
*/

 



answered Oct 11, 2023 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        Object obj = 19485;

        if (obj instanceof Integer) {
            Integer i = (Integer) obj;
            System.out.print(i);
        }
    }
}
 
 
 
/*
run:
 
19485
 
*/

 



answered Oct 11, 2023 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        Object obj = 3.14f;

        if (obj instanceof Float) {
            Float f = (Float) obj;
            System.out.print(f);
        }
    }
}
 
 
 
/*
run:
 
3.14
 
*/

 



answered Oct 11, 2023 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        Double obj = 897401.2398;

        if (obj instanceof Double) {
            Double f = (Double) obj;
            System.out.print(f);
        }
    }
}
 
  
 
/*
run:
 
897401.2398
 
*/

 



answered Oct 11, 2023 by avibootz

Related questions

...