Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 70

Passing Parameters to a Java Program

Оглавление

Let's see how to send data to our program's main() method. First, we modify the Zoo program to print out the first two arguments passed in:

public class Zoo { public static void main(String[] args) { System.out.println(args[0]); System.out.println(args[1]); } }

The code args[0] accesses the first element of the array. That's right: array indexes begin with 0 in Java. To run it, type this:

javac Zoo.java java Zoo Bronx Zoo

The output is what you might expect:

Bronx Zoo

The program correctly identifies the first two “words” as the arguments. Spaces are used to separate the arguments. If you want spaces inside an argument, you need to use quotes as in this example:

javac Zoo.java java Zoo "San Diego" Zoo

Now we have a space in the output:

San Diego Zoo

Finally, what happens if you don't pass in enough arguments?

javac Zoo.java java Zoo Zoo

Reading args[0] goes fine, and Zoo is printed out. Then Java panics. There's no second argument! What to do? Java prints out an exception telling you it has no idea what to do with this argument at position 1. (You learn about exceptions in Chapter 11, “Exceptions and Localization.”)

Zoo Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1 at Zoo.main(Zoo.java:4)

To review, the JDK contains a compiler. Java class files run on the JVM and therefore run on any machine with Java rather than just the machine or operating system they happened to have been compiled on.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Подняться наверх