How To Format A String, integer, floating point number, character using the format() Method
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.
1. 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);
}
}
2. 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 for the second argument and refers to the second String str2
#codingriver
#java
#programming
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «How To Format A String, integer, floating point number, character using the format() Method», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.