Next page | Contents page |

How does Squarer work?

The source code looked like this, except that I have added line numbers down the left side, as you should have seen in Notepad++.

 1	/** Squares any whole number comprising 5 digits or fewer. */
 2	public class Squarer
 3	{
 4		public static void main (String [] args)
 5		{
 6			int n = Integer.parseInt (args [0]);
 7			int nsq = n * n;
 8			System.out.println (n + " squared is " + nsq);
 9		} // main	
10	} // Squarer
		

Line 1

Line 1 is just a comment for human readers, not part of the executable program. So any typing mistake inside it would not have caused errors. There are 3 types of comment in Java:

  1. /* comment */ can appear anywhere between words or numbers. It can continue over several lines before reaching the */.
  2. /** comment */ is very similar to that, except that it is recognised by the javadoc utility and so will appear in the generated documentation of your work. These comments have to be placed directly before whatever is being documented. In Squarer this kind of comment is used just before the class declaration, so it describes the whole class called Squarer. We will look at this in more detail later in the course.
  3. // comment means that anything to the right of the double slash is a comment, up to the end of the current line but no further. Examples of its use can be seen in Squarer on lines 9 and 10. This is my own convention for marking the ends of certain things - not many people do this in quite the same way.

Tip

Make your comments useful. There is no point in just repeating in words what the code is obviously doing. It is important to make comments about anything which is not immediately obvious to any programmer. Type 1 and type 3 comments will be only be read by programmers looking at the source code, probably to maintain or enhance it. So write the comments in such a way as to help them, not waste their time. Type 2 (javadoc) comments will be seen by anyone wanting to reuse your code, to explain what classes and their constituents do, as black boxes (ie, not usually about how they do it). So again write those kinds of comments from that point of view.

Do write comments, even for your own benefit - you will forget why you did this or that.

Lines 2, 3 and 10

 2	public class Squarer
 3	{
 
10	} // Squarer

This defines the class called Squarer. The use of braces (curly brackets) to group chunks of code is very common and we will see more of it later.

public and class are keywords in the Java language. Keywords are reserved for the language syntax and cannot be used in any other way. They are coloured blue by Notepad++. Java keywords are always all lower case.

public means the class is useable by any other code, which is usually (but not always) the case.

class simply means we are here defining a class. The next thing after this keyword must be the name of the class. Class names begin with capital letters and are then followed by lower case letters. This is only a convention, not enforced by the compiler, but it is universally observed. If you see a Java name following this pattern you can be sure it is the name of a class (or possibly an interface or enum, but we have not met those yet).

A very important thing to remember is that the source code for a class is stored in a file with exactly the same name followed by the extension .java. The case of the letters in the file name is important both to the compiler and, at run-time, to the JVM. (Windows doesn't care about letter case in file names but nevertheless you must follow the Java case convention when naming .java files.)

There are two vehemently opposed schools of thought about where the braces should be placed. You will often see

 2	public class Squarer {
 
10	}

instead of my layout. As far as the Java compiler is concerned it does not matter at all. Line ends (except after // comments) are ignored by javac. The layout only matters for human readability. I belong to the school that thinks placing matching braces vertically above each other helps to see where blocks begin and end. I am very keen on using the clearest possible layout for my code.

(IDEs usually enable you to reformat code between one style and another.)

Lines 4, 5 and 9

 4		public static void main (String [] args)
 5		{

 9		} // main	

Inside the braces of a class we define the data and methods of the class. In this example there is simply one method, called main. The way it is written is very special. Any method that begins public static void main (String [] args) is the starting point of a program: the JVM will begin execution here. It must be written exactly like that every time, so memorise the pattern. (Well, there are a couple of things that could be slightly different but those will be mentioned later.)

As before, public means the method is accessible to other code, and that is essential to let the JVM run it.

static is harder to explain at this stage - we will come back to it later. Just remember to include this keyword.

void means the method main does not return any result to its caller (the JVM). All method declarations must either have a return data type or this keyword immediately before the name of the method.

In this case the method is called main. The (universal) convention is that method names always start with lower case letters, unlike class names.

We know this is a method because it is followed by parentheses (smooth brackets). Whenever a method is either defined or used it must have parentheses after it. Sometimes, but not always, the parentheses have something inside them - parameter values being passed into the method.

In this case there is one parameter, an array ([]) of objects of type String (notice the capital S: it is a class). The array (conventionally called args, short for arguments) holds any parameters entered on the command line when we run the program. The operating system passes those through to the JVM which in turn passes them into our main method. Arrays in Java are always indexed starting from 0 so if n space-separated values are appended to the command line they will be available inside main () as args [0] to args [n - 1].

Line 6

 6			int n = Integer.parseInt (args [0]);

This is the first executable statement of our program, inside the main method. Like all executable statements in Java it ends with a semicolon (;). Remember that line ends are not significant to the compiler but semicolons are.

int is a data type, for whole numbers. We are here defining a variable (a memory location in which we can store things) and giving it the name n. In the same line we are assigning a value to n, by means of the equals sign.

What value are we assigning? Well it must be a whole number but the command parameters, the args array, are merely strings of text. Java is very fussy about data types (that is a good thing - it helps to avoid errors in large programs). It will not let you put anything other than a suitable whole number into a variable declared as of type int. So we have to convert from something of type String to something of type int before doing the assignment. If you knew how to navigate the documentation of the JRE, which we will show later, you would find that there is a class called Integer and one of its methods, called parseInt () does exactly the job we need. It takes in one parameter, which is the string to be parsed to convert it to an integer. You would also see that the return value of parseInt () is indeed of type int. Notice how a dot (.) is used in line 6 to show that parseInt () is a method of class Integer.

Line 7

 7			int nsq = n * n;

This declares another int variable called nsq and assigns to it the value obtained by multiplying n by itself. Most programming languages use the asterisk (*) to denote multiplication because x might be the name of a variable (or method). So at this stage we have two variables with values in them: the original number in n and its square in nsq.

Line 8

 8			System.out.println (n + " squared is " + nsq);

This statement displays the result in the command window (often called the console window). JRE class System has a data field called out which represents the output stream to the console window. That object has a method called println () having one input parameter, a String to be printed. In our case we build the string by concatenating 3 things together: the two values and a bit of text between them. The plus sign is used for string concatenation in Java as well as for numerical addition. The compiler is able to deal with the fact that the values are numbers, not strings. It invokes methods to convert them to strings before doing the concatenation. Finally the "ln" part of the method name means that it appends a line feed to the string too, so the console stream continues on a new line after our result.

Next page | Contents page |