PDA

View Full Version : FAQ: Compiling and Running Java Programs



LaRoza
March 3rd, 2008, 05:19 AM
Working on the rest, post suggestions as well. I am not skilled or experienced in Java

So you're willing to write your own Java programs, or simply compile someone else's code? This guide will get you started...

This FAQ assumes you're trying to compile error-free code. To actually learn the Java languages, see the How to start programming (http://ubuntuforums.org/showthread.php?t=333867) thread.

0.a. Make sure the third party repositories are enabled

The easiest way to do this is open Applications->Add/Remove and select "All Available Applications".

0.b. Make sure the sun-java6-jdk package is installed

This package installs the essential tools needed to write and run Java programs.


sudo aptitude install sun-java6-jdk

Also run this to set the Sun Java as the default.


sudo update-java-alternatives --set java-6-sun


1. Compiling your first Java program

Copy & paste this code into a new file. Save the file as Main.java


//First Java Program
class Main
{
public static void main (String[] args)
{
System.out.println ("Hello, world.");
}
}

Open a terminal, go to the directory where you saved Main.java, and type:

javac Main.javaIf all went fine, nothing is printed and you get back to the shell. Now, run it:

java Main"Hello World!" gets printed in the terminal.

Explanations: javac is the Java compiler
obviously, Main means that the compiler must compile this file.
java Main runs the newly compiled executable.


2. Paranoid programming is good for your health!

Many beginners want to avoid compiler errors and warnings at any cost, which often leads them to ignore the "cryptic" messages the compiler outputs and to tinker anxiously with the relevant line until the error goes away.
Don't fall in that trap! The compiler is your friend, the messages it outputs are kind advices rather than punishments. You should really take the time to try and understand those messages, this is a very good way to improve your code's quality.

As a matter of fact, most seasoned programmers set the compiler's warning level as high as possible, so that it catches the little errors they make when they aren't paying much attention.

**Help needed** Post in thread to recommend content or deletion of this section.


3. Useful tips

**Help needed** Post in thread to recommend content or deletion of this section.

4. Read the manual!

Plain old manpage:

man java

Naturally, the Documentation and Tutorial on the Sun site is a great place to get answers: http://java.sun.com/docs/books/tutorial/


Thanks to so many people @UF for their very useful help, this FAQ wouldn't be the same without them. In particular, this thread is based on aks44's thread on C and C++ (see link in sticky). Not only is this thread based on it, it is blatently copying it, I hope he doesn't mind...

petzworld999
March 3rd, 2008, 05:34 AM
Wouldn't it be this?



javac Main.java


Whenever I compile a file without the extension the compiler spits at me.

LaRoza
March 3rd, 2008, 05:51 AM
Wouldn't it be this?

Whenever I compile a file without the extension the compiler spits at me.

Quite right, thanks. It has been a while...

mssever
March 3rd, 2008, 06:29 AM
Just a small suggestion: Blue text looks like a link (even if the site in question doesn't use blue links). Changing your text highlight color to something other than blue would improve the usability of the page. (useit.com has some info on this, though I don't have the exact link handy.)

pmcastillo
March 3rd, 2008, 07:19 AM
Thanks!!! This would be very good for those who are beginning with programming! ^_^

HuBaghdadi
March 3rd, 2008, 07:48 AM
One more thing:
In order to set Sun Java SDK's tools as the default for your Ubuntu, run the following command:
sudo update-java-alternatives --set java-6-sun

Vladislav Mkrtychev
June 2nd, 2008, 02:14 PM
Thanks!
Page one instructions worked for me - no probs!
I got another question: Does Linux(Ubuntu) have it's
developing tool like DrJava or something similar?

Thanks.

LaRoza
June 2nd, 2008, 02:16 PM
Thanks!
Page one instructions worked for me - no probs!
I got another question: Does Linux(Ubuntu) have it's
developing tool like DrJava or something similar?

Thanks.

http://drjava.org/

It works on Linux.

xlinuks
June 2nd, 2008, 04:59 PM
3. Useful tips
After the user gets comfortable with compiling and running the hello world app, would be good to let him know that nowadays every modern Java program is inside (let's call it) a package namespace. Anonymous packages (like the one in LaRoza's example) should be avoided since it's considered to be a bad habit (more precisely since JDK 1.4). This is especially true when sharing/using third-party libraries to avoid class name collisions.
Since this is probably gonna scare/confuse the user, I think the explanation/example should be very short and comprehensive.
http://en.wikipedia.org/wiki/Java_package
only shows how to import packages, not how the user can create/compile/run them.

themusicwave
June 2nd, 2008, 08:33 PM
You may also want to add links to the major Java APIs these are really helpful and I always have them open anytime I am writing Java.

Here is the page that leads to the various APIs:
http://java.sun.com/reference/api/

Also, java ranch has some great cattle drives for beginers at:
http://www.javaranch.com/java-college.jsp

Otherwise it's a pretty good intro to Java.

LaRoza
June 2nd, 2008, 08:34 PM
These FAQ's are just how to get thing working on Ubuntu, not intros to the languages. The compiling of the sample programs are just to show it works (and a general howto)

My wiki is dedicated to learning, and those links are on it.

themusicwave
June 2nd, 2008, 08:39 PM
We should also add some information abotu setting the CLASSPATH. That can be a major source of issues for newbies and experienced programmers alike.

