The java.util.Scanner class facilitates text parsing from various input sources, most commonly the standard input stream (System.in) for console interactions. To capture terminal data, instantiate the scanner passing System.in to its constructor. Once initialized, utility methods like nextInt(), nextDouble(), or nextLine() parse the subsequent token based on the expected type.
import java.util.Scanner;
public class ConsoleInputHandler {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter an integer: ");
int capturedValue = reader.nextInt();
System.out.println("You provided: " + capturedValue);
}
}
Processing multiple inputs typically involves sequential calls or loop constructs. Below demonstrates capturing two numeric values and computing their aggregate, followed by determining the highest value among three inputs using nested conditional evaluation.
import java.util.Scanner;
public class NumericProcessor {
public static void main(String[] args) {
Scanner inputDevice = new Scanner(System.in);
// Calculate sum of two inputs
System.out.print("Input first number: ");
int operandA = inputDevice.nextInt();
System.out.print("Input second number: ");
int operandB = inputDevice.nextInt();
int total = operandA + operandB;
System.out.println("Resulting sum: " + total);
// Find maximum of three inputs
System.out.print("Input third number: ");
int valOne = inputDevice.nextInt();
System.out.print("Input fourth number: ");
int valTwo = inputDevice.nextInt();
System.out.print("Input fifth number: ");
int valThree = inputDevice.nextInt();
int peak = (valOne > valTwo) ?
((valOne > valThree) ? valOne : valThree) :
((valTwo > valThree) ? valTwo : valThree);
System.out.println("Highest value found: " + peak);
}
}
Instantiating Scanner explicitly assigns a reference variable to the object. Omitting the reference variable creates an anonymous instance. While valid for single-use method invocations like new Scanner(System.in).nextInt(), this pattern should be avoided for repeated operations, as each invocation establishes a distinct stream connection, leading to resource inefficiency.
Generating unpredictable sequences relies on java.util.Random. This component produces pseudo-random integers within specified boundaries. Initialize the generator once to maintain state consistency across calls. The nextInt(int bound) method yields values ranging from zero (inclusive) up to the provided bound (exclusive).
import java.util.Random;
public class SequenceGenerator {
public static void main(String[] args) {
Random rng = new Random();
int limit = 5;
int count = 3;
System.out.println("Generating " + count + " values under " + limit + ":");
for (int i = 0; i < count; i++) {
int seed = rng.nextInt(limit);
System.out.println("Generated: " + seed);
}
}
}
To adjust the lower bound away from zero, apply arithmetic offset. For inclusive upper limits like n, calculate rng.nextInt(n) + 1. Interactive applications often pair random generation with user feedback loops. The following snippet implements a target-matching routine where the system selects a hidden figure between one and one hundred, guiding the user toward the correct guess through comparative hints until termination conditions are met.
import java.util.Random;
import java.util.Scanner;
public class NumberGuessingGame {
public static void main(String[] args) {
Random chance = new Random();
Scanner prompter = new Scanner(System.in);
int hiddenTarget = chance.nextInt(100) + 1;
boolean sessionActive = true;
while (sessionActive) {
System.out.print("Predict a number (1-100): ");
int playerGuess = prompter.nextInt();
if (playerGuess == hiddenTarget) {
System.out.println("Success! The target was indeed " + hiddenTarget);
sessionActive = false;
} else if (playerGuess > hiddenTarget) {
System.out.println("Too high. Try again.");
} else {
System.out.println("Too low. Try again.");
}
}
prompter.close();
}
}
When managing collections of objects, traditional arrays enforce immutable length constraints post-declaration. Resizing requires allocating new memory blocks and copying references, which becomes cumbersome for evolving datasets. java.util.ArrayList<E> addresses this limitation by implementing a dynamically expanding backing array. The generic parameter <E> defines the acceptable reference type for stored elements.
Construction follows standard factory patterns. Pre-JDK 7 required explicit type repetition on both sides (new ArrayList<String>()), but modern syntax permits diamond operators <> for inference (new ArrayList<>()). Elements are appended sequentially via add(E item). Iteration relies on index tracking bounded by the size() metric, preventing boundary exceptions. Core mutation operations include get(index) for retrieval, remove(index) for deletion, and size() for capacity checks.
import java.util.ArrayList;
import java.util.List;
public class CollectionBasics {
public static void main(String[] args) {
List<String> inventory = new ArrayList<>();
inventory.add("Alpha");
inventory.add("Beta");
inventory.add("Gamma");
System.out.println("Initial batch size: " + inventory.size());
for (int idx = 0; idx < inventory.size(); idx++) {
System.out.println("Item at " + idx + ": " + inventory.get(idx));
}
String discarded = inventory.remove(0);
System.out.println("Pulled from front: " + discarded);
}
}
Because Java generics do not accept primitive types (e.g., ArrayList<int> is invalid), automatic boxing/unboxing bridges the gap. Wrapper classes like Integer, Double, and Boolean map directly to their primitive counterparts. Storing numeric primitives simply requires referencing the uppercase variant.
import java.util.ArrayList;
public class PrimitiveStorage {
public static void main(String[] args) {
ArrayList<Integer> numericBuffer = new ArrayList<>();
numericBuffer.add(10);
numericBuffer.add(20);
numericBuffer.add(30);
numericBuffer.add(40);
System.out.println("Buffer contents: " + numericBuffer);
}
}
Advanced collection workflows frequently involve filtering, transformation, and formatted serialization. The next examples demonstrate aggregating randomized outcomes, encapsulating custom domain objects, applying delimiter-based string rendering, and isolating subsets based on mathematical criteria.
import java.util.ArrayList;
import java.util.Random;
public class AggregationExample {
public static void main(String[] args) {
Random lottery = new Random();
ArrayList<Integer> draws = new ArrayList<>();
for (int i = 0; i < 6; i++) {
draws.add(lottery.nextInt(33) + 1);
}
for (Integer val : draws) {
System.out.println(val);
}
}
}
Domain modeling often requires storing composite entities rather than primitives. Assigning instance references to a strongly-typed list ensures compile-time safety during iteration and property access.
import java.util.ArrayList;
record Person(String name, int years) {}
public class ObjectCollectionExample {
public static void main(String[] args) {
ArrayList<Person> roster = new ArrayList<>();
roster.add(new Person("Alice", 28));
roster.add(new Person("Bob", 34));
roster.add(new Person("Charlie", 22));
for (Person member : roster) {
System.out.println(member.name() + " / Age: " + member.years());
}
}
}
Custom serialization logic can be isolated into reusable utility methods accepting collection parameters. Implementing structured output like bracketed sets with specific separators requires careful boundary handling to avoid trailing delimiters.
import java.util.ArrayList;
public class FormatterUtility {
public static void main(String[] args) {
ArrayList<String> group = new ArrayList<>();
group.add("UnitA");
group.add("UnitB");
group.add("UnitC");
renderCustomSet(group);
}
public static void renderCustomSet(ArrayList<String> source) {
StringBuilder output = new StringBuilder("{");
int total = source.size();
for (int i = 0; i < total; i++) {
output.append(source.get(i));
if (i < total - 1) {
output.append("@");
}
}
output.append("}");
System.out.println(output.toString());
}
}
Data purification routines frequently extract subsets satisfying specific predicates. Filtering even integers from a mixed pool into a separate container illustrates return-value collection patterns.
import java.util.ArrayList;
import java.util.Random;
public class FilterRoutine {
public static void main(String[] args) {
Random mixer = new Random();
ArrayList<Integer> rawPool = new ArrayList<>();
for (int i = 0; i < 20; i++) {
rawPool.add(mixer.nextInt(1000) + 1);
}
ArrayList<Integer> evensOnly = isolateEvenValues(rawPool);
System.out.println("Filtered results: " + evensOnly);
}
public static ArrayList<Integer> isolateEvenValues(ArrayList<Integer> dataset) {
ArrayList<Integer> filteredBag = new ArrayList<>();
for (int i = 0; i < dataset.size(); i++) {
Integer candidate = dataset.get(i);
if (candidate % 2 == 0) {
filteredBag.add(candidate);
}
}
return filteredBag;
}
}