C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Introduction to Java

Java Program - Print user’s name

import java.util.Scanner;

 

public class PrintUserName {

    public static void main(String[] args) {

        // Create Scanner object to read input from keyboard

        Scanner sc = new Scanner(System.in);

 

        // Asking user to enter name

        System.out.print("Enter your name: ");

 

        // Reading the name typed by user

        String name = sc.nextLine();

 

        // Printing the name

        System.out.println("Hello, " + name + "!");

 

        sc.close(); // Closing scanner

    }

}

Output

 
OUTPUT :
Enter your name: Anand Rao
Hello, Anand Rao!

Explanation (Step-by-Step)

  1. import java.util.Scanner;
    • Scanner is a built-in Java class used to take input from the user.
  2. Scanner sc = new Scanner(System.in);
    • Creates a Scanner object that reads input from the keyboard.
  3. System.out.print("Enter your name: ");
    • Displays a message asking for the user's name.
  4. String name = sc.nextLine();
    • Reads the full line of text entered by the user and stores it in the variable name.
  5. System.out.println("Hello, " + name + "!");
    • Prints a greeting along with the entered name.
  6. sc.close();
    • Closes the Scanner to prevent memory leaks.