Working with Scanner and String Manipulation in Java: Input Handling, Comparison, Extraction, and Conversion
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.