- The Java Workshop
- David Cuartielles Andreas G?ransson Eric Foster Johnson
- 1344字
- 2021-06-11 13:05:20
Handling Command-Line Arguments
Command-line arguments are parameters passed to the main() method of your Java program. In each example so far, you've seen that the main() method takes in an array of String values. These are the command-line arguments to the program.
Command-line arguments prove their usefulness by giving you one way of providing inputs to your program. These inputs are part of the command line launching the program, when run from a Terminal shell window.
Exercise 15: Testing Command-Line Arguments
This exercise shows how to pass command-line arguments to a Java program, and also shows how to access those arguments from within your programs:
- Using the techniques from the previous exercises, create a new class named Exercise15.
- Enter the following code:
public class Exercise15 {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.println(i + " " + args[i]);
}
}
}
This code uses a for loop to iterate over all the command-line arguments, which the java command places into the String array named args.
Each iteration prints out the position (i) of the argument and the value (args[i]). Note that Java arrays start counting positions from 0 and args.length holds the number of values in the args array.
To run this program, we're going to take a different approach than before.
- In the bottom of the IntelliJ application, click on Terminal. This will show a command-line shell window.
When using IntelliJ for these examples, the code is stored in a folder named src.
- Enter the following command in the Terminal window:
cd src
This changes to the folder with the example source code.
- Enter the javac command to compile the Java program:
javac Exercise15.java
This command creates a file named Exercise15.class in the current directory. IntelliJ normally puts these .class files into a different folder.
- Now, run the program with the java command with the parameters you want to pass:
java Exercise15 cat dog wombat
In this command, Exercise15 is the name of the Java class with the main() method, Exercise15. The values following Exercise15 on the command line are passed to the Exercise15 application as command-line arguments. Each argument is separated by a space character, so we have three arguments: cat, dog, and wombat.
- You will see the following output:
0 cat
1 dog
2 wombat
The first argument, at position 0 in the args array, is cat. The argument at position 1 is dog, and the argument at position 2 is wombat.
Note
The java command, which runs compiled Java programs, supports a set of command-line arguments such as defining the available memory heap space. See the Oracle Java documentation at https://packt.live/2BwqwdJ for details on the command-line arguments that control the execution of your Java programs.
Converting Command-Line Arguments
Command-line arguments appear in your Java programs as String values. In many cases, though, you'll want to convert these String values into numbers.
If you are expecting an integer value, you can use Integer.parseInt() to convert a String to an int.
If you are expecting a double value, you can use Double.parseDouble() to convert a String to a double.
Exercise 16: Converting String to Integers and Doubles
This exercise extracts command-line arguments and turns them into numbers:
- Using the techniques from the previous exercises, create a new class named Exercise16.
- Enter the main() method:
public class Exercise16 {
public static void main(String[] args) {
}
}
- Enter the following code to convert the first argument into an int value:
if (args.length > 0) {
int intValue = Integer.parseInt(args[0]);
System.out.println(intValue);
}
This code first checks if there is a command-line argument, and then if so, converts the String value to an int.
- Enter the following code to convert the second argument into a double value:
if (args.length > 1) {
double doubleValue = Double.parseDouble(args[1]);
System.out.println(doubleValue);
}
This code checks if there is a second command-line argument (start counting with 0) and if so, converts the String to a double value.
- Enter the javac command introduced in Chapter 1, Getting Started, to compile the Java program:
javac Exercise16.java
This command creates a file named Exercise16.class in the current directory.
- Now, run the program with the java command:
java Exercise16 42 65.8
You will see the following output:
42
65.8
The values printed out have been converted from String values into numbers inside the program. This example does not try to catch errors, so you have to enter the inputs properly.
Note
Both Integer.parseInt() and Double.parseDouble() will throw NumberFormatException if the passed-in String does not hold a number. See Chapter 5, Exceptions, for more on exceptions.
Diving Deeper into Variables — Immutability
Immutable objects cannot have their values modified. In Java terms, once an immutable object is constructed, you cannot modify the object.
Immutability can provide a lot of advantages for the JVM, since it knows an immutable object cannot be modified. This can really help with garbage collection. When writing programs that use multiple threads, knowing an object cannot be modified by another thread can make your code safer.
In Java, String objects are immutable. While it may seem like you can assign a String to a different value, Java actually creates a new object when you try to change a String.
Comparing Final and Immutable
In addition to immutable objects, Java provides a final keyword. With final, you cannot change the object reference itself. You can change the data within a final object, but you cannot change which object is referenced.
Contrast final with immutable. An immutable object does not allow the data inside the object to change. A final object does not allow the object to point to another object.
Using Static Values
A static variable is common to all instances of a class. This differs from instance variables that apply to only one instance, or object, of a class. For example, each instance of the Integer class can hold a different int value. But, in the Integer class, MAX_VALUE and MIN_VALUE are static variables. These variables are defined once for all instances of integers, making them essentially global variables.
Note
Chapter 3, Object-Oriented Programming, delves into classes and objects.
Static variables are often used as constants. To keep them constant, you normally want to define them as final as well:
public static final String MULTIPLY = "multiply";
Note
By convention, the names of Java constants are all uppercase.
Example20.java defines a constant, MULTIPLY:
public class Example20 {
public static final String MULTIPLY = "multiply";
public static void main(String[] args) {
System.out.println("The operation is " + MULTIPLY);
}
}
Because the MULTIPLY constant is a final value, you will get a compilation error if your code attempts to change the value once set.
Using Local Variable Type Inference
Java is a statically typed language, which means each variable and each parameter has a defined type. As Java has provided the ability to create more complex types, especially related to collections, the Java syntax for variable types has gotten more and more complex. To help with this, Java version 10 introduced the concept of local variable type inference.
With this, you can declare a variable of the var type. So long as it is fully clear what type the variable really should be, the Java compiler will take care of the details for you. Here's an example:
var s = new String("Hello");
This example creates a new String for the s variable. Even though s is declared with the var keyword, s really is of the String type. That is, this code is equivalent to the following:
String s = new String("Hello");
With just a String type, this doesn't save you that much typing. When you get to more complex types, though, you will really appreciate the use of the var keyword.
Note
Chapter 4, Collections, Lists, and Java's Built-In APIs, covers collections, where you will see really complex types.
Example21.java shows local variable type inference in action:
public class Example21 {
public static void main(String[] args) {
var s = new String("Hello");
System.out.println("The value is " + s);
var i = Integer.valueOf("42");
System.out.println("The value is " + i);
}
}
When you run this example, you will see the following output:
The value is Hello
The value is 42
Activity 1: Taking Input and Comparing Ranges
You are tasked with writing a program that takes a patient's blood pressure as input and then determines if that blood pressure is within the ideal range.
Blood pressure has two components, the systolic blood pressure and the diastolic blood pressure.
According to https://packt.live/2oaVsgs, the ideal systolic number is more than 90 and less than 120. 90 and below is low blood pressure. Above 120 and below 140 is called pre-high blood pressure, and 140 and over is high blood pressure.
The ideal diastolic blood pressure is between 60 and 80. 60 and below is low. Above 80 and under 90 is pre-high blood pressure, and over 90 is high blood pressure.

