Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Does String.Format exist in Java like in C#?

Tags:

java

c#-3.0

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); 
like image 910
Snow_Mac Avatar asked Jun 26 '11 06:06

Snow_Mac


3 Answers

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)

like image 148
a_horse_with_no_name Avatar answered Oct 21 '22 13:10

a_horse_with_no_name


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.

like image 28
andri Avatar answered Oct 21 '22 13:10

andri


String myString = String.format("Your lucky numbers are: %d, & %d", myNum, myNumSq);
like image 33
H-H Avatar answered Oct 21 '22 12:10

H-H