Scanner Class
Exploring the String
Class, Using Command-Line Arguments
1. Write a Java program to find the area of a rectangle using command-line arguments.
The length and width are provided as command-line arguments when the program is run. The String
arguments from the command line are converted to integers to perform the calculation to find area of a rectangle.
public class RectangleArea {
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Provide two numbers.");
return;
}
try {
// Command-line arguments are always strings.
// We must parse them into a numeric type.
int length = Integer.parseInt(args[0]);
int width = Integer.parseInt(args[1]);
int area = length * width;
System.out.println("Calculating the area of a rectangle...");
System.out.println("Length: " + length);
System.out.println("Width: " + width);
System.out.println("Area: " + area);
} catch (NumberFormatException e) {
// if the arguments are not valid integers.
System.out.println("Invalid input. Please make sure both length and width are valid integers.");
}
}
}
Varargs, Scanner
Class
1. What are variable-length arguments (varargs) in Java? What are their advantages?
Variable-length arguments (varargs) allow a method to accept zero or more arguments of a specified type. It's a feature that provides a simpler way to handle methods that need a variable number of inputs.
In the method signature, varargs are denoted by three dots (...
) after the data type. Inside the method, the vararg parameter is treated as an array of the specified type.
public void printNumbers(int... numbers)
can be called with printNumbers()
, printNumbers(1)
, printNumbers(1, 2, 3)
, and so on.
The main advantages of using varargs are:
Simplicity and Readability: They provide a cleaner and more convenient alternative to manually creating and passing an array when the number of arguments is unknown at compile time.
Flexibility: They allow a single method to handle different numbers of arguments, reducing the need for method overloading. For instance, instead of creating
sum(int a, int b)
andsum(int a, int b, int c)
, you can just create onesum(int... nums)
.
2. Illustrate the use of varargs.
Calculating the sum of an arbitrary number of integers. The sumAll
method uses varargs to accept any number of int
values.
public class VarargsDemo {
public static int sumAll(int... numbers) {
System.out.println("Number of arguments received: "
+ numbers.length);
int total = 0;
// Inside the method, 'numbers' is treated as an array.
for (int num : numbers) {
total += num;
}
return total;
}
public static void main(String[] args) {
int sum1 = sumAll(1, 2);
System.out.println("Sum 1: " + sum1 + "\n");
// Output: 3
int sum2 = sumAll(10, 20, 30, 40, 50);
System.out.println("Sum 2: " + sum2 + "\n");
// Output: 150
int sum3 = sumAll();
// Calling with no arguments is also valid.
System.out.println("Sum 3: " + sum3 + "\n");
// Output: 0
}
}
3. Discuss the usage of the Scanner
class in Java for input operations.
The java.util.Scanner
class is one of the most common and straightforward ways to get input from a user in Java. It can parse primitive types and strings from various input sources, most notably the standard input stream (System.in
), which typically corresponds to the keyboard.
Key Features and Usage:
Creating a Scanner: First create an instance of the Scanner class, telling it what source to read from. For keyboard input, you use System.in.
Scanner scanner = new Scanner(System.in);
Reading Different Data Types: The
Scanner
class provides several methods to read different types of data. The scanner waits for the user to type something and press Enter.nextInt()
: Reads an integer value.nextDouble()
: Reads a double value.nextBoolean()
: Reads a boolean value.nextLine()
: Reads a full line of text (including spaces) until the user hits Enter.next()
: Reads the next "token" or word, stopping at the first whitespace.
Handling
nextLine()
afternextTYPE()
: A common issue arises whennextLine()
is called after anothernext...()
method (likenextInt()
). ThenextInt()
method reads the number but leaves the newline character (\n
) in the input buffer. The subsequentnextLine()
call reads this leftover newline and returns an empty string. To fix this, you must add an extrascanner.nextLine();
call to consume the leftover newline.Closing the Scanner: It's good practice to close the scanner object using
scanner.close()
when done with it to release the underlying resources. This is especially important when reading from files.
import java.util.Scanner;
public class ScannerUsageDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.print("Enter your average grade: ");
double grade = scanner.nextDouble();
System.out.println("\n--- User Profile ---");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Grade: " + grade);
scanner.close();
}
}
String Manipulation Program
text.length()
text.toUpperCase()
text.toLowerCase()
text.isEmpty()
text.charAt(0)
text.startsWith("")
text.indexOf("")
text.replace('', '')
text.substring(4)
text.trim()
import java.util.Scanner;
public class SimpleStringExplorer {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Usage: java SimpleStringExplorer <some-text>");
return;
}
String initialText = args[0];
System.out.println("Argument received: \""
+ initialText + "\"");
System.out.println("\n## String Manipulation ##");
manipulateString(initialText);
System.out.println("\n## Varargs Demonstration ##");
String sentence = joinStrings(" ", "Varargs", "is", "simple.");
System.out.println("Joined sentence: " + sentence);
System.out.println("\n## Scanner Demonstration ##");
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
scanner.close();
}
public static void manipulateString(String text) {
System.out.println("Length: " + text.length());
System.out.println("Uppercase: " + text.toUpperCase());
System.out.println("Lowercase: " + text.toLowerCase());
// Get the character at a specific index
if (!text.isEmpty()) {
System.out.println("Character at index 0: "
+ text.charAt(0));
}
// Check if the string starts with a certain prefix
System.out.println("Starts with 'Hello': "
+ text.startsWith("Hello"));
// Find the index of a character or substring
System.out.println("Index of 'J': "
+ text.indexOf('J'));
// Replace all occurrences of a character
System.out.println("Replacing 'a' with '@': "
+ text.replace('a', '@'));
// Get a portion of the string
if (text.length() > 5) {
System.out.println("Substring from index 5: "
+ text.substring(5));
}
// Demonstrate trimming whitespace from the beginning and end
String paddedText = " some spaces ";
System.out.println("Trimming '"
+ paddedText + "': '" + paddedText.trim() + "'");
}
public static String joinStrings(String separator, String... words) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.length; i++) {
sb.append(words[i]);
// Add the separator unless it's the last word
if (i < words.length - 1) {
sb.append(separator);
}
}
return sb.toString();
}
}
Argument received: "HelloJava"
## String Manipulation ##
Length: 9
Uppercase: HELLOJAVA
Lowercase: hellojava
Character at index 0: H
Starts with 'Hello': true
Index of 'J': 5
Replacing 'a' with '@': HelloJ@v@
Substring from index 5: Java
Trimming ' some spaces ': 'some spaces'
## Varargs Demonstration ##
Joined sentence: Varargs is simple.
## Scanner Demonstration ##
Please enter your name: Alex
Hello, Alex!