Write a JAVA program to read a String value from user and display it? | StudyEcart | CODE001

import java.util.Scanner; public class ReadAndDisplayString { public static void main(String[] args) { // Create a Scanner object to read user input Scanner scanner = new Scanner(System.in); // Prompt the user to enter a string System.out.print("Enter a string: "); // Read the user's input as a string String userInput = scanner.nextLine(); // Display the entered string System.out.println("You entered: " + userInput); // Close the scanner to release resources scanner.close(); } } (code-box)


In this program:

1. We import the `Scanner` class from the `java.util` package to handle user input.

2. We create a `Scanner` object named `scanner` to read input from the standard input stream (usually the keyboard).

3. We use the `System.out.print` method to display a prompt asking the user to enter a string.

4. We use the `scanner.nextLine()` method to read the entire line of text entered by the user, including spaces.

5. We use the `System.out.println` method to display the entered string along with a message.


Remember to import the necessary packages and handle resources properly by closing the `Scanner` when you're done using it.



🚀 Elevate Your Career with Studyecart! 📚📊

🔥 Get instant job notifications and ace interviews with Studyecart. 📌

Download now

#StudyecartApp #CareerBoost

Post a Comment

0 Comments