Java Basic Input and Output
In this article, you will learn simple ways to display output, and take input from the user.
Java Output
You can simply use System.out.println(), System.out.print() or System.out.printf() to send output to standard output (screen).
System is a class and out is a public static field which accepts output data.
Let's take an example to output a line.
class AssignmentOperator {
public static void main(String[] args) {
System.out.println("Java programming is interesting.");
}
}
When you run the program, the output will be:
Java programming is interesting.
Example 2: print() and println()
class Output {
public static void main(String[] args) {
System.out.println("1. println ");
System.out.println("2. println ");
System.out.print("1. print ");
System.out.print("2. print");
}
}
When you run the program, the output will be:
1. println
2. println
1. print 2. print
Java Input
There are several ways to get input from the user in Java. You will learn to get input by using Scanner object in this article.
For that, you need to import Scanner class using:
import java.util.Scanner;
Learn more about Java import
Then, we will create an object of Scanner class which will be used to get input from the user.
Scanner input = new Scanner(System.in);
int number = input.nextInt();
Example 5: Get Integer Input From the User
import java.util.Scanner;
class Input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("You entered " + number);
}
}
When you run the program, the output will be:
Enter an integer: 23
You entered 23
Java Compiler For Android
Open playstore app
Search 'Aide' & Install app
Open Aide app & enter java code
0 Comments