OCA 2: Command Line and The main() Method

Most of us use some kind of fancy Integrated Development Environment (IDE) to write code. An IDE manages all of the unnecessary hard work so that we can focus only on the actual coding. Latest IDEs brag about having features like autocomplete, refactoring, source control, debuggers and lots of other useful stuff. But I think when we want to learn how a programming language actually works, we should get out of this comfort zone and get back to the old command line to compile and run our programs.

For Java, you need to have JDK installed and the PATH set. You can get info on how to install JDK on different platforms here. Once everything is set, you can check if JDK is installed properly by opening up the command prompt window (or terminal for Linux or Mac users) and run the command

java -version

If everything goes right, the command line will show the Java version installed. It’s the signal that you’re good to go.

So, we know that Java files have an extension .java. We use the command javac to compile the .java file and the command java to run it. Every class in Java, when compiled gets converted into what’s called a bytecode which has .class extension. Bytecode consists of instructions that the JVM (Java Virtual Machine) knows how to execute. So, let’s make that typically boring yet confidence boosting Hello World program and run it using the command line.

We open notepad and write

1
2
3
4
5
public class HelloWorld{
    public static void main(String[] args){
        System.out.println("Hello World!");
    }
}

Now we need to keep in mind that:

  • Each .java file can have one and only one public class
  • There can be no or many non-public classes. Each class will have a separate bytecode file (<classname>.class)
  • The .java filename should be the same as the name of the public class in the file.

So keeping the above things in mind, we save the file as HelloWorld.java and open command prompt in that directory where we saved the file. We compile the program using javac command. If there are no compile time exceptions or errors, a .class file would be created in the same directory with name HelloWorld.class (above code shouldn’t produce any errors but if it does, then try to figure out if JDK is installed properly and you are in the right directory). Then we can run the program by using java command with the class name containing the main() method.

javac HelloWorld.java
java HelloWorld

Our output should be

Hello World

Now that we know how to compile and run Java programs using the command line, let’s have a look at the main() method.

The main() method is the entry point to every Java program. Try running a program without a main() method and see what happens. Let’s have a look at the main() method’s signature. The method should be public (it is an access modifier), that means that the method is accessible anywhere. The method should be static (a non-access modifier), which means the method belongs to the class and not to the object. void is the return type of the method which says that the method doesn’t return any value. main is the name of the method which takes an array of String as a parameter. In practice, you can write String[] args, String args[] or String… args, the compiler accepts any of these (Yes, varargs syntax is allowed). The variable name args hints that this list contains values that were read in (arguments) when the JVM started. Technically, we can name the variable anything but we follow the convention and call it args. So the following are valid main() method signatures.

1
2
3
4
public static void main(String[] args)
public static void main(String args[])
public static void main(String... args)
public static void main(String[] whatever)

The method signatures different that the ones above are not technically illegal. They will just be considered overloaded methods (more on method overloading soon) and will compile just fine. But you’ll get an error when you try to run that main method not found.

You’ll be wondering- What’s the use of the parameter defined in the main() method signature? The args parameter is used to store the values given to the JVM while running the program from command line. What?!

So to simplify things, we say that while running the program from command line, we can give some values to the JVM which are stored in the args parameter. These values can then be used in our program. Again, what?! Let’s have a look at an example.

1
2
3
4
5
6
public class ArgTest{
    public static void main(String[] args){
        System.out.println(arg[0]);
        System.out.println(args[1]);
    }
}

We save this in ArgTest.java file and we compile it using the command

javac ArgTest.java

Now while running this file, we need to pass in some arguments. The way to do so is ‘java <ClassName> <arguments list>‘. Let’s have a look

java ArgTest hello world

We pass in two arguments to the main() method. These arguments are stored in the args array. The indexing for the array starts from zero so args[0] stores hello and args[1] stores world. Both of them are then printed out. If we pass more arguments, then the above program will run the same but if we pass in fewer arguments, then we will get ArrayIndexOutOfBoundsException which is a Runtime Exception.

One more thing to note is that if we want to pass in two or more words as a single argument, we can enclose it in double quotes. For example:

java ArgTest "hello world" java

The above command will treat hello world as a single argument and will be stored in args[0] and args[1] will store java.

All command line arguments are treated as String objects even if they represent another data type. To make it clear, let’s make another program to add up the args. The program will be as follows:

1
2
3
4
5
public class ArgTest2{
    public static void main(String[] args){
        System.out.println(args[0] + args[1]);
    }
}

Now when we run the program by passing two numbers as an argument:

java ArgTest2 1 2

We will get the output as 12 and not 3 because each argument is a String object and hence the + operator concatenates the two String objects.

This concludes our discussion on using the command line to run a Java program and the main() method. Feel free to ask questions.

Share this:
Share
«
»

6 comments on “OCA 2: Command Line and The main() Method”

  1. Jim says:

    Hi there, I enjoy reading through your article. It’s nice.

  2. zeng fanzhi says:

    If you want to improve your know-how just keep visiting this site and be updated with the newest news posted here.

  3. Doretha says:

    Hi there! Do you use Twitter? I’d like to follow you if that would be
    okay. I’m absolutely enjoying your blog and look forward
    to new posts. http://pagebin.com/zj1gkoKD

  4. TechnoTux says:

    hi, congratulations on the JavaCertified t-shirt
    what do you think is the best way to prepare for the OCA java8 exam ?
    i’m studying to take the exam but i’m not very confident yet
    right now i finished the book by sybex Jeanne Boyarsky & Scott Selikoff
    i’m also taking quiz where ever i can find them (the java magazine usually have some)

    1. Steve Mann says:

      Hi TechnoTux! Thanks.
      For OCA 8, the Sybex book is good enough. Go through it thoroughly a couple of times, make notes, challenge yourself.
      For confidence gaining, you need to know how well you’re prepared. I bought Enthuware test series and gave a few tests first. I scored low, like 60-65% so I knew I needed more efforts. I went through the Sybex book again and then gave tests and was around 85% this time. I’d definitely recommend Enthuware if you’re preparing for OCA 8(I’m not getting paid to say this ;-)…)

      Next, Coderanch was really helpful. Its a forum where you get to ask doubts and all. It really helps you to understand the topics.

      And yes, you can always mail me if you’re in trouble preparing for OCA…
      Good Luck!
      Cheers!

Leave a Reply