In this program, you'll learn to print a String entered by the user in Java. The String is stored in a variable using System.in, and is displayed on the screen using System.out.
import java.util.Scanner; public class Test { public static void main(String[] args) { String str; Scanner p=new Scanner(System.in); System.out.print("Enter any string:"); str =p.nextLine(); System.out.println("Display enter String:" + str); } }
Output:
Enter any string:cricket Display enter String:cricket
In this program, an object of Scanner class, reader is created to take inputs from standard input, which is keyboard.
Then, Enter a number prompt is printed to give the user a visual cue as to what they should do next.
op.nextLine() then reads all entered Char from the keyboard unless it encounters a new line character \n (Enter).
If you enter any character which is not an String, the compiler will throw an InputMismatchException.
Finally, number is printed onto the standard output (System.out) - computer screen using the function println().