Java 17 Recipes
-10. Passing Arguments via Command-Line
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
- Bu sahifa navigatsiya:
- Listing 1-8.
1-10. Passing Arguments via Command-Line
Execution Problem You want to pass values into a Java application invoked via the java utility command line. Solution Run the application using the java utility, and specify the arguments that you want to pass into it after the application name. If you’re passing more than one argument, each should be separated by a space. For example, suppose you want to pass the arguments to the class created in Listing 1-8 . ChApteR 1 GettInG StARted wIth JAvA 17 36 Listing 1-8. Example of Accessing Command-Line Arguments public class PassingArguments { public static void main(String[] args){ if(args.length > 0){ System.out.println("Arguments that were passed to the program: "); for (String arg:args){ System.out.println(arg); } } else { System.out.println("No arguments passed to the program."); } } } First, make sure to compile the program so that you have a .class file to execute. You can do that via the javac utility at the command line or terminal. Therefore, open a command prompt or a terminal window for compiling and executing your Java class. Now issue a java command to execute the class and type some arguments on the command line following the class name. The following example passes two arguments. java PassingArguments Luciano Manelli You should see the following output. Luciano Manelli Spaces separate arguments. Enclose strings in double quotes when you want to pass an argument containing spaces or other special characters. The following is an example. C:\Users\lucky\OneDrive\Desktop>java PassingArguments "Luciano Manelli" The output now shows just one argument. Arguments that were passed to the program: Luciano Manelli The double quotes translate the "Luciano Manelli" string into a single argument. ChApteR 1 GettInG StARted wIth JAvA 17 |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling