06.Java Basic Input and Output
06.Java Basic Input and Output
In this tutorial, you will learn simple ways to display output to users and take
input from users in Java.
Java Output
In Java, you can simply use
System.out.println(); or
System.out.print(); or
System.out.printf();
Here,
• System is a class
• out is a public static field: it accepts output data.
Don't worry if you don't understand it. We will discuss class , public ,
and static in later chapters.
Let's take an example to output a line.
class AssignmentOperator {
public static void main(String[] args) {
Output:
Output:
1. println
2. println
1. print 2. print
System.out.println(5);
System.out.println(number);
}
}
Run Code
5
-10.6
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.
Output:
I am awesome.
Number = -10.6
Here, we have used the + operator to concatenate (join) the two strings: "I am
Here, first the value of variable number is evaluated. Then, the value is
concatenated to the string: "Number = ".
Java Input
Java provides different ways to get input from the user. However, in this
tutorial, you will learn to get input from user using the object of Scanner class.
In order to use the object of Scanner , we need to
import java.util.Scanner package.
import java.util.Scanner;
To learn more about importing packages in Java, visit Java Import Packages.
Then, we need to create an object of the Scanner class. We can use the object to
take input from the user.
class Input {
public static void main(String[] args) {
Output:
Enter an integer: 23
You entered 23
Note: We have used the close() method to close the object. It is recommended
to close the scanner object once the input is taken.
class Input {
public static void main(String[] args) {
Output:
As mentioned, there are other several ways to get input from the user. To
learn more about Scanner , visit Java Scanner.