Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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: ???

like image 470
slisnychyi Avatar asked May 08 '13 10:05

slisnychyi


People also ask

What is printf () in Java?

The printf() method of Java PrintStream class is a convenience method to write a String which is formatted to this output Stream. It uses the specified format string and arguments.

Is there a printf in Java?

printf() method is not only there in C, but also in Java. This method belongs to the PrintStream class. It's used to print formatted strings using various format specifiers.

What is the difference between printf and print in Java?

println() prints a new blank line and then your message. printf() provides string formatting similar to the printf function in C. printf() is primarily needed when you need to print big strings to avoid string concatenaion in println() which can be confusing at times. (Although both can be used in almost all cases).


1 Answers

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.

like image 143
Barend Avatar answered Oct 01 '22 02:10

Barend