7

Something I discovered I like about C# are properties & String.Format.

Does something like String.Format from C# exist in Java?

C# ex:

int myNum = 2; 
int myNumSq = myNum * myNum;
String MyString = String.Format("Your lucky numbers are: {0}, & {1}", myNum, myNumSq); 
1

3 Answers 3

9

Yes, the class in question is "MessageFormat":

http://download.oracle.com/javase/6/docs/api/java/text/MessageFormat.html

MessageFormat.Format("Your lucky numbers are: {0}, & {1}", myNum, myNumSq);

(Not sure if auto-boxing will work correctly in this case - you might need to convert the int to an Integer first)

Sign up to request clarification or add additional context in comments.

1 Comment

Auto boxing works, its for precisely this use case it was introduced.
5

It' even called String.format():

String myString = String.format("Your lucky numbers are: %d, & %d", myNum, myNumSq);

This method is available since Java 1.5.

Comments

2
String myString = String.format("Your lucky numbers are: %d, & %d", myNum, myNumSq);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.