Saturday 12 December 2009

Java Introduction Part 3 - Arithmetic Operations

This is the third part on the Java Introduction posts. In this post I would like to discuss about the arithmetic operators that the Java language supports. Even though the theory behind them is simple, it is vital and basic knowledge that needs to be acquired in order to write programs in Java

These arithmetic operators are summarized below:
  • Addition
  • Subtraction
  • Multiplication
  • Division
  • Remainder
Let's take each on of the operators and present an example on how to use them in a program.

In order to add two integers in Java, we use the plus sign (+). Assuming that we have declared two integer variables as number1 and number2 respectively, the addition can be defined as follows:

sum = number1 + number2; // add two numbers

The subtraction in Java uses the same principle as the addition. The symbol used for subtraction is the minus sign (-). Re-using the two integer variables from the previous example, the subtraction can be defined as follows:

subtraction = number1 - number2; // subtract two numbers

For the multiplication, we use the asterisk sign (*). Again using the variables from the examples above, the multiplication can be defined as follows:

product = number1 * number2; // multiply two numbers

For the division, we use the forward slash sign (/). Again using the variables from the examples above, the division can be defined as follows:


fraction = number1 / number2; // divide two numbers

* Please note that if the division takes part between two integers, the result yields an integer quotient. So, for example, 17 / 5 evalutes to 3. Any fractional part in integer division is simply discarded - no rounding occurs.

For this reason, Java provides the remainder operator (%) which yields the remainder after the division.  Again using the variables from the examples above, the remainder can be defined as follows:


remainder = number1 % number2; // remainder of a division between two numbers

* In this, 17 / 5 evaluates to 2 (since 5 can be multiplied by 3 which evaluates to 15. To get to 17 we need 2 which is the remainder).



An example of putting all of these arithmetic operators into a simple program can be found below:

// ArithmeticOperators.java
/* Simple Java program that illustrates the use of the arithmetic operators that the Java language supports */

 public class ArithmeticOperators
 {
     // main method where the execution of a Java application begins
     public static void main (String args[])
     {
        int number1 = 17; /* Declare an integer variable number1 and assign the number 17 to it */
        int number2 = 5; /* Declare an integer variable number2 and assign the number 5 to it */
       
        // Addition
        /* Declare an integer variable sum and assign the sum of number1 and number2 to it. The value assigned to the variable sum is the number 22. */
        int sum = number1 + number2;
        System.out.println("The sum is equal to " +  sum); /* Print out the sum */
       
        // Subtraction
        /* Declare an integer variable difference and assign the difference of number1 and number2 to it. The value assigned to the variable sum is the number 12. */
        int difference = number1 - number2;
        System.out.println("The difference is equal to " +  difference); /* Print out the difference */
       
        // Multiplication
        /* Declare an integer variable product and assign the product of number1 and number2 to it. The value assigned to the variable product is the number 85. */
        int product = number1 * number2;
        System.out.println("The product is equal to " +  product); /* Print out the product */
       
        // Division
        /* Declare an integer variable fraction and assign the fraction of number1 and number2 to it. The value assigned to the variable fraction is the number 3. */
        int fraction = number1 / number2;
        System.out.println("The fraction is equal to " +  fraction); /* Print out the fraction */
       
        // Remainder
        /* Declare an integer variable remainder and assign the remainder of number1 and number2 to it. The value assigned to the variable remainder is the number 3. */
        int remainder = number1 / number2;
        System.out.println("The remainder is equal to " +  remainder); /* Print out the remainder */
       
     } // end of main method
} // end class ArithmeticOperators

Java Introduction Part 2 - Comments

This is the second part on the Java Introduction posts. I would like to discuss in detail the importance of comments in Java development and present the different styles that a programmer can use in order to enrich a program and make it more readable to peers and other programmers.

There are three different ways when it comes to inserting comments into a Java application. These can be categorized as follows:
  • End-of-line comments
  • Traditional comments
  • Javadoc comments
An end-of-line comment begins with two forward slashes ("//") and indicates that the remainder of the line is a comment. The comment terminates at the end of the line on which it appears. A // comment can begin at any point within a line and will continue until the end of that line.

A traditional comment (also called a multiple-line comment) can be spread over several lines. This type of comment begins with a forward slash and an asterisk ("/*") and ends with an asterisk and a forward slash ("*/"). An example is shown below:

/* This is a comment
    the spans over
    several lines */

All text between /* and */ is ignored by the compiler and will not affect the execution of the program.

Java also provides Javadoc comments which begin with a forward slash followed by two asterisks ("/**") and ends with an asterisk and a forward slash ("*/"). Again all Javadoc comments will be ignored by the compiler. Yet the javadoc utility program (which is part of the J2SE Development Kit) will read the Javadoc comments and will be used to prepare a documentation of the program in HTML format.

An example of Javadoc comments is shown below. This example has been take from How to Write Doc Comments for the Javadoc Tool by Sun Microsystems.

/**
 * Returns an Image object that can then be painted on the screen. 
 * The url argument must specify an absolute {@link URL}. The name
 * argument is a specifier that is relative to the url argument. 
 * 
 * This method always returns immediately, whether or not the 
 * image exists. When this applet attempts to draw the image on
 * the screen, the data will be loaded. The graphics primitives 
 * that draw the image will incrementally paint on the screen. 
 *
 * @param  url  an absolute URL giving the base location of the image
 * @param  name the location of the image, relative to the url argument
 * @return      the image at the specified URL
 * @see         Image
 */
 public Image getImage(URL url, String name) {
 try {
     return getImage(new URL(url, name));
 } catch (MalformedURLException e) {
     return null;
 }
 }
 
This Javadoc comment will produce the following output which again has been taken from How to Write Doc Comments for the Javadoc Tool by Sun Microsystems.

