In this blog, we will be discussing about how we take input from the user and how the output is displayed in java.
Java Input
There are different ways to take input from user in java. But in this blog, we will talk about taking input from user using the object of Scanner class.
In order to use the object of Scanner class, we need to import java.util.Scanner package.
Then we create an object of Scanner class. An object is an instance of a class in java. We can use the object to take input from the user:
Example: Get Integer Input From the User
Output
In the above example, we have created an object named input of the Scanner class. We then call the nextInt() method of the Scanner class to get an integer input from the user.
Similarly, we can use nextLong(), nextFloat(), nextDouble(), and next() methods to get long, float, double, and string input respectively from the user.
Note: We have used the close()
method to close the object. It is recommended to close the scanner object once the input is taken.
Example: Get float, double and String Input
Output
As mentioned, there are other several ways to get input from the user. To learn more about Scanner, visit Java Scanner.
Java Output
In java, for displaying output, you can simply use
to send the output to the standard output(screen) ===> Standard Output Stream Object
Here,
- System is a class.
- out is a public static field: it accepts output data.
Let's take an example to print a statement
Output
Here we have used println() method for displaying the string. To learn about println() method, visit Chapter 1 Question 2.1
Difference between println(), print() and printf()
- print() - It prints string inside the double quotes " ".
- println() - It prints string inside the quotes similar like print() method. Then the cursor moves to the beginning of the next line.
- printf() - It provides string formatting (used for formatting the display/output).
Example: print() and println()
Output
In the above example, we have shown the working of the print() and println() methods. To learn about the printf() method, visit Java printf().
Example: Printing Variables and Literals
Output
Here, you can see that we have not used the quotation marks. It is because to display integers, variables and so on, we don't use quotation marks.
Example: Print Concatenated Strings
Output
In the above example, notice the line,
Here, we have used the + operator to concatenate (join) the two strings: "I am " and "awesome.".
And also, the line,
Here, first the value of variable number is evaluated. Then, the value is concatenated to the string: "Number = ".
If you have any doubts or questions, please let me know.