wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes String.format() - can i pass array ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String.format() - can i pass array ?" Watch "String.format() - can i pass array ?" New topic
Author

String.format() - can i pass array ?

Mohammed Yousuff
Ranch Hand

Joined: Oct 17, 2007
Posts: 198
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


My Thoughts : http://passion4java.blogspot.com
Try not to become a man of success but rather to become a man of value.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

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:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Mohammed Yousuff
Ranch Hand

Joined: Oct 17, 2007
Posts: 198
YES it worked , can you please explain me how it works , can i add more value to this argument ?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String.format() - can i pass array ?
 
Similar Threads
Hex ??
working with the DataBase
I passed, but I suffered the 44/80 locking penalty. Why?
Sorting Issue Help Needed Badly
How do the values change even if I am not passing the arrays with reference?