Course Links

Exercises

Resources

External

The purpose of this lab is to get you started writing programs in Java. Before doing this lab, you should make sure that you have completed Lab 0, which covers details on setting up your account and submitting your work.

Variable Types

Consider the following piece of Python script. Admittedly, the program doesn't do much, but its simplicity makes it a good testbed for learning about the structure of a language. We will convert this program into Java step by step.

# Sample program to demonstrate variable types
def main():
  # ask user for a number
  n = input("Please enter an integer: ")

  # double the number
  ndoubled = n+n
  print n, "doubled is", ndoubled

  # square of number
  nsquared = n*n
  print n, "squared is", nsquared

  # square root of number
  nsqrt = n**(0.5)
  print "The square root of", n, "is", nsqrt

The first step is to put in the boilerplate that should appear in every Java program: a main() method enclosed within a class. We will also add Javadoc comments at the top of the file. This step should be entirely automatic, with the exception of choosing a sensible name for our class and writing the comments. The result should look something like this:

/**
 *  Sample program to demonstrate variable types
 *
 *  @author Nicholas R. Howe
 *  @version 3 September 2013
 */
class NumberFacts {
    /**
     *  Get a number from the user and display facts about it
     *
     *  @param args  Command line arguments
     */
    public static void main(String[] args) {
        // insides not yet written
    }
}	

This may seem like an awful lot of code considering that the equivalent in Python is a mere two lines. This will be a recurring theme as you start to learn Java. However, the good news is that a lot of the complications that appear either will make your programs more efficient or will prove useful as your programs become more complex. In any case, we are not done yet. It turns out that capturing user input from the keyboard is also more complicated than in Python. To do it, we must import a Java library module with a class called Scanner, create an instance of this class to handle the input (called input below), and ask it for an integer. (Note that we're not worrying yet about what happens if the user types letters instead of numbers as input!)

import java.util.*;
 
/**
 *  Sample program to demonstrate variable types
 *
 *  @author Nicholas R. Howe
 *  @version 3 September 2013
 */
class NumberFacts {
    /**
     *  Get a number from the user and display facts about it
     *
     *  @param args  Command line arguments
     */
    public static void main(String[] args) {
        // ask user for a number
        System.out.print("Please enter an integer: ");
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
 
        // remainder not yet written
    }
}

The above may seem somewhat mysterious, but without it we can't really set up a working interactive program. Now we can turn to our original intent: looking at variable declarations. Every time you introduce a variable in Java you will need to declare its type before you put it to use. You can see an example in the program above. The line that gives n its initial value also declares its type (int). Let's do a similar thing for the next section, which introduces another variable, ndoubled.

	// double of number
	int ndoubled = n+n;
	System.out.println(n+" doubled is "+ndoubled);

Let's point out a few more differences from Python here: All the lines end in semicolons, and the comment symbol has changed. The command that prints messages to the terminal has a different name, and pieces of output to be assembled are combined using + instead of being separated by commas. Also Java needs extra inserted spaces in the text because it does not automatically insert them.

If you understand the example above, you should be able to do the next two (squared and square root). Keep in mind that the square root may not be an integer, so its variable should be declared as type double. Also, Java does not have an exponentiation operator (**) like Python; the square root is instead implemented as a method of the predefined Math object, as in: Math.sqrt(n).

Here is the full python program we want to translate: NumberFacts.py. Continue expanding your program to do the two division by 7 examples. The compiler will complain if you try to do something unclear or potentially dangerous. Can you declare a variable with the same name twice? Can you change the type of a variable once it has been declared? You will have to think ahead to choose a good type for ndiv7.

Functions and their Arguments

The last part of this example works with method declarations and their arguments, all of which include types. The method must specify its return type, i.e., the type of the value it passes back, and the types of all the arguments passed in. Here is an example of the prime() function translated to a Java method:

    /**
     *  Tests whether an integer is prime
     *
     *  @param n  The number to test
     */
    public static boolean prime(int n) {
        boolean isPrime = true;
        for (int i = 2; i < n; i++) {
            if (n%i == 0) {
                isPrime = false;
            }
        }
        return isPrime;
    }

Setting aside the public static portion for the moment (more will be said on these next week), the method declaration says that prime() returns a boolean value (e.g., true or false). It also accepts one input argument, which must be an int. The body of the function is delineated with curly braces and includes examples of a for loop and an if statement. (Note that the variable i in the for loop is declared as an int. Also note that the % operator returns the remainder of an integer division, so (11 % 3) has the value 2.)

So how would you use the above function in a program? You would do something like the following:

if (prime(n)) {
    System.out.println(n+" is prime.");
} else {
    System.out.println(n+" is not prime.");
}

To Do: Using the above as an example, write and call a similar function to test whether the number is even. Note that this task is simpler and will not require use of a loop.

Arrays

Java has eight primitive types: int, float, double, boolean, char, byte, short, and long. You may also declare variables that will hold some class of object, or an array of some type. Not only must these be declared accordingly, but before the individual elements of an array may be used the correct storage must be allocated via the new keyword. This example shows how:

  float[] numbers = new float[6];  // declare an array of float, and also allocate storage for six elements.

You might want to give all the elements of the array some starting value. (This is called initializing.) Here's a simple loop in Java that will do that. The loop syntax is fairly complex, but for now we'll just be using it in this standard form to go through an array element by element. As the loop runs, the loop index i will take each of the valid array indices as value.

for (int i = 0; i < numbers.length; i++) {
  numbers[i] = 17;  // arbitrarily set all array elements to 17
}

To Do: Create an array with space to hold ten int values. Then, using a loop, fill in as values the multiples from 0 to 9 of the original number entered by the user. Below appears the equivalent Python code. (Note: the Python code actually uses a list instead of an array, which is a very different datatype internally, but for now we will ignore these differences.) If you wish, you may tell your program to print out the multiples, but this part is optional.

  # multiples
  multiples = [None]*10
  for i in range(0,9):
    multiples[i] = i*n

Strings

Strings in Java are not primitive types because they require variable-size storage, but in many ways they behave in the same manner. (The S on String is capitalized, as are other class names, to distinguish it from the eight primitive types.) Strings do not normally require the use of new -- instead they can be allocated automatically by assigning them a string constant as value, or by a computation that produces a String result..

  String first_name = "Nick";     // create a string containing a name
  String last_name = "Howe";      // create a second string
  String name = first_name+" "+last_name;  
    // create a third string that combines the first two with a space between

Most of the string methods you may have used in Python have their counterparts in Java. However, the syntax for calling them is slightly different. Python would replace parts of a string called sentence using something like the following: string.replace(sentence,"will","did"). In Java, replace is a method that is applied to the sentence object itself: sentence.replace("will","did"). It returns a new String with the requested replacement, leaving the original value of sentenceuntouched.

To Do: Create an array with space to hold eleven String values. Then fill in the number names from zero to ten as their values. (Do this individually, not as a loop.) To check that everything worked right, you can write a loop to print out the values one to a line.

  numbers = [None]*11
  numbers[0] = "zero"
  numbers[1] = "one"
  # etc...

To turn in

You should submit the following files as lab1:

If you finish this lab with time to spare, you should start on the first programming assignment.