Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use printf("%s") for arguments passed to generic methods?

Tags:

java

printf

package genericMethods;

public class OverloadedMethods {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Integer[] integerArray = {1, 2, 3, 4, 5};
        Double[] doubleArray = {1.0, 2.0, 3.0, 4.0, 5.0};
        Character[] charArray = {'a', 'b', 'c', 'd'};

        System.out.println("A has: ");
        printArray(integerArray);
        System.out.println("B has: ");
        printArray(doubleArray);
        System.out.println("C has: ");
        printArray(charArray);
    }

    public static <T> void printArray(T[] array)
    {
        for(T element : array)
            System.out.printf("%s ", element);//why use %s instead of others? 

        System.out.println();
    }

}

My question is the method printArray() doesn't know what type of data is going to print out, and seems %d will occur error at run time - but isn't %s for String only ?

like image 611
Venzentx Avatar asked Mar 02 '13 19:03

Venzentx


People also ask

What is %s in printf?

%s and string We can print the string using %s format specifier in printf function. It will print the string from the given starting address to the null '\0' character. String name itself the starting address of the string. So, if we give string name it will print the entire string.

What is %d in Java printf?

The %d specifies that the single variable is a decimal integer. The %n is a platform-independent newline character. The output is: The value of i is: 461012. The printf and format methods are overloaded.


2 Answers

The issue is that you don't KNOW what type "element" will be. In your example, it could be Integer, Double, or Character. That being the case, you can't use %d or %lf, because those wouldn't work for types that aren't Integer (for %d) or Double (for %lf).

%s actually works for them all, because all Object types have a .toString(), so they can all be converted to Strings for printing.

like image 129
billjamesdev Avatar answered Nov 15 '22 17:11

billjamesdev


The use of %s will result in the toString() method being called on the object, and thus will work for any type T.

like image 35
NPE Avatar answered Nov 15 '22 17:11

NPE