Figure 2.4: Ideal ranges for systolic and diastolic blood pressures
For the purpose of this activity, if either number is out of the ideal range, report that as non-ideal blood pressure:
- Write an application that takes two numbers, the systolic blood pressure and the diastolic blood pressure. Convert both inputs into int values.
- Check if there is the right number of inputs at the beginning of the program. Print an error message if any inputs are missing. Exit the application in this case.
- Compare against the ideal rates mentioned previously. Output a message describing the inputs as low, ideal, pre-high, or high blood pressure.
To print an error message, use System.err.println instead of System.out.println.
- Try out your program with a variety of inputs to ensure it works properly.
You'll need to use the Terminal pane in IntelliJ to compile and run the program with command-line input. Look back at Exercises 15 and 16 for details on how to do this.
- The blood pressure is typically reported as systolic blood pressure/diastolic blood pressure.
Note
The solution for this activity can be found on page 533.
- Learning Scala Programming
- Django+Vue.js商城項目實戰(zhàn)
- Apache ZooKeeper Essentials
- Mastering Ember.js
- Mastering Articulate Storyline
- SAP BusinessObjects Dashboards 4.1 Cookbook
- Mastering ROS for Robotics Programming
- C++寶典
- Node.js開發(fā)指南
- 網(wǎng)絡(luò)數(shù)據(jù)采集技術(shù):Java網(wǎng)絡(luò)爬蟲實戰(zhàn)
- SwiftUI極簡開發(fā)
- Getting Started with the Lazarus IDE
- C# 7 and .NET Core 2.0 Blueprints
- Scratch超人漫游記:創(chuàng)意程序設(shè)計:STEAM創(chuàng)新教育指南
- Comprehensive Ruby Programming