Search This Blog

Tuesday, May 19, 2015

Command line execution of a Java class built in Eclipse

 IDEs like Eclipse provides higher productivity. However, if your testing program involves command line arguments, you should check run configurations and change the command line argument through clicking mouse several times. Then, your intention would be running the compiled java class on command line.

When you have created a package and created classes within a package, your source directory structure will be like:

$ ls -R src
chapter1

src/chapter1:
Binary.java    Chapter1.java    Factors.java    Gambler.java

Maybe, your binary directory will be structured like:

$ ls -R bin
chapter1

bin/chapter1:
Binary.class    Chapter1.class    Factors.class    Gambler.class


When your Chapter1 class contains the entry point, main() method, for instance, your Chapter1.java will be like:

package chapter1;

public class Chapter1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Factors factors = new Factors();
        factors.run(args);
    }

}

and you have a separate file of Factors.java for Factors class:
package chapter1;

public class Factors {
    public void run(String[] args)
    {
        long N = Long.parseLong(args[0]);
        long n= N;
        for (long i = 2; i <= n/i; i++)
        {
            while (n % i == 0)
            {
                n /= i;
                System.out.print(i + " ");
            }
        }
        if (n > 1) System.out.print(n);
        System.out.println();
    }
}

On the command line, you can type
$ java -cp bin chapter1.Chapter1 287994837222311


It will produce:
17 1739347 9739789