6

I couldn't find in Google.

Is in Java the same possibility to print with "{}" like in C# ?

C#:

  namespace Start
{
    public class Program
    {
        public static void Main(string[] args)
        {

            string a = "Hi";

            Console.WriteLine("{0}", a);
        }
    }
}

Java: ???

0

4 Answers 4

9

Yep, the syntax is inherited from C:

String a = "Hi!";
System.out.printf("%s\n", a);

The thing to be mindful of is that there are different kinds of formatting specifiers. The example uses %s, for formatting strings. If you're printing an integer or long, you use %d. There are also options for controlling things like min/max length, padding and decimal places. For the full list of options, check the JavaDoc of java.util.Formatter.

2

MessageFormat is what you are looking for:

public static void main(String[] args)
{
    String a = "Hi";
    MessageFormat mFormat = new MessageFormat("{0}");
    String[] params = {a};
    System.out.println(mFormat.format(params));
}
0

I think the best equivalence is java.util.Formatter.

For instance:

Formatter formatter = new Formatter().format("%s %d", "myString", 1);
System.out.println(formatter.toString());

Output:

myString 1

See here for more info.

0

You can Use also

System.out.format(.....);

Not the answer you're looking for? Browse other questions tagged or ask your own question.