Archive for the 'Tutorials' Category

Your first Java program

Steve on Feb 15th 2009

One last thing before actually typing in a program, compiling it and running it.  You need a text editor that has features useful for a programmer.  Although Windows comes with notepad.exe built in, you really don’t want to be using it to write code. A programmers editor offers special features that help you to write code. These can include colouring different elements of the text in a way that helps understanding, highlighting of useful elements like matching quote symbols or parentheses, automatic help for language keywords, etc.

There are too many programmers editors available to go into a detailed analysis or comparison here. However, a recommendation for a particular editor is also a bit awkward for me to offer! I personally use SlickEdit and have done so for many years, but it’s a very advanced and also very expensive tool (currently $299 for a Windows license). For an advanced programmer already familiar with Integrated Development Environments (IDEs for short), I would recommend Eclipse as probably one of the most used and advanced Java programming environments available.  For someone literally starting out programming though, IDEs can be very overwhelming and confusing. Conversely, they often simplify the processes involved in programming (eg. automatic compilation) which beginners need to be exposed to in order to gain a thorough grounding.  As I continue these tutorials, there will be natural points where more advanced tools (such as Eclipse) can be introduced, but here at the beginning, I’m going to recommend a free (as in beer and speech) programmers editor called Notepad++.

Installing Notepad++

  1. First things first, head over to the Notepad++ download page and follow the links to grab the latest version binary install file.  Or here’s the direct link for downloading version 5.2 from sourceforge.net.
  2. Run the installer program and follow the prompts to install.  Leave all the options as they are, the installation is quick and painless, and leaves a handy icon on your desktop, which can be put right next to the Java Programs command line icon we created last time.
Notepad Plus Plus

Notepad++

Coding your first Java program

  1. When you start Notepad++ for the first time, it loads a file called change.log which tells you all the things that have changed since the last version. Close this by selecting File->Close.  This leaves you with an empty file.
  2. Type in the following Java source code exactly, being careful to match the case of the letters (particularly the H and W or HelloWorld are in upper case).  You can indent lines with tabs or spaces, your choice. You can also just select copy to clipboard and paste it into your Notepad++ window.
  3. public class HelloWorld
    {
       public static void main (String [] args)
       {
          System.out.println ("HelloWorld");
       }
    }
  4. Now save the file, making sure it’s called HelloWorld.java into your C:\Java\Programs folder. Do this by selecting File->Save, selecting My Computer and navigating to your C: drive, then into the Java and Programs folders. Then enter HelloWorld.java into the “File name” box and clicking the Save button.
  5. You’ll notice that after you’ve saved the file, the text in the window changes to include some colour. This is because Notepad++ now recognises your program as a Java program, due to it being a file with .java on the end.  All Java source code file must use the .java suffix.

Compile and run your program

A PC cannot directly execute Java source code, until we get to more advanced topics that is. For now, it suits our purposes to understand that source code can’t be ‘run’ straight away, we need to process it into a form that the computer can understand. The source code needs to be compiled. To do this, you need to use the Java compiler program, javac, from the command line.

  1. Double click on your “Java Programs” desktop shortcut to bring up the command window, already in the C:\Java\Programs folder, which is handy.  If you type dir and press enter, this will see a listing of the files in the folder, which will include our newly created HelloWorld.java source code file.
  2. Enter javac HelloWorld.java (and press Enter). Nothing will appear to happen unless there are errors in the program.
  3. Enter dir again and you will see that there is now a file called HelloWorld.class. This file is the compiled code file, it is in an unreadable binary format, but this is how the computer likes it.
  4. Enter java HelloWorld.  This command tells the PC to execute the compiled Java program, and the program prints out the text “Hello World”.  If you study the program source carefully, you can see the line that outputs the text onto the screen. See if you can change this text, save the source file, then compile and run the program again.

Here’s what you should see in your command window if everything goes well.

Command Line Compile

Command Line Compile

That’s it for now, well done on getting this far.  Next time I’ll introduce some errors into the program and we’ll see what happens when things go wrong. If you’ve already had some errors from the javac compiler, carefully check through your source code to see if you can find the problem. Also carefully read the exception message you get when attempting to compile. The Java compiler is actually quite good at recognising problems and will tell you which line of your program is wrong.

Filed in Tutorials | No responses yet

Next steps with Java

Steve on Feb 12th 2009

Well that first tutorial, installing a JDK, was pretty easy. About the only complicated thing was actually navigating to the right place to get a download link on Suns website. Pretty soon, we can write some actual code and see it working, but there are a couple of things worth doing before that to save us time later on. Sometimes, performing a couple of minor housekeeping actions or simple ‘one time’ setups can really save time, especially when using a command line, like we’re going to.

Opening a command line

Although you might think it’s a bit primitive to actually type commands into a computer, doing so really makes you feel that you’re controlling the machine. When you click on an icon on your desktop, do you really know what’s happening? Most of the time even I don’t, and that’s no bad thing in the majority of cases. Actually typing commands makes you feel like it’s really you in control, and not someone else, who happened to put an icon in front of you to click.

  1. Go to the Start Menu and find ‘Command Prompt’.  If it’s not immediately obvious, it will be in ‘All Programs->Accessories’.  The icon is a black square, with a white C:\_ in it on Windows XP.  When you’ve found it and clicked on it, you’ll end up with a window that looks like this:
Windows XP Command Line

Windows XP Command Line

Now, if you type java -version and press Enter, you’ll get a printout from the Java Virtual Machine program detailing it’s version number and a couple of other things.  If this doesn’t happen, then you probably didn’t install the JRE along with the JDK, which isn’t a problem, we’ll fix that in the next step.

