Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String.format() - can i pass array ?

 
Mohammed Yousuff
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can i pass a int Array to a method which has variable length argument.For example we have String.format method , where i haev to pass the aregument as array. because i will find the argument length only at the runtime.

please see the code below.

public String getDisplayMobileNumber(String MobileNumber,PhoneDataObject phoneDO){

int[] numberOfFields = phoneDO.getNumberOfFields();
Object[] phoneNumberSplitUps = new Object[numberOfFields.length];
int pointer = 0;
for(int tempCounter = 0 ;tempCounter < numberOfFields.length;tempCounter++){

String temp = MobileNumber.substring(pointer,(pointer + numberOfFields[tempCounter]));

/** Moving the Pointer*/
pointer += numberOfFields[tempCounter];

phoneNumberSplitUps[tempCounter] = temp;

}

return String.format(phoneDO.getDisplayPrintfPattern(),phoneNumberSplitUps);

}


Any Suggessions ?. thanks for your help
 
Rob Spoor
Sheriff
Pie
Posts: 20667
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you tried it?

The answer is yes you can, but the array needs to be Object[]. Using something like String[] will work but will give you a compiler warning; in that case just cast it to get rid of the warning:
 
Mohammed Yousuff
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
YES it worked , can you please explain me how it works , can i add more value to this argument ?
 
Rob Spoor
Sheriff
Pie
Posts: 20667
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stirng.format uses the technique called varargs. This idea has been in C and C++ for years and since Java 5.0 it finally made it to Java as well.

What it means is that whenever you see a parameter with ... behind the type, it means you can enter 0 or more of that type. It must always be the last parameter.

Now in Java, this is just a little syntactic sugar. The compiler actually turns it into an array. For example:

is turned into this:

It just saves you the trouble of creating an Object[] each time.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic