0% found this document useful (0 votes)
21 views10 pages

Z 12

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
21 views10 pages

Z 12

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 10
0412023 20.11 Command-Line Arguments in Java | Baeloung “ Command-Line Arguments in Java Last updated: June 23.2022 |. written by atta Fojér htips/ wanwbaeldung.com/author/atla-folr) Y thitos//adsfreestarcom/? Java (https://wwwbaeldung.com/category/java) + Get started with Spring 5 and Spring Boot 2, through the Learn Spring course: > CHECK OUT THE COURSE (/s-course-start) mrepietty | room woman = Register today: Harness the Power of Your Identity Data Mp ronste (nttps//ads freestarcom/? utm_campaign-branding&ulm_medium-banner&utm_source-baeldung.comutm_content-baeldung_incontent 2 y 1. Introduction Its quite common to run applications from the command-line using arguments. Especially on the server- side. Usually, we don't want the application to do the same thing on every run: we want to configure its behavior some way. In this shor tutorial, wel explore how can we handle command-line arguments in Java - hitps:lvww-baeldung.comjava-command:ine-arguments ano oart2029 20.11 Command-Line Azgumenis in Java | Baelsung 2. Accessing Command-Line Arguments in Java ‘Since the main method is the entry point of a Java application, the JVM passes the command-line arguments through its arguments. The traditional way is to use a String array: I} handle arguments 0 ; However, Java § introduced varargs, which are arrays in sheep's clothing, Therefore, we can define our main with a String vararg: (https//ads freestarcom/? public static votd main(String... ares) < 71 mance sraumerts Oo ) Theyre identical, therefore choosing between them is entirely up to personal taste and preference. ‘The method parameter of the main method contains the command-line arguments in the same order we passed at execution, If we want lo access how much arguments did we gel, we only have to check the length of the array. For example. we can print the number of arguments and their value on the standard output: ‘System.out.printla("Argument count: " + args. length); O > Note that in some languages, the first argument willbe the name of the application. On the other hand, in Java, this array contains only the arguments. 3. How to Pass Command-Line Arguments Now that we have an application that handles command-line arguments, were eager to try it Lets see what ‘options we have, ldung.comjava-commanet-jine-arguments 20 oart2023 20:11 Command-Line Arguments in Java | Baeloung “ 3.1. Command Line ‘The most obvious way is the command-line, Let's assume we already compiled the class com baeldung.commandlinearguments CliExample with our main method in it ‘Then we can run itwith the following command: It produces the following output: Now. we can pass arguments after the class name: ‘And the output is: Argument count: 2 Argument 0: Hello Argument 1: Wortd! Usually, we publish our application as ajar file, not as a bunch of class files. Let's say, we packaged it in cli-examplejar, and we set com baeldung commandlinearguments CliExample as the main class. Now we can run it without arguments the following way. the java “jar cli-exanple-jar Or with arguments: ¥ htipsifwnew.baeldung,com/ava-commandsiine-arguments ano oart2023 20.11 Command-Line Arguments in Java | Baeleung jeva Jar ont wile cur Heltd)Worldt oO Argument count: 2 Argument 02 Hello Argument 1: Kortd! Note, that Java will treat every argument we pass after the class name or the jar file name as the arguments of our application. Therefore. everything we pass bofore thal are arguments for the JVM itself 3.2. Eclipse While we're working on our application, welll want to check iit works the way we want. In Eclipse, we can run applications with the help of run configurations, For example, a run configuration defines which JVM to use, what is the entry point, the classpath, and so on. And of course, we can specify command-line arguments. ‘The easiest way to create an appropriate run configuration is to right-click on our main method, then choose Run As > Java Application from the context menu ns ec x oh OO ROH OS eRe Oia HP Hw BM b+ Feo er oe Sari | oop 7 | oseain =i i: oe ccrereeentine yee B Of ree et tiem tw ne a Syienavto cos a % Open Declaration a tel » Open ype Hlerwchy # = Gmesieny cho cone one onus . tame eter pee, 5 (/wp-content/uploads/2019/09/eclipse-run png) ‘With this, we instantly run our application with settings that honor our project settings. htipsifwnew.baeldung,com/ava-commandsiine-arguments ano 0412023 20.11 Command-Line Arguments in Java | Baeloung “ (https//ads freestarcom/? To provide arguments, we should then edit that run configuration. We can do it through the Run > Run Configurations. menu option. Here, we should click the Arguments tab ane fil the Program arguments textbox @ tun Contato o x un lee appicston ‘reste, manage, and run configurations Cr) SB 1S [frame |citsmpe peer (© Waa |o-Argunentt ph RE Ganpatl|y Saure] I Eionnen| El Gemnen) BPemhpe] BB. Apacte Tomcat a © ipeesoataton ranma FF ceneriesener Bene Senerstral Launch ff Gallon BL EE review (vee. deve Api [Fe appicnion Yitorguments (2 chtzample yun FF Nine Pagan Te Bp Lamen raup a Maven Bud @ Notes dppleatin & O5GiFamevere Working decor @ Seng foot 9p Detaie 8 sping toot Denoo cient || © ibe. obeebeeeneel omer Waspces | [ Beaten | [i ne al a ® eo (/wwp-content/uploads/2019/09/eclipse-configure.png) Hitting Run will run the application and pass the arguments we just entered. 3.3. Intellid IntelliJ uses a similar process to run applications. It calls these options simply as configurations, First, we need to right-click on the main method, then choose Run ‘CliExamplemain0 htipsifwnew.baeldung,com/ava-commandsiine-arguments 50 oart2023 20:11 Command-Line Arguments in Java | Baeloung B -sejatine eet pedi elepgsparns-acminiconibneingonmaainerginewACianpejeainaal=— OX Ble fi Vow signe Code Anas Beate BUD fun Too’ VCS Whfow Hep CiBanpejoe ———— ” 2 pecags cn dng cman 4 > pbc ane Citi ( i Spe bo plies ji, a ‘ Meant prin) mas > 4 for tine 8 coprtdeence antic Psion ot St ae : ; kent cotiney ' ‘Column Selection Mode Alt Shiteinsert Bene A jake recompile sinieje cost Denis Cteanpe msl) 1G fun caxamptemany wencoueaye 1B eit ciple msin. Show leer 1 opera Temi Lec stony > > compara cipoas Citamele > mend ieuceed Biiemmi = 61000 0 cnet Centos a 508 GF UT. Fai (/wwp-content/uploads/2019/09/intellj-runpng) This will run our program, but it will also add it to the Run list for further configuration, So, then to configure arguments, we should choose Run > Edi Configurations. and edit the Program arguments textbox Bintan x errr = Coe Conon 2s a Pewee [nde (mining sneer 5 I a ee cement nati (RTE z con ager Pe ® Peas a zi ans aa Ca=ape gaa ° (a es (/wp-content/uploads/2019/09/intelli-configure-1024x646.png) After that. we should hit OK and rerun our application for example with the run button inthe toolkar htipsifwnew.baeldung,com/ava-commandsiine-arguments eno oart2023 20:11 3.4. NetBrens “ Command-Line Arguments in Java | Baeloung NotBeans also falls into line with its running and configuration processes. \We should run our application first by right-clicking on the main method and choosing Run File: © cocina iach eo =p s AGES 6 poe VOTH )-i-O: HiacG 2 [emote * - — va alr @5 8 Were Feviaaioaina # Bp mone om sens comatersnaens: 7 fp] 3) mets cies canes « Se public static vosd madmeancinat arma ¢ als Sertenrotrpeiord Reve : aj: mcs oe ee || | Cattewely pe rate cms lo oy mom rn Tipjelnebatot Gi eee Pa 5 Bone ae = oa ine htipsifwnew.baeldung,com/ava-commandsiine-arguments (wp-content/uploads/2019/09/netbeans-run png) Like before. this creates a run configuration and runs the program. Next, we have to configure the arguments in that run configuration, We can do that by choosing Run > Set Project Configuration > Customize. Then we should Run on the left anc fil the Arguments text field m0 oart2028 20.11 Command-Line Arguments in Java | Baeloung Crenthoe = seni yy x gies Ge cote saasowiaie. ° cmoe Matrathee = a Hos -— es sto ae wap ea (ep ome) Vwp-content/uploads/2019/09/netbeans-configurepng) ‘After that. we should hit OK and start the application, 4. Third-Party Libraries Manual handling of the command-line arguments i straightforward in simple scenarios. However, as ‘our requirements become more and more complex, so does our code. Therefore. if we want to create an application with multiple command-line options, it would be easier to use a third-party library. Fortunately, therere a plethora of those libraries which support most use cases, Two popular examples are Picoeli /java-picocli-create-command-line-program) and Spring Shell (/spring-shell-cli. 5. Conclusion It's always a good idea to make your application's behavior configurable. In this article, we saw how to do that using command-line arguments. Additionally, we covered various ways to pass those arguments, ‘As usual, the examples are available over on GitHub (httos///github.com/eugenp/tutorials/tree/master/core-java-modules/core-java-lang-2). hitps:lvww-baeldung.comjava-command:ine-arguments ano oart2023 20:11 Command-Line Arguments in Java | Baeldung ” Get started with Spring 5 and Spring Boot 2, through the Learn Spring course; >> CHECK OUT THE COURSE (/s-course-end) Learning to build your API with Spring? Download the E-book (/rest-api-spring-guide) 2. COMMENT HO Oloest View Comments ‘Comments are closed on this article! htipsifwnew.baeldung,com/ava-commandsiine-arguments ano 0412023 20.11 Command-Line Arguments in Java | Baeloung ‘COURSES, [ALL COURSES (aL. COURSES) ALL BULK TEAM COURSES (/ALL-SULK-TEAVACOURSES) SERIES JACKSON JSON TUTORIAL JACKSON ‘SPRING SERSIGTENCE TUTORIAL /PERSISTENCE-WITH-SPRINGHSERIES) ‘ABOUT (OUR PaRINERS {ZPARTNERS) COMPANY INFO {/8AELOUNG-COMPANY=INFO} ipsa baeldung,comijava-commanci son0

You might also like