Printing Type & Value with Varargs in Java


Create a Java program to demonstrate a method with varargs that prints the type and value of different arguments

  • The ArgumentPrinter class contains a static method printArgs that takes a variable number of arguments of type Object.
  • Inside the method, it iterates through each argument in the args array using an enhanced for loop.
  • For each argument, it prints the type of the argument (obtained using getClass().getSimpleName()) and its value.
  • In the main method, the printArgs method is called with multiple arguments of different types: an integer (7), a string ("Java"), a double (23.14), and a boolean (true).
  • When executed, the main method prints information about each argument to the console.

Source Code

public class ArgumentPrinter
{
	static void printArgs(Object... args)
	{
		for (Object arg : args)
		{
			System.out.println("Type : " + arg.getClass().getSimpleName() + ", Value : " + arg);
		}
	}
 
	public static void main(String[] args)
	{
		printArgs(7, "Java", 23.14, true);
	}
}

Output

Type : Integer, Value : 7
Type : String, Value : Java
Type : Double, Value : 23.14
Type : Boolean, Value : true

Example Programs