Setting the PATH

The java program we invoked just now is needed to run programs written in the Java language.  In order to create programs in the Java language, you need to invoke a program called javac, which stands for Java Compiler.  If you type javac in the command line (and press enter), Windows will helpfully inform you that it can’t find the program, you’re screwed, sorry. I kid!  Actually Windows just doesn’t know where to find it, so we need to tell it. Here’s what you do:

  1. Open the Windows control panel, usually it’s in the start menu.
  2. If it says “Pick a Category”,  select “Performance and Maintenance” then “System” from the bit at the bottom where it says Pick a Control Panel icon.  If you’re in Classic View, just select the “System” icon.
  3. In the window that opens up, click on the Advanced tab.
  4. Click on the button labeled “Environment Variables”.
  5. You’ll notice that there’s an entry in the bottom list called “Path”.  This is where windows looks for programs to run on the command line.  You don’t want to change this, altering the “System Variables” can be risky, but we can add a “User Variable” of our own.
environment_path

Environment Settings

Click on the New button in the middle of the window and add a new User Entry called PATH (where it says Variable name).  Set the value (Variable value) to C:\jdk1.6.0_12\bin and press the OK button.  If you didn’t install the JDK into that path, you need to enter wherever you did install it too, of course.

Finally, you need to close your command line window and open it again.  Type javac and press enter.  This time, you should get a list of options we won’t worry about for now.  Windows should not tell you it can’t find anything!  You can also type java -version and see that output too now, if you couldn’t before.

A custom command line

You’ll notice that when you open  the command line, it automatically sets the current working directory as your ‘home’ folder, which on Windows is the lovely C:\Documents and Settings\<Username>. In my case, that path name has 2 spaces in it!  It’s also not where I want to store any Java programs I might write.  I want to put my Java programs in a folder called C:\Java\Programs, and I’m also going to use C:\Java for some other tools later on too.  So, type the following simple commands into the command window to create the folders:

  1. cd C:\ <Enter>
  2. mkdir Java <Enter>
  3. cd Java <Enter>
  4. mkdir Programs <Enter>

Now you want to create a shortcut on the Desktop, that will open the command prompt straight into your Java programs folder.

  1. Close the current command line by typing exit, or clicking the X button.
  2. Right click with the mouse on the Desktop and select New->Shortcut
  3. Type cmd.exe in the box labeled “Type the location of the item”, click Next.
  4. Enter a meaningful name, like “Java Programs” and click Finish.
  5. Now right click on the new shortcut and select Properties.
  6. In the box labeled “Start in:”, that probably has %windir% in it, change %windir% to C:\Java\Programs and click OK.
command_line_properties

Command Line Properties

Now you have a handy shortcut on the desktop that will take you to your Java programs folder straight away.  Next time, I’ll talk about getting a programmers editor to actually write code with.  If you want to try something straight away, try finding a simple Java ‘Hello World’ program on the net, typing it in using Notepad, compiling it and running it.

If none of those terms made any sense, I’ll be carrying on soon.

Filed in Tutorials | No responses yet

First steps with Java

Steve on Feb 9th 2009

Programmers like debating till the cows come home about the best languages to use for teaching and learning to program.  I first programmed a computer using BASIC, but that was never anything more than typing listings from magazines and books into my Sinclair Spectrum. I didn’t learn much back then, but I gained an understanding of the endless possibilities programming can offer.

I’m not actually going to advocate Java as a first language, but it is a language I know intimately, and if I’m going to write coding tutorials on anything, I’m most qualified to do it in Java!

Installing the Java Development Kit

Before you can do anything with Java, you need to install a Java Development Kit, or JDK, on your PC. You might already have what’s called a Java Runtime Environment, or JRE, installed, but unfortunately this won’t help you for programming. You go to java.sun.com to get JDKs for different platforms. There’s quite a bit of stuff to browse around, and it can be confusing if you just want to get going quickly and aren’t quite sure what you need. Specifically, you want to follow the link on the right for Java SE (Standard Edition) in the Popular Downloads box.  Then, look for the latest version of the Java SE Development Kit, which is Version 6 Update 12 (as of February 2009). The following link should take you directly to the download page:

Download Java Development Kit 6u12

Once you’ve downloaded the 73Mb jdk-6u12-windows-i586-p.exe (which is the Windows installer) simply run it to start the installation.  I won’t lead you through the installation step by step in a patronising fashion, it would take far to long and pad the post out with useless images of the installer wizard at each stage.  However…

There’s one thing to think about when installing the JDK, the location you install it too.  By default, the installer wizard will offer to install the components to C:\Program Files\jdk1.6.0_12\ which will work of course, but has 2 problems.  The first is that it’s quite a long path, and if you do any Java programming for a while, you’ll find yourself typing it in many times.  The second is that it has a space in it, which can cause no end of problems (the path is even word wrapped in this post), even in the 21st century. I reckon it will still be a problem in the 23rd century!

Jean-Luc Picard: Get that computer operating again Mr La Forge.

Geordi La Forge: I’m sorry captain, the firmware update file has a space character in its name, our tools can’t handle it.

I prefer to use a shorter path, right in the root of C:

Highlight of the JDK Install Wizard install location
Highlight of the JDK Install Wizard

You might as well  include all the other items along with the install, unless you’re running short on hard drive space!  I’ve not had any call to use the JavaDB yet though.

Well, that’s it for installing the Java Development Kit. Soon, I’ll go over a bit more basic setup to make your life easier coding Java, and some simple programs.  You can also go and look around java.sun.com and dive into the Essentials of the Java Programming Language and other tutorials if you’re really keen.

Filed in Tutorials | No responses yet