Introduction to Java

Java's History

Java was first developed as an operating system in 1991.  It was originally known as Oak and written by James Gosling.  In 1994 Oak was adapted to web technology and was launched into popularity in 1994 by Sun Microsystems and known as HotJava.  Many of the large technology companies such as Microsoft, IBM, and Corel were interested in this new product.  Sun has endured a number of legal battles over Java including one it lost giving another company the write to retain the name Java Script.  Java Script is still used today and is very popular with web page authors.  Java Script is therefore often confused with the Java programming language because of the similarity in the name.  In reality, the Java programming language and Java Script are not related.  Proficiency in Java Script does not necessarily translate into knowledge about the Java programming language.

The first Java Development Kit (JDK) was released and available for free in 1996.  Today, you can still download both the most current and older versions of the JDK for free from Sun Microsystems.  Java programs can be created using Notepad and the JDK.  It is not necessary to have an IDE (Integrated Development Environment) to write Java programs.  We use and IDE in class to help with formatting our programs and to make it easier to discover and correct errors.  Many Java IDEs are available to make writing programs easier.  Some of the more common ones include Borland's JBuilder, Code Warrior, and JCreator.

Your First Program

This first program is being used to introduce the structure of the Java language and the IDE we are using in class.  The program will output a simple line of text to the screen.  Create a new project titled unit1 and add to it a class file called Aliens.  In the class coding window type the following code:

/* The Aliens Program
     Programmed by Mr. Joy Augustine, January 2004
    This program is an introductory program, which will result in a single line
    of output on the screen.*/

public class Aliens {

     public static void main (String [ ] args){
         System.out.println("Aliens have landed in the backyard!");
     }// end main method

}//end class

Run the program and you will see a simple line of output: Aliens have landed in the backyard!

Let's look at the parts of the program.  The first part begins with /* and ends with */.  These symbols enclose multi-line comments.  Comments do not affect the way your program runs.  The first three lines of your programs should always be comments.  The first line should be the name of the program.  The programmer's name and the date go on the second line followed by a short description of what this program is about.  Single line comments begin with //.

Java programs usually begin with the words public class [the name of the program] and an opening brace bracket {.  Remember that for every brace bracket you open, you must have another which closes the statement }.  The class name must always be the same as the file name including upper and lower case letters.  Java is case sensitive.

Methods are the components inside the { } brace brackets.  In this case there is only one method.

We will be looking at two kinds of Java programs in this course, applications and applets.  Applications are programs which can run on their own.  Applets must run inside a web browser.  The Aliens Program is an application.  All of the applications you will write in this course will have a main method which begins with the words public static void main (String [ ] args).  Let's look at what this means:

public -> means that other classes can call this method

static -> means that main() exists even though no class objects have been created

void -> means the method does not return a value

main -> is the name of the method, it is also the name of the method that begins every application

String [ ] args -> is an array of parameters that could be passed to the method

Swing Classes

Instead of command line output, we can also have output dialog boxes.  These are part of the Swing classes.  Swing components are built in GUIs which allow us to make interfaces which are more user friendly.  The following code is an example of the use of dialog boxes.

/*The Welcome Program
 *Programmed by Mr. Joy Augustine, January 2004
 *This program demonstrates simple output in a dialog box. */

import javax.swing.JOptionPane;       //imports the class JOptionPane and makes it
                                                               //and makes available for use by the program.

public class Welcome{
    public static void main (String [ ] args){
        JOptionPane.showMessageDialog(null, "Welcome to Java Programming. JAVA RULES!");

        System.exit(0);                            //necessary to properly terminate the program

    }//end main

}//end class

There are a number of escape characters, which help format output.  The one we are primarily concerned with is \n which places output on a new line.  Escape characters must be enclosed within a set of quotation marks.  Try the following code and see how the output from the above program changes.

/*The Welcome2 Program
 *Programmed by Mr. Joy Augustine, January 2004
 *This program demonstrates multi-line output in a dialog box. */

import javax.swing.JOptionPane;          //imports the class JOptionPane and makes it
                                                                  //and makes available for use by the program.

public class Welcome2{
    public static void main (String [ ] args){
        JOptionPane.showMessageDialog(null, "Welcome to \nJava Programming.\nJAVA RULES!");

        System.exit(0);                               //necessary to properly terminate the program

    }//end main

}//end class

Classes and Methods

When we create Java programs in JBuilder, we begin by defining a project.  Classes are the primary building blocks of all Java programs.  Each application program is a class.  The class name must always be the same as the file name.  When you first create the class file you save it with the .java extension.  When the file is compiled, or built, a bytecode file is created.  The bytecode file has a class extension instead of the .java extension.

