How To Format A String, integer, floating point number, character using the format() Method
Coding River
How To Format A String, integer, floating point number, character using the format() Method
In this video, we will discuss on the Java String format() method, which we can use to format a String. Actually, we can use this method to perform many operations like for example joining Strings and formatting the output of the String that has been joined.
In this video we will have a look at some examples on how to use this method.
- In the first example, I will show you how to use the format() method to convert values of certain types into Strings and then joining them
String name = “Brandon Cole”;
Since this method returns a String, we will declare a String variable
String string_format = String.format(“My name is %s” , name);
System.out.println(string_format);
The output in the console will be: My name is Brandon Cole As you can notice the Strings have been joined. The %s represents the argument position, that is used to pass the String variable name.
Here are the statements, if you want to pass other variable types
String str1 = String.format("%d", 15); // for Integer value
String str3 = String.format("%f", 16.10); // for float value
String str4 = String.format("%x", 189); // for Hexadecimal value
String str5 = String.format("%c", 'P'); // for char value
String str6 = String.format("%o", 189); // for octal value
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
System.out.println(str4);
System.out.println(str5);
System.out.println(str6);
}
}
- In the next example I want to show you how to play around formatting arguments
double height = 1.86;
Since this method returns a String, we will do a
String string_format = String.format(“My height is %.4f” , height); System.out.println(string_format);
The output in the console will be: My height is 1.8600 Notice that our decimal number format has changed because of what we specified in the argument by writing %.4f which means that the decimal number needs to be formatted to have four figures at its decimal part
Second example with Integer values
int number = 28;
String formattedString = String.format("%06d", number); System.out.println(formattedString);
The result in the console will show : 000028
The %06d formatted the integer value stored in variable number by adding zeros at the beginning of the integer value so that it will be made up of 6 figures
Another example with Strings
String str1 = "cool string"; String str2 = "28";
String formattedstring = String.format("My String is: %1$s, %1$s and %2$s", str1, str2); System.out.println(formattedstring);
%1$ and %2$ are used for specifying argument positions. %1$ is used for the first argument and refers to the first String str1 %2$ is used fo ... https://www.youtube.com/watch?v=Q8PYQyhTXT4
28069963 Bytes