Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 13th, 2012  |  syntax: None  |  size: 1.26 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. String formatting with variable number of arguments in java
  2. String Str = "Entered number = %d and string = %s"
  3.        
  4. List<Objects> args = new ArrayList<Objects>();
  5. args.add(1);
  6. args.add("abcd");
  7.        
  8. String formatted = String.format(str, args.toArray());
  9.        
  10. Entered number = 1 and string = abcd
  11.        
  12. String str = "Entered number = %d and string = %s";
  13.  
  14.     List<Object> args = new ArrayList<Object>();
  15.     args.add(1);
  16.     args.add("abcd");
  17.  
  18.     System.out.println(String.format(str, args.toArray()));
  19.        
  20. Entered number = 1 and string = abcd
  21.        
  22. The last formal parameter in a list is special;
  23. it may be a variable arity parameter, indicated by an
  24. elipsis following the type.
  25.  
  26. If the last formal parameter is a variable arity parameter of type T,
  27. it is considered to define a formal parameter of type T[].
  28. The method is then a variable arity method. Otherwise, it is a fixed arity
  29. method. Invocations of a variable arity method may contain more actual
  30. argument expressions than formal parameters. All the actual argument
  31. expressions that do not correspond to the formal parameters preceding
  32. the variable arity parameter will be evaluated and the results stored
  33. into an array that will be passed to the method invocation.
  34.        
  35. final String myString = String.format(Str, 1, "abcd");