In this article we want to learn about Java Scanner Input and Output, so as we already know that Java is one of the best and popular programming language, and it offers different functionalities to build nice applications. in java we have the ability to handle input and output streams, Java Scanner is one of the tools used to handle user input, in this article we want to talk about this concept.
Java Scanner Input
Java Scanner is a class in the Java.util package and it provides different methods to read user input. Scanner class can take input from different sources, including standard input, files and strings. this is an example that demonstrates how to take user input from the console:
1 2 3 4 5 6 7 8 9 10 11 |
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter your name: "); String name = scanner.nextLine(); System.out.println("Hello " + name); scanner.close(); } } |
In the above code, first we have created Scanner object that takes input from the standard input. after that we have prompted the user to enter their name using System.out.print() method. after that we have read the input using nextLine() method of the Scanner class and we have store it in the name variable. and lastly we display a greeting message on the console using System.out.println() method.
Run the code and this will be the result
Java Output Stream
Java output stream is a class in the Java.io package, and it provides different methods for displaying data in the screen or write it to a file. this is an example that shows how to display data on the console using System.out.println() method:
1 2 3 4 5 |
public class Main { public static void main(String[] args) { System.out.println("Welcome to codeloop.org"); } } |
In the above code we have used System.out.println() method for displaying a text in the console. System.out is an instance of the PrintStream class that provides different methods to display data on the console or write it to a file.
Subscribe and Get Free Video Courses & Articles in your Email