Inside a class you have methods.  A class can have one or more methods.  Applications will always have one method called the main method.  The main method is like the director of a play in that it cues or calls the other methods when it is their turn to run.  A good main method contains primarily method calls.  Methods are segments of programming code that have a particular purpose.  It is possible to have many methods in a class file.  Let's examine using methods by writing a program that will output the lyrics to the song Happy Birthday.

Create a new class called HappyBirthday and enter the following code to demonstrate the use of multiple methods within one class.

/* The Happy Birthday Program
 * Programmed by Mr. Joy Augustine, January 2004
 * This program will demonstrate the use of multiple methods within one class.*/

public class HappyBirthday{

    public static void sayHappy(){
        System.out.println("Happy Birthday to you.");
    }//end sayHappy

    public static void greeting(){
        System.out.println("Happy Birthday dear Mom,");
    }//end greeting

    public static void main (String [ ] args){
        sayHappy();
        sayHappy();
        greeting();
        sayHappy();
    }//end main

}//end class

The main method in this case only calls the other methods in the order they are needed.  

Passing Parameters

Passing information from one method to another is also known as passing parameters.  In the next version of this program, we will introduce the use of variables, show how we can concatenate output, and pass parameters.  Create a new class named HappyBirthday2 and enter the following code.

/* The Happy Birthday2 Program
 * Programmed by Mr. Joy Augustine, January 2004
 * This program will demonstrate the concept of passing parameters from one
 * method to another.*/

public class HappyBirthday2{

    public static void sayHappy(){
        System.out.println("Happy Birthday to you.");
    }//end sayHappy

   public static void greeting(String name){
       System.out.println("Happy Birthday dear " + name);
    }//end greeting

    public static void main (String [ ] args){
        String birthdayName = "Mortimer,";
        sayHappy();
        sayHappy();
        greeting(birthdayName);
        sayHappy();
    }//end main

}//end class

Notice the variable name being used by the sending method, greeting (birthdayName) is not the same as the variable name being used by the method receiving the parameter (name).  They however, be of the same type.  The only way you can send information from one method to another is by using parameters.  Parameters or as they are sometimes called, arguments, can be passed by reference to a variable name or by value.  The following program uses both values and variable names to send information from one method to another.  Create a new class called HappyBirthday3 and enter the following code.

/* The Happy Birthday3 Program
 * Programmed by Mr. Joy Augustine, January 2004
 * This program will demonstrate the concept of passing parameters from one
 * method to another. It shows that parameters can be passed either by variable
 * name or by value.*/

public class HappyBirthday3{

    public static void sayHappy(){
        System.out.println("Happy Birthday to you.");
    }//end sayHappy

    public static void greeting(String firstName, String lastName){
        System.out.println("Happy Birthday dear " + firstName + " " + lastName);
    }//end greeting

    public static void main (String [ ] args){
        String birthdayName = "Mortimer";
        sayHappy();
        sayHappy();
        greeting(birthdayName, "Snerd");
        sayHappy();
    }//end main

}//end class

The receiving method, greeting, must declare two string variables in the first line of the method to receive the parameters being sent to it from the sending main method.  One of the parameters being passed is a variable (birthdayName) and the second is a value (Snerd).

Keyboard Input

The next logical change for this program is to allow the user to type in the name of the birthday person.  To do that there has to be a number of changes.

The first is to make available the Java input/output routines.  Java just loads a very basic set of tools and as other features are needed they are added.  This is done through the use of import statements that happen before the class is defined.  To use keyboard input, the statement: import java.io.*; must be added as the first line of the program.

The next step is to modify the main method.  Using the keyboard or disk access means there is a possibility that an error could occur, for example if the keyboard is not working correctly or a file is not found.  Such an error in Java is called an exception.  The words throws IOException must be added to the definition line of the main method.

The third change is to define the input stream reader.  In Java, input and output is handled in streams.  No matter what the source or destination, data is a stream of binary characters, hence the word stream.  The statement to create an input stream reader is: BufferedReader br = new BufferedReader (new InputStreamReader (System.in));

This statement uses two classes, BufferedReader and InputStreamReader.  They are used together to build the functionality that is needed.  The word new is important, it actually loads a copy of the class into memory and therefore creates a new object.  The object in this case is called br, the name could be anything that the programmer decides to call it.

