How to declare a function argument that can accept any type in Java

2 Answers

0 votes
public class Program {
    public static <T> void AcceptAnyType(T x) {
        if (x instanceof String) {
            System.out.println("The argument is a String.");
        } else if (x instanceof Integer) {
            System.out.println("The argument is an Integer.");
        } else {
            System.out.println("The argument is of type: " + x.getClass().getName());
        }
    }
    public static void main(String[] args) {
        AcceptAnyType(384);      // Integer
        AcceptAnyType("ABCD");   // String
        AcceptAnyType(3.14);     // Double
    }
}



/*
run:

The argument is an Integer.
The argument is a String.
The argument is of type: java.lang.Double

*/

 



answered Jul 31, 2025 by avibootz
0 votes
public class Program {
    public static void AcceptAnyType(Object x) {
        if (x instanceof String) {
            System.out.println("The argument is a String.");
        } else if (x instanceof Integer) {
            System.out.println("The argument is an Integer.");
        } else {
            System.out.println("The argument is of type: " + x.getClass().getName());
        }
    }

    public static void main(String[] args) {
        AcceptAnyType(384);      // Integer
        AcceptAnyType("ABCD");   // String
        AcceptAnyType(3.14);     // Double
    }
}



/*
run:

The argument is an Integer.
The argument is a String.
The argument is of type: java.lang.Double

*/

 



answered Jul 31, 2025 by avibootz
...