getImage

public Image getImage(URL url, String name)
Returns an Image object that can then be painted on the screen. The url argument must specify an absolute URL. The name argument is a specifier that is relative to the url argument. This method always returns immediately, whether or not the image exists. When this applet attempts to draw the image on the screen, the data will be loaded. The graphics primitives that draw the image will incrementally paint on the screen.
Parameters:
url - an absolute URL giving the base location of the image
name - the location of the image, relative to the url argument
Returns:
the image at the specified URL
See Also:
Image
 

I cannot stress enough how important comments are to Java programs, and
any programs for that matter. Having worked for a number of years as a
developer I can only say that a bad written program without any
comments is as good as having no program at all. The amount of time
that you will spend in order to understand what a complex Java program
is supposed to be doing and then modify it to enhance it, will make you
appreciate comments as much as I do.

Java Introduction Part 1 - Hello World

As it is a common theme to introduce a language by providing a "Hello World" example, I have decided to follow the same pattern.

Below is a simple Java program which prints out in the console the message "Hello World". This simple program will print out in the console the message "Hello World !!!". Following the example, we will walk through each line and explain what it does. We will come across a lot of keywords and identifiers which will discuss in subsequent posts. For now we will just walk through the program to see how it works without worrying too much about the underlying complexity hidden in the aforementioned keywords and identifiers.

  1. // HelloWorld.java
  2. // Simple Java program that prints out in the console the message "Hello World !!!"

  3. public class HelloWorld
  4. {
  5.     // main method where the execution of a Java application begins
  6.     public static void main (String args[])
  7.     {
  8.         System.out.println("Hello World!!!");
  9.     } // end of main method
  10. } // end class HelloWorld

Let's take now each line and explain what the line does.

Lines 1-2:
  1. // HelloWorld.java
  2. // Simple Java program that prints out in the console the message "Hello World !!!"
As we can see both lines begin with two forward slashes ("//"). This symbol indicates that the remainder of the line is a comment. It is always a good practice to use comments in order to document programs and improve their readability. Inserting comments into a program also helps other people to read and understand programs. Comments are ignored by the Java compiler; therefore they do not affect the execution of the program when it runs.

Line 3: This is an empty line.

Line 4:
  
      4.  public class HelloWorld

This is a class declaration for class HelloWorld. Every program in Java should contain at least on class declaration which is defined by the programmer. The word class is a Java keyword and is used to declare a Java class, followed by the class name (HelloWorld in our example). Keywords (or reserved words) are special words in Java; they are always spelled in lower case and cannot be used by the programmers as identifiers.

* By convention all Java class names follow the pattern below:
  • Java class names begin with a capital letter
  • Capitalize the first letter of each subsequent word.
Example: SampleClassName.

Line 5:
  
      5.  {

Line 5 in this program is a left brace. This symbol begins the body of every class declaration. A corresponding right brace (at line 11) must end each class declaration.

Line 6:
  
      6.  // main method where the execution of a Java application begins

Line 6 (as lines 1 and 2) is an end-of-line comment. As we can see, from line 6 onwards, there is an indentation pattern which is one of the spacing conventions used in Java to make the programs more readable. This convention is used throughout the program and every time a left brace is opened, the following line is intended using the TAB button.

 
Line 7:
  
      7.  public static void main (String args[])

Line 7 is the starting point of every Java application. The parentheses after the identifier main indicate that this is a program building block called a method. Normally there are one or more methods defined within a Java class. Line 7 contains a number of keywords (marked in blue) which we will discuss now.

The keyword public is called an access modifier. This allows the class to be accessible from the entire workspace. Other access modifiers exist to limit the access of a class by other classes. More about access modifiers in subsequent posts.

The keyword static indicates that this method is special since it can be called without first creating an object of that class. More about objects in subsequent posts.

The keyword void indicates that this method will perform a task but will not return any information when that task is completed. More about return types in subsequent posts.


Line 8:
  
      8.  {

Line 8 is again a left brace. The body of the method declaration begins here. A corresponding right brace will end this method declaration's body in line 10. Again we can see that the following line is indented to the right using the TAB button.


Line 9:
  
      9.  System.out.println("Hello World!!!");

Line 9 instructs the computer to perform an action. It will print to the console the string of characters included within the double quotation marks. System.out is known as the standard output object and allows the Java application to display a set of characters in the command window where the Java application is run from. The System.out.println method prints a line of text in the command window. As with the main method, this method is followed by parentheses. Within the parentheses we specify the argument(s) of the method. In this example, we specify the string to be printed in the command window. The statement (action to be performed) ends with a semicolon (;) and the whole line 9 that ends with the semicolon is called a statement. Every statement must end with a semicolon.

* Please note that omitting the semicolon at the end of the statement is a syntax error and the program will not run.

Lines 10-11


      10.    } // end of main method
      11.  } // end class HelloWorld

Lines 10-11 contain the closing brackets for the method's declaration body and the class. They also contain comments to make the program more readable. 

This concludes Part 1 of the Java Introduction posts. We have written a simple Java program that prints "Hello World !!!" to the command window and we have discussed the various bits and bobs that make up the program.  

First post ...

As a first post I would like to introduce myself and explain what this blog is all about.

To get started, my name is Christoforos Nikitas and I am currently a Consultant for SunGard Consulting Services. I am specializing in Java development and I am very interested in the financial sector.

I originally come from Athens, Greece but have settled in London, UK for the past 5 years.

This blog will contain posts concerning mainly Java programming (maybe a few posts regarding other technologies) as well as various posts on financial theory, products and markets.

Instead of diving into the complex aspects of the Java programming language, I will be starting with posts introducing the Java language and increasing the difficulty gradually.

Introductory posts in financial theory, products and markets will follow as well.