The last thing we have to do is use keyboard input.  We can do this by first prompting the user to enter a name and then getting the input.  The code could read something like this:  System.out.print ("Please enter the birthday person's name: ";  followed by the line: String birthdayName = br.readLine ( );  The variable birthdayName can now be passed to the greeting( ) method.  Create a class called HappyBirthday4 and enter the following code.

/* The Happy Birthday4 Program
 * Programmed by Mr. Joy Augustine
 * This program will demonstrate the use of keyboard input with a command line
 * program. Input will become the parameter being passed between methods.*/

import java.io.*; // imports the java io utility

public class HappyBirthday4{

    public static void sayHappy(){
        System.out.println("Happy Birthday to you.");
    }//end sayHappy

    public static void greeting(String name){
        System.out.println("Happy Birthday dear " + name);
    }//end greeting

    public static void main (String [] args) throws IOException{
        BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
        System.out.print("Please enter a name: ");
        String birthdayName = br.readLine();
        sayHappy();
        sayHappy();
        greeting(birthdayName);
        sayHappy();
    }//end main

}//end class

Primitive Data Types

Java data types include primitive data types and objects.  Primitive data types are created without using a class.  For example any string is an object, such as a name from one of the HappyBirthday programs.  A string is created from the String class.  There will be more about Strings later in the course.  The primitive data types are:

For integer values:
byte, short, int, and long which use 1, 2, 4, and 8 bytes of space respectively; byte and short are rarely used anymore, int covers most of the situations in this course and programming courses you will take at university or college.  There are some cases where long is needed.  The range for int is -2,147,483,648 to +2,147,483,647.

For decimal values:
float and double - float uses 4 bytes of space and double uses 8 bytes.  We will primarily use double for accuracy and convenience.

For character values:
char - holds one UNICODE character and takes up 2 bytes of space.  When assigning a char value to a variable it should be enclosed in single quotation marks.

For boolean values:
boolean - contains either true or false in that format, full word, lower case.

Primitive Data Type Declaration and Assignment

Declaration

All primitive data types or variables must be declared before they can be used in a program.  The statement int number; declares an integer data type called number.  Other examples are:

int mark;
double cost;
char letter;
boolean flag;

More than one variable of the same type can be declared in one line, with the variables separated by commas.  The statement: int totalMarks, numCourses; declares two integer variables totalMarks and numCourses.

Assignment

An assignment statement gives a value to a variable.  The statement number = 15; stores the integer value 15 in the variable identified as number.  Some other examples are:

mark = 78;
cost = 34.75;
letter = 'b';
flag = true;

Declaration and Assignment

It is possible to both declare and assign a value to a variable in one step.  Examples are:

int mark = 78;
double cost = 34.75;
char letter = 'b';
boolean flag = true;

Operators

The statement int number = 16; uses the equal sign as the assignment operator.  

The operators for basic mathematical operations are:

+  addition
-  subtraction
*  multiplication
/  division
%  modulus

The comparison operators are:

==  equals
!=  not equal
>  greater than
<  less than
>=  greater than or equal to
<=  less than or equal to
&&  and
||  or

There are other special operators that can be used in Java.  Since the number one is used so frequently for many constructs it has the most flexibility.  If we wanted to add one to a value of a variable called number it can be done in the following four ways:

number = number + 1
number++
++number
number+=1

To subtract one from the value of a variable called number any one of the following four methods could be used:

number = number - 1
number--
--number
number-=1

There are other short forms for using numbers.

number +=12;  means add 12 to the number
number -=12;  means subtract 12 from the number
number *=12;  means multiply the number by 12
number /=12;  means divide the number by 12;

Keyboard Input of Numbers

We have looked at the BufferedReader class to input strings.  Inputting numbers from the keyboard is more complicated as a translation has to be done from String to the correct data type format.  For now the following class will be used to do this.  Copy this code into a new class called the ReadNum class then save and compile the code.

/*The ReadNum Program
 *Programmed by Mr. Joy Augustine, January 2004
 *This is the first part of a class library program, which will be used by other
 *programs to demonstrate how methods in other classes can be used.*/

import java.io.*;
import java.util.*;

public class ReadNum {
    static private StringTokenizer stok;
    static private BufferedReader br = new BufferedReader (new InputStreamReader
    (System.in));

    public static int readInt(){
        int i = 0;

        try { //attempt getting input from keyboard
            String str = br.readLine();
            StringTokenizer stok = new StringTokenizer (str);
            i = new Integer (stok.nextToken()).intValue();
        }//end try statement

        catch (IOException ex){
            //print out an error message if keyboard input doesn't work.
            System.out.println(ex);
        }//end catch statement

        return i; //return an integer value to the method which called this one.
    }//end readInt

    public static double readDouble(){
        double d = 0;

        try { //attempt getting input from keyboard
            String str = br.readLine();
            StringTokenizer stok = new StringTokenizer (str);
            d = new Double (stok.nextToken()).doubleValue();
        }//end try statement

        catch (IOException ex){
            //print out an error message if keyboard input doesn't work.
            System.out.println(ex);
        }//end catch statement

        return d; //return a double value to the method which called this one.
    }//end readDouble

}//end class

As you progress through in the course, you will be able to understand the commands in ReadNum, for now you just have to learn how to use it.  The following program will now let us use the ReadNum class we have just created.

/*The ReadDemo Class
 *Programmed by Mr. Joy Augustine, January 2004
 *This program implements the ReadNum class */

import ReadNum;

public class ReadDemo{

    public static void main (String [ ] args){
        int number;
        double decimal;

        System.out.print("Enter and integer: ");
        number = ReadNum.readInt();
        System.out.println("The integer value you entered was: " + number);
        System.out.print("Enter a decimal value: ");
        decimal = ReadNum.readDouble();
        System.out.println("The decimal value you entered was: "+ decimal );
    }//end main
}//end class

Note that in order for this program to work the ReadNum class must be in the same project folder as the ReadDemo class and the ReadNum class has to be compiled or built.

We can of course also use swing components, which allow us to use input dialog boxes and use somewhat different code to do conversions from strings to integers or decimals.  The following program demonstrates the use of input boxes and Integer and Double classes to parse string input.

/*The Addition Program
 *Programmed by Mr. Joy Augustine, January 2004
 *This program demonstrates the use of input boxes and a message box.
 *The program will ask the user to enter two numbers into dialog boxes,
 *add the two numbers, and output the result into a message box.*/

import javax.swing.JOptionPane;    //import class JOptionPane

public class Addition{
    public static void main (String [ ] args){
        String firstNumber,                   //first string entered by the user
                   secondNumber;            //second string entered by user
         int number1,                            //first number to add
              number2,                            //second number to add
              sum;                                    //sum of number1 and number2

        //read in first number from user as a string
        firstNumber = JOptionPane.showInputDialog("Enter first integer:");

        //read in second number from user as a string
        secondNumber = JOptionPane.showInputDialog("Enter second integer:");

        //convert numbers from type string to type int
        number1 = Integer.parseInt(firstNumber);
        number2 = Integer.parseInt(secondNumber);

        //add the numbers
        sum = number1 + number2;

        //display the results
        JOptionPane.showMessageDialog(null, "The sum is " + sum + ".", "Results", JOptionPane.PLAIN_MESSAGE);

        //terminate the program
        System.exit(0);
    }//end main method
}//end class

Methods That Return Values

The methods sayHappy( ) and greeting( ) in the HappyBirthday class are void methods.  They carry out a task but do not return a value.  There are many methods built into Java that return values, we have used some of them already.  You can also define a method such that it returns a value.  In the following program, the main method calls three other methods that return values and assigns the values returned to variables.  It then calls a fourth method to which it passes all the previous values for output.

/*The Return Values Program
*Programmed by Mr. Joy Augustine, January 2004
*This demonstrates methods that return values. This program asks the user to
*input the price of an object. The value is then sent to a second method that
*calculates the pst, another method that calculates the gst, and a method
*which then outputs the original price, the pst, the gst, and the final
*cost of the object.*/

import javax.swing.JOptionPane; //import class JOptionPane
import java.text.DecimalFormat;

public class ReturnValues{
    public static void main (String [] args){
        double mPrice = inputPrice();
        double mPST = calculatePST(mPrice);
        double mGST = calculateGST(mPrice);
        outputToScreen (mPrice, mPST, mGST);
    }//end main

    public static double inputPrice (){
        //this method gets the input
        String inputThePrice; //string value entered by user
        double price; //value to hold price after conversion

        //read in the price of the object from user as a string
        inputThePrice = JOptionPane.showInputDialog("Enter the price of the object:");
        //convert price from type string to type double
        price = Double.parseDouble(inputThePrice);
        //return the double value to the main method
        return price;
    }//end inputPrice method

    public static double calculatePST (double price){
        //this method calculates the PST
        double pst = price * .08;
        return pst;
    }//end calculatePST

    public static double calculateGST(double price){
        //this method calculates the GST
        double gst = price * .07;
        return gst;
    }//end calculateGST

    public static void outputToScreen(double price, double pst, double gst){
        double total = price + pst + gst;
        DecimalFormat precisionTwo = new DecimalFormat ("0.00");
        //display the results
        JOptionPane.showMessageDialog(null, "The price is: $" +
        precisionTwo.format(price) + "\n PST: $"+ precisionTwo.format(pst) +
        "\n GST: $" + precisionTwo.format(gst)+ "\n Total: $" +
        precisionTwo.format(total),"We calculated the taxes.", JOptionPane.PLAIN_MESSAGE);

        //terminate the program
        System.exit(0);
    }//end outputToScreen

}//end class
Hosted by www.Geocities.ws

1