Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String formatting with variable number of arguments in java

Consider a string.

String Str = "Entered number = %d and string = %s"

Let us say I have a list of objects

List<Objects> args = new ArrayList<Objects>();
args.add(1);
args.add("abcd");

Is there any way in which I can substitute these args into Str , so that i get a string like "Entered number = 1 and string = abcd " ?

By generalizing this I was planning to dump all the questions and arguments in a file (like json) and execute them at run time. Please do let me know if there are better ways to do this.

like image 676
Nithin Avatar asked Dec 19 '11 10:12

Nithin


Video Answer


1 Answers

Try:

String formatted = String.format(str, args.toArray());

This gives:

Entered number = 1 and string = abcd
like image 188
dogbane Avatar answered Nov 07 '22 07:11

dogbane