Use overloaded methods to print array of different types in Java


In method overloading, the class can have multiple methods with the same name but the parameter list of the methods should not be the same.

Overloaded methods can be used to print an array of different types in Java by making sure that the parameter list of the methods contains different types of arrays that can be printed by the method.

A program that demonstrates this is given as follows −

Example

 Live Demo

public class Demo {
   public static void arrPrint(Integer[] arr) {
      System.out.print("
The Integer array is: ");       for (Integer i : arr)          System.out.print(i + " ");    }    public static void arrPrint(Character[] arr) {       System.out.print("
The Character array is: ");       for (Character i : arr)          System.out.print(i + " ");    }    public static void arrPrint(String[] arr) {       System.out.print("
The String array is: ");       for (String i : arr)          System.out.print(i + " ");    }    public static void arrPrint(Double[] arr) {       System.out.print("
The Double array is: ");       for (Double i : arr)          System.out.print(i + " ");    }    public static void main(String args[]) {       Integer[] iarr = { 8, 1, 5, 3, 9 };       Character[] carr = { 'A', 'B', 'C', 'D', 'E' };       String[] sarr = { "Jane", "Amy", "John", "Tim", "Sara" };       Double[] darr = { 7.3, 5.9, 2.5, 3.7, 1.4 };       arrPrint(iarr);       arrPrint(carr);       arrPrint(sarr);       arrPrint(darr);    } }

Output

The Integer array is: 8 1 5 3 9
The Character array is: A B C D E
The String array is: Jane Amy John Tim Sara
The Double array is: 7.3 5.9 2.5 3.7 1.4

Updated on: 30-Jun-2020

772 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements