Next page | Contents page |

Exercise 1 - Squarer

  1. If you don't already have it, download and install the free text editor Notepad++ from http://notepad-plus-plus.org
  2. If you don't already have it, download and install the latest free Java development kit (JDK) from java.sun.com (as of July 2010 the latest version of Java SE is Java 6 update 20). NB: Make sure you get the basic JDK, not the JRE, but you do not need the additional FX or EE bits.
  3. Run Notepad++
  4. On the Language menu select J and then Java. This ensures that Notepad++ will recognise some of the words you type and display them in meaningful colours.
  5. On the File menu select New.
  6. Type in the following exactly (letter case is important).
  7. /** Squares any whole number comprising 5 digits or fewer. */
    public class Squarer
    {
    	public static void main (String [] args)
    	{
    		int n = Integer.parseInt (args [0]);
    		int nsq = n * n;
    		System.out.println (n + " squared is " + nsq);
    	} // main	
    } // Squarer
    		
  8. In a directory called ex1 save the text in file Squarer.java (the capital S is important, even in Windows).
  9. Open a command window (in Windows, from the Start button select Run..., type in cmd and click OK).
  10. Navigate to your ex1 directory (in Windows command window: cd {some path}/ex1)
  11. Compile the program by giving the command javac Squarer.java
  12. If that gives error messages they will identify lines in your code by number, to go and correct.
  13. When there are no errors the compiler will simply come back to the command prompt (ex1>) and you will see that file Squarer.class has been created in directory ex1. Notice how small it is (a corresponding C program would be at least a megabyte). That is because a .exe file made from C would contain all the code neded for its execution but a .class file depends on a large library which forms part of the JRE (remember, you need a JRE installed in order to run a Java program; the JDK we installed above does in fact include a JRE).
  14. Run the program by giving the command java Squarer 5 and you should see the output we intended.
  15. Try squaring other numbers. What about 99999? Does it work with negative numbers? Down to -99999?
  16. Particularly if you did not have any error messages before, edit the file to make some deliberate mistakes and try compiling again (javac) to see what the messages are like.

NB: Do use Notepad++ for the first few exercises, NOT NetBeans (or other IDE), because it will help you to understand how the Java system really works. NetBeans (or other IDE) hides a lot of the details. It is trying to be helpful but in doing so it makes you less able to work out why things sometimes go wrong. We will start to use NetBeans later in the course.

Next page | Contents page |