Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Working with Scanner and String Manipulation in Java: Input Handling, Comparison, Extraction, and Conversion

Tech 1

Using the Scanner Class for User Input

The Scanner class from the java.util package enables reading input from standard input (typically the keyboard). To use it, import the clas and instantiate a object with System.in as the source.

import java.util.Scanner;

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

        System.out.print("Enter an integer: ");
        if (input.hasNextInt()) {
            int value = input.nextInt();
            System.out.println("Received: " + value);
        }

        System.out.print("Enter a full line of text: ");
        String line = input.nextLine();
        System.out.println("Line: " + line);

        System.out.print("Enter a word: ");
        String word = input.next();
        System.out.println("Word: " + word);

        input.close();
    }
}

nextInt() is commonly used to read integers, while nextLine() captures entire lines of text. The hasNextInt() method helps prevent input mismatch errors by validating data type before reading.

String Comparison Methods

String objects support several methods for comparison and validation:

public class StringComparison {
    public static void main(String[] args) {
        String first = "hello";
        String second = "HELLO";

        boolean isEqual = first.equals(second); // false (case-sensitive)
        boolean isEqualIgnoreCase = first.equalsIgnoreCase(second); // true
        boolean startsWithH = first.startsWith("h"); // true
        boolean isEmpty = first.isEmpty(); // false

        System.out.println("equals: " + isEqual);
        System.out.println("equalsIgnoreCase: " + isEqualIgnoreCase);
        System.out.println("startsWith h: " + startsWithH);
        System.out.println("is empty: " + isEmpty);
    }
}

Thece methods are essential for validating user input or comparing strings in conditional logic.

Extracting Information from Strings

String provides multiple ways to extract parts of its content based on index positions:

public class StringExtraction {
    public static void main(String[] args) {
        String text = "Hello java";

        int length = text.length();
        System.out.println("Length: " + length);

        int firstAIndex = text.indexOf('a');
        System.out.println("First 'a' at index: " + firstAIndex);

        int lastLIndex = text.lastIndexOf('l');
        System.out.println("Last 'l' at index: " + lastLIndex);

        String sub1 = text.substring(3);
        System.out.println("From index 3 onward: " + sub1);

        String sub2 = text.substring(6, 10);
        System.out.println("From index 6 to 9: " + sub2);
    }
}

Methods like length(), indexOf(), lastIndexOf(), and substring() allow precise control over string slicing and analysis.

Converting and Transforming Strings

Strings can be converted into other types and modified using built-in utilities:

public class StringTransformation {
    public static void main(String[] args) {
        String source = "abc";

        byte[] bytes = source.getBytes();
        for (byte b : bytes) {
            System.out.println(b);
        }

        char[] chars = source.toCharArray();
        for (char c : chars) {
            System.out.println(c);
        }

        String numberStr = String.valueOf(456);
        System.out.println(numberStr + 789);

        String replaced = "abc abc abc".replace("b", "d");
        System.out.println("Replaced: " + replaced);

        String[] splitParts = "apple banana cherry".split(" ");
        for (String part : splitParts) {
            System.out.println(part);
        }

        String trimmed = "  test  ".trim();
        System.out.println("Original: |" + "  test  " + "|\nTrimmed: |" + trimmed + "|");
    }
}

This demonstrates conversion between string and primitive types, character replacement, splitting strings by delimiters, and removing leading/trailing whitespace.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.