Quick Reach
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class string_example {
public static void main(String []args) {
int yourage;
float yoursal;
yourage = 25;
yoursal= (float)5000.99;
String Strex;
Strex =String.format(“Your age is: %d and you salary is: %f”,yourage,yoursal);
System.out.println(Strex);
}
}
|
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
Leave A Comment?