Programming 1, fall 2007 -- Demonstration 2

Remember:The English exercise set (''demonstrations'') is a bit shortened from the Finnish version. The purpose is to support learning, and show the overall picture of what the Finnish students are doing during the fall. The course grade will be based on the exam only, but doing the exercises is recommended, as the exam is going to be exactly the same as the Finnish one, and based on the exercises of the course. (The only difference is that the questions are translated to English)

The second demonstration continues from where the first one left. Now you should be comfortable with all the tools seen this far:

You should be able to compile and run Java programs on some computer that you have frequent access to.

Next, we will strengthen the knowledge about some underlying concepts, most importantly the abstract concept of syntax (another word for this is grammar). We will start doing short programs that follow the syntax and conventions of Java. It is important to grasp everything well from the ground up, as the length and complexity of the programs to be produced will increase very fast in the future exercises.

Contents

Abstract syntax

Let us look at syntax (or grammar) for the second time. Go learn the concept of syntax diagrams (or "railroad diagrams") from somewhere. The following web resource is one good place to learn this:

http://cui.unige.ch/db-research/Enseignement/analyseinfo/JAVA/BNFindex.html

Start by viewing the "startrule" which is called CompilationUnit and explore how the syntax is built in layers or "symbols" (denoted by boxes) that expand (and expand and expand, recursively) until finally they arrive at the so called "terminal symbols" (denoted by round ellipses) which can be written as characters.

Try to understand how this scheme allows one sequence of characters to be valid according to the grammar, and one sequence to be invalid. A programming language (and many other places in computing) has a strictly defined abstract syntax which you must follow in order to produce a valid sequence of characters, for example a Java program.

Try to understand how the abstract concept and the diagrams relate to the plain text representation known as BNF (the "Backus Naur Form").

In most syntaxes, the number of valid character sequences is infinite. For example

Programming is the process of communicating your thoughts via the given syntax of your programming tool. You communicate to the compiler, for making a program that works, and runs on a computer. You also communicate to other programmers, and to yourself in the future. You need to be correct, and, in addition, you need to be clear in your representation of ideas in a formal language.

Exercise 1:

Using the BNF syntax, create a syntax that allows any mathematical expression consisting of positive integer numbers and the following operators:

+  for addition
-  for subtraction
*  for multiplication
/  for integer division

Integer numbers must allow any length of positive integers (we omit negative integers). The integer must not begin with the digit zero.

Go all the way through to terminal symbols '+', '-', '*', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ' ' (space character) in your syntax.

Examples of valid character sequences:

5 + 7

14 - 18

1 / 27318967 * 14   +     101023448 / 342 - 2

I expect you will begin expanding your syntax from something like the following BNF formulation:

Expression = Number WhiteSpace [Expression]

Then you need something in between, and you will finally have something like:

DigitNotZero = '9' | '9' | '9' | '9' | '9' | '9' | '9' | '9' | '9'

Exercise 2: Execution of expressions

The source code on its most detailed level, consists of Statements, which in turn may be composed of embedded Statements, and of Expressions. Expression is something that will have a definite numerical value after computation. Let us examine the following Java code:

public class EsimerkkiLausekkeesta{
    public static void main(String[] args){

        /* Beware the number systems and literal syntax: */

        int a = 000;
        int b = 006;
        int c = 016;
        int d = 106;
        int e = 0xe;

        int f = (a*b) + (a - (c+d) ) * (e + 0126);
    }
}

First thing to learn, of course, is the concept of variable, a storage place of a numerical value, with a name and a type. Learn the concept of variable, and of the assignment operator '=' in Java, and answer the following question:

When the last line, int f = (a*b) + (a - (c+d) ) * (e + 0126); is executed, what is the order of execution of the operators, and what are the numerical values for each of:

  • the left-hand operand of the operator being executed
  • the right-hand operand of the operator being executed
  • the result of the operation

There is an additional pitfall here! The literal 0126 does not have the value 126 as we understand the 10-digit number system!

First things to get going with Java: printing

In this demonstration, all our programs will be simple, and they will have exactly the following structure:

public class TheNameOfYourProgram {
    public static void main(String[] args){

        /* All that we do at first is written here. */

    }
}

Be certain that this is what you write each time, and that the name of your program begins with a capital letter. Be sure about indentation (it is 4 space characters per level of indentation), and start indenting so that the last curly brace } is on the same level as the line of code containing the corresponding left brace {.

We will gradually find out what all the words mean, but it is too much to be learned at once.

There are three convenient ways to print characters to the standard output in Java. They are (never mind if you don't yet understand what this means):

"the public instance methods print, println, and printf found in the interface of the class java.io.PrintStream whose instance is automatically created prior to activating main(), and always referenced to by the public static field out of the class java.lang.System"

You must understand that the above description, although precise, is too much for us to grasp at once! At this point, we will learn to do printing by imitating examples of use. We shall land on the concepts of reality, such as "class", "method", "instance", "reference", "field", "activation", and others, only gradually during the fall period. As you see, there are a lot of concepts waiting for us before we can be truly programming Java!

I give you the fundamental examples here, with comments:

public class TheNameOfYourProgram {
    public static void main(String[] args){

        /*prints characters:*/
        System.out.print("Characters you want printed");

        /*prints, and inserts a line break character:*/
        System.out.println("Characters you want printed");

        /*prints only the line break character:*/
        System.out.println();

        /*prints a "formatted character sequence":*/
        System.out.printf(
                "This is year %d, %nand temperature is %.4f degrees C.",
                2007, -13.0);

    }
}

Exercise 3:

Write a Java program that prints out, line by line, the plain text that you wrote about yourself in the previous exercise.

Exercise 4:

You can print out numerical values, and they are automatically converted to text when the printing happens.

Try using the Java language as a calculator. Make up calculations with divisions, multiplications, and so forth... Decide what you expect the program to output, then write, let us say, 15 or more lines of code that print the things. Like this:

System.out.printf("I expect 0.33 out of this: %.2f " 1/3);

System.out.println("Expect the following line to say 4:");
System.out.println( (9*2)/6+1 );

After each small change or addition, compile and run your program to validate that it works as you want it to.

If you have imagination and creativity, this exercise will teach you a great deal of how things work in Java. For example, the first line of the above may not be what you expect...

Write a Java program that prints out line by line, the plain text that you wrote about yourself in the previous exercise.

Exercise 5:

Variables, types, and assignments. Find out what all these mean in Java. There's no way to check your knowledge, other than the fact that next time we'll be using this knowledge to start really programming

Algorithms

Exercise 6:

Think about a phone directory, where the names of people are listed with their phone numbers.

  1. Devise an algorithm (i.e., instructions on how to perform a task) to locate the number of any given person from the phone book.
  2. Devise an algorithm to find out the person to whom a given number belongs to.

Which one of the algorithms works faster? How much faster do you expect? Why?