Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (9.5k points)

Below is Java code, which uses String.format() to support variable number of arguments: 

String.format("Hello %s! ABC %d!", "World", 123);

//=> Hello World! ABC 123!

Can anyone tell me how to make my own function to accept a variable number of arguments?

1 Answer

0 votes
by (19.7k points)

You can implement a method like below which just renames format (or print): 

public PrintStream print(String format, Object... arguments) {

    return System.out.format(format, arguments);


Check the below code which shows how to implement it: 

private void printScores(Player... players) {

    for (int i = 0; i < players.length; ++i) {

        Player player = players[i];

        String name   = player.getName();

        int    score  = player.getScore();

        // Print name and score followed by a newline

        System.out.format("%s: %d%n", name, score);



// Print a single player, 3 players, and all players



printScores(player2, player3, player4);



// Output

Abe: 11

Bob: 22

Cal: 33

Dan: 44

Interested in Java? Check out this Java tutorial by Intellipaat.


Related questions

Browse Categories