Java User Input and Output
We can use Scanner class to take input from user. Scanner class is a part of util package.
Create a Scanner class object and use nextLine() function to take an input from user.
Example:
Below is the code snippet to take a user input:
OUTPUT:
Input type methods defined in Scanner class:
Java Output
The Java output statement helps us print the output/result on screen.
Java output statements:
System.out.print()
System.out.println()
System.out.printf()
System.out is the standard output stream used to produce the output of a program on computer screen.
print(), println() and printf() methods help us to print values or output on the screen.
print()
The print() method prints everything on the same line of the screen as shown in below output. After printing output cursor remains in same line.
In below example we used print() statement to print everything in same line.
println()
The println() method prints everything on the next line of the screen as shown in below output. After printing output cursor moves to the next line.
In below example we used println() method to print everything in next line.
print() and println() can perform mathematical calculations and string concatenation.
printf()
The printf() method help us to print formatted String to the console.
Below are the overloaded printf() methods:
System.out.printf(string);
System.out.printf(format, arguments);
Example:
There are three import thing we need to understand in below sample printf() example:
%n → This is getting used for moving cursor in next line.
%s → It will simply print the given output in small letters.
%S → It will simply print the given output in capital letters.
%s%n → It will simply print the given output in small letters and move the cursor to next line.
%S%n → It will simply print the given output in capital letters and move the cursor to next line.