Java string format – An example to learn formatting in Java

The string formatting in Java

The Java String class comes up with the format() method that enables us to create the formatted strings. The formatted strings can also be created by using Java printf() method, however, Java string format method of the String class can be reused whereas the printf() method can be used once.

See the printf method with examples here

The Syntax of format Java method

The syntax of String.format method is:

Strex.format(“String to be formatted, args”)

Where Strex is an object of the string class.

Return Value of Java format method

The value returned by the string.format method is a formatted string.

Java format string example

The following example shows how to use the string format Java method to create a formatted string in the Java program. We have declared two variable, one is an integer type while the other is the float. Both variables are assigned the values, after the declaration. After that, a string object is created where we will perform formatting by using the format Java string method.

See the example by clicking the link below:

Experience this online

The output will be:

Your age is: 25 and you salary is: 5000.990234

As you can see we used %d for int and %f for the float value in Java string format method to return a formatted string.

Also see: Java Strings

Was this article helpful?

Related Articles

Leave A Comment?