Home‎ > ‎Applied Core Java‎ > ‎Introduction‎ > ‎

HelloName - pass command line argument and check

Problem : Write a program that takes a name from command line and say hello it? If no name is passed then display a user friendly Usage message.

Program :

Step 1 - Coding

Create a text file c:\sunilos\HelloName1.java  and copy below contents.


 * A program which take commond line argument and check error.
public class HelloName1 {

    public static void main(String[] args) {

                //Check length of an array.  If an argument will be passed then length will be one
        if (args.length == 1) {
            System.out.println("Hello " + args[0]);
        } else {
            System.out.println("Usage : java -cp c:/sunilos HelloName1");


Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy HelloName1.java  into 'c:\sunilos' folder.
  3. Open your command prompt and go to  'c:\sunilos'
  4. Compile HelloName1.java with help of 
    • javac HelloName1.java command.Command will create class file in the same folder.
  5. Congratulations!! your Java program is ready to serve.

Step 3 - Testing

  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your java program from command prompt with help of
    • java HelloName1 SunilOS
  3. Now again execute java program from command prompt without any argument
    • java HelloName1


With argument
Hello SunilOS

Without argument
Usage : java -cp c:/sunilos HelloName1

<<Previous | Next>>
nakul shukla,
Mar 19, 2009, 6:46 AM