PrintStream is a class under the java.io package. The System.out is a PrintStream object. This means that you can just other methods after System.out. This class has two formatting methods that you can use to replace print or println which are format and printf. This two methods are the equivalent.
Definition:
public PrintStream format(String format, Object... args){}
The definition above returns an object of PrintStream class. It has two parameters. First a string named format. This accepts accepts a format specifier which is a special character use by the second parameter to specify the data type to be use. The second parameter is a varargs of type Object. Meaning it can accept zero or more arguments from the first parameter.
NOTE:
1. format method is overloaded. Meaning it has other forms that differs in parameters from the top definition but uses the same method name format.
2. format specifier begins with percent sign (%) and then followed by a character for the type of argument. %n here means new line. You can add an optional flag in between the % and the character.
====================
import java.util.Scanner;
class FormattingStringClass {public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter your name: ");
String input1 = scan.next();
System.out.print("Enter your age: ");
int input2 = scan.nextInt();
System.out.print("Enter an amount: ");
double input3 = scan.nextDouble();
System.out.format("name: %s%n" +
"age: %d%n" + "amount: %.2f", input1, input2, input3);
}
}====================
Result:
Enter your name: HomieEnter your age: 100Enter an amount: 5.5555name: Homieage: 100amount: 5.56
NOTE:
1. Converters, flags, specifiers can be found in java.util.Formatter most especially if you want to specify the date and time.
2. In the above code, .2 means it will display 2 decimal places to the right of dot and whatever is in the left side of the dot, will be displayed in full but 10.3 means different. 10 means the whole width to be displayed and inside that width has reserved 3 places for decimal.
YOU ARE READING
Java Programming
Randomhttps://docs.oracle.com/javase/tutorial/ This is the link where I learned my java lessons online. I choose java as first programming language. I am a career shifter. I just want to start something new. I choose to write it here in Wattpad so that I...