There are several ways to do this and I am not sure which one is best really. I know the path is: /usr/lib/jdk1.6.0/bin

Any suggestions on which way to set the CLASSPATH.

jamesstansell
June 3rd, 2008, 05:49 AM
Any suggestions on which way to set the CLASSPATH.

For larger projects you should define the classpath through a project definition via ant, maven, or your IDE.

For small projects it should be fine to just use the -cp option to javac, perhaps from a shell script for convenience.

»ync
June 3rd, 2008, 09:36 AM
javac *.java
This works

Vladislav Mkrtychev
June 9th, 2008, 12:18 AM
http://drjava.org/

It works on Linux.

Thanks. I got it installed.
However, when I try to compile, It says "No Compiler Available"
or something similar.
Any ideas on where the compiler might be?

NormR2
June 9th, 2008, 03:28 AM
I've never had an IDE with interactive debugging and have had to rely on print statements to tell me where the program is executing and how variables values are changing.

For example: System.out.println("Here I am. x=" + x);

Often conditional using a boolean so I can turn the output on and off with a single statement change:

boolean debug = true;
...
if(debug){
System.out.println("Here I am. x=" + x);
}

To find out how a method is being called, I add the following statementin the method to print the call stack:


try{throw new Exception("who called");}catch(Exception ex) {ex.printStackTrace();}

You'll need the -g option on the javac compile to have the statement numbers in the code.

If the method is called many times you may only want to see it once:


boolean oneTime = true;
....
if(oneTime) {
oneTime = false;
try{throw new Exception("who called");}catch(Exception ex) {ex.printStackTrace();}
}


Finding NullPointerException in large program that doesn't have enough try{}catch blocks:
Copy the NullPointerException.java class from the source.zip file for your JDK and modify by adding:


// Insert our own special debugging version
public String getMessage() {
try{throw new Exception("Where am I");}catch(Exception ex){ex.printStackTrace();}
return super.getMessage();
}
Compile it and put the class file(s) in its own jar file. Prepend that jar file to the classpath for the java program using the -Xbootclasspath option:


java -Xbootclasspath/p:D:\JavaDevelopment\MyJavaClasses.jar -classpath .... ...

When you get a NullPointerException, your code will be called with its printStackTrace() showing who called.

turtlepaul
June 10th, 2008, 02:44 AM
Thanks. I got it installed.
However, when I try to compile, It says "No Compiler Available"
or something similar.
Any ideas on where the compiler might be?

Same thing for me. It says that it is unable to locate 'tools.jar'.

NormR2
June 10th, 2008, 02:50 AM
It says that it is unable to locate 'tools.jar'.
What is the "It" you refer to?

jamesstansell
June 10th, 2008, 03:29 AM
What is the "It" you refer to?

I believe they're talking about DrJava. Here is what the quickstart guide has to say:

"To compile programs in DrJava, you must make sure you have a Java JDK (Java Development Kit) installed on your machine."

http://drjava.org/quickstartdocs/gettingready.html

To turtlepaul and vladislav:

That page talks about manually downloading and installing the Java SDK from Sun, but hopefully you can just use synaptic to install the sun-java6-jdk package.

Hopefully just installing the JDK package will get things working, but if not then the tools.jar preference mentioned at http://drjava.org/quickstartdocs/preferences.html may need to be set.

turtlepaul
June 17th, 2008, 02:58 AM
I found the tools.jar file and put the location in in the preferences, and it still doesn't work. It says it's incompatible.

NormR2
June 17th, 2008, 03:04 PM
It would help if you would copy and post the full text of the error message you are getting.

LaRoza
June 17th, 2008, 03:33 PM
It would help if you would copy and post the full text of the error message you are getting.

...on another thread.

Shin_Gouki2501
June 17th, 2008, 06:30 PM
if certainly i had too much time and i would consider some kind of :
create GUI's using Eclipse RCP
FAQ. You think that would fit into ubuntu programming forums? Or would it be too complex ?
For myself i'm deeply impressed by the productivity which is offered by the API and i would like to share that experience.

LaRoza
June 17th, 2008, 07:21 PM
if certainly i had too much time and i would consider some kind of :
create GUI's using Eclipse RCP
FAQ. You think that would fit into ubuntu programming forums? Or would it be too complex ?
For myself i'm deeply impressed by the productivity which is offered by the API and i would like to share that experience.

Sure, write up a howto, and we can have a small tutorials section in the sticky for non basic things. That would be cool.

Shin_Gouki2501
June 17th, 2008, 07:38 PM
I have already something , which i "just" need to translate into english. When i'm done , i'll post again!

Flynn555
October 9th, 2008, 02:39 PM
thank you!

this was very helpful...
thinking of taking a java course next semester, i wanna get a head start ;)

monkeystuner
October 10th, 2008, 01:04 AM
Thanks, this tutorial was helpful to me...

0cton
April 6th, 2009, 07:06 PM
I think a usefull tip would be to use an IDE
such as Eclipse or Neatbeans

anotherusernametoforget
September 13th, 2011, 10:12 PM
The following does not, in fact, install anything for me. I imagine the file is obsolete... but I'm a newb so I'll dust off a years-old thread




This package installs the essential tools needed to write and run Java programs.

Code:
sudo aptitude install sun-java6-jdk

sisco311
September 13th, 2011, 11:53 PM
Outdated. Thread closed.

@anotherusernametoforget

I moved your post here: http://ubuntuforums.org/showthread.php?t=1843630