Getting User Input and Introduction to the String class

Learn Java user input with Scanner and basics of the String class. Day 4 Java tutorial for beginners with examples and explanations.
Getting User Input, Introduction to the String class

On Day 4 of the Java course, we learn how to take input from users and work with the String class. Getting user input makes programs interactive, while Strings allow us to handle text. Both are essential for almost every real-world application.

1. Getting User Input with Scanner

Java provides the Scanner class (from java.util package) to read user input from the console. It can read numbers, words, or whole lines.


import java.util.Scanner;

public class UserInputExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Taking integer input
        System.out.print("Enter your age: ");
        int age = scanner.nextInt();

        // Taking string input
        scanner.nextLine(); // consume newline
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

        System.out.println("Hello " + name + ", you are " + age + " years old!");
    }
}

How it works: The Scanner object reads input typed by the user. nextInt() reads integers, nextLine() reads text. After reading numbers, we use scanner.nextLine() once to clear the input buffer before reading strings.

2. Introduction to the String Class

The String class in Java is used to store and manipulate text. Strings are objects, not primitive types, and come with many built-in methods.

Common String Methods

  • length() → returns number of characters
  • toUpperCase() → converts text to uppercase
  • toLowerCase() → converts text to lowercase
  • charAt(index) → gets character at given index
  • concat() → joins two strings

public class StringExample {
    public static void main(String[] args) {
        String greeting = "Java Programming";

        System.out.println("Length: " + greeting.length());
        System.out.println("Uppercase: " + greeting.toUpperCase());
        System.out.println("Lowercase: " + greeting.toLowerCase());
        System.out.println("First character: " + greeting.charAt(0));
        System.out.println("Concatenation: " + greeting.concat(" is fun!"));
    }
}

How it works: Strings are immutable, meaning once created, they cannot be changed. Methods like toUpperCase() create a new String without altering the original.

Summary

Today you learned how to make programs interactive using Scanner for user input and explored the basics of the String class. Mastering Strings is crucial because most applications handle text data, such as names, messages, or user input.

إرسال تعليق