Working with Java in the console (terminal)

I think this is very useful. I know there are powerful script languages like python or ruby which, by the way, I strongly recommend you to learn. But maybe you feel comfortable (like me) using Java for simple and not so simple programs or scripts. I'm writing this post because the other day I wanted to create a word list file to use in Backtrack with specific restrictions that I had in mind. It had been long time without using Ruby and I had to refresh my knowledge about it to make it. But then I thought that I could have made the word list faster just with a few lines of Java. But of course we don't want to use an IDE like Eclipse o NetBeans for this kind of programs, we just want our lovely console :).

Enough chatter let's go to practice. We're going to create a HelloWorld.java and run it all from the console.

First of all we need to install the Java Development Kit (JDK) in order to run the Java compiler (javac). We can use the one from Sun, but I'll be using openjdk which is installed in my Backtrack.

If you don't have it installed yet, just type:

apt-get install openjdk-6-jdk

or

apt-get install default-jdk

We are going to use the Java Compiler (javac) to create the binary file HelloWorld.class, the one that can be executed by the Java Virtual Machine (JVM).

Let's write the source code. Use your favorite editor, I'll use nano:

nano HelloWorld.java

And now the code:

/* Java Hello World from mendrugox */
 
public class HelloWorld
{
	public static void main(String[] args)
	{
		System.out.println("Hello World!");
	}
}

Save and close (Ctrl +x in nano).

Now we have our code in the HelloWorld.java file, let's compile it:

javac HelloWorld.java

The file HelloWorld.class is created and now we can execute our program:

java HelloWorld

*Notice that I put HelloWorld and not HelloWorld.class.

 

We're done.

Enjoy.

Posted on December 28, 2011 at 12:36 by Samuel · Permalink
In: Backtrack, Debian, Java, Languages, Linux · Tagged with: 

Please leave a reply :)

Time limit is exhausted. Please reload CAPTCHA.