Format String and characters
In this chapter you will learn:
- How to format individual character and how to format string
- How to pass in two strings into the format string
Formatting Strings and Characters
To format an individual character, use %c. This causes the matching character argument to be output, unmodified.
To format a string, use %s.
format('%.15s', String str) (Display at most 15 characters in a string)
The following code use %s specifier and number to control the output width. It will only display at most 15 characters in a string.
import java.util.Formatter;
//from j a v a2s. c o m
public class MainClass {
public static void main(String args[]) {
Formatter fmt = new Formatter();
fmt = new Formatter();
fmt.format("%.15s", "Formatting with Java is now easy.");
System.out.println(fmt);
}
}
The output:
Pass in two strings
public class Main {
public static void main(String args[]) {
//from j a va 2 s .c o m
System.out.println(
String.format("Hi %s at %s", "java2s.com", "your screen"));
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » String