0
What is meant by,
String.format() method in java
2 Antworten
+ 2
String.format() is a way to format strings in specific ways. If you know how System.out.printf() works then its the exact same but instead of printing out to console, it creates a String Object for you. If you have never used printf() here is my short summary of what you can do
let's say you have a String where you want to format as shown:
"Date: [Month]/[Day]/[Year], Name:[name] Age: [Age]"
and you want to replace everything in square brackets with the required info.
It is possible to do it like this:
String a = "Date: " + monthVar + "/" + DayVar etc.
But you can tell that it can get messy very fast, so a better solution is to use String.format()
String b = String.format("Date: %s/%d/%d, Name: %s, Age: %d", monthVar, dayVar, yearVar, nameStringVar, AgeVar);
again printf() works the same way. Sidenote: %s and %d will be replaced by the variables after the very first comma, you can have as many parameters as there are %s's or %d's.
There is a lot more you can do with this so if you want to read more, the javadocs formatter class is a good read.
https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html
or this dzone article
https://dzone.com/articles/java-string-format-examples
Hope this helps
Happy coding
0
your article is very helpful.
thank you..!