previous
 next 
CS 1063  Weeks 1 and 2:  Introduction to Java Programming 
Fall 2014: Sections 1 and 2

Objectives

Assignments

Outline

Setup
Algorithms
Your First Lab
Writing Simple Programs
Static Methods
Summary of Syntax

Setup

Logging in for the First Time

If you registered this course, you have your own account to access the computer in classroom and the CS Main labs.
Your account is your UTSA id abc123, and your password will be given in the first lecture.
When you log in for the first time you will be prompted to change your password.
Passwords must be at least 14 characters in length.
It is recommended that you use the same password as you use to access your UTSA account.
This will make it easier for you to remember.

If you did not see the login screen and need to re-start/re-boot the computer, be sure to select the VDI client 2.0.

When the class is over, be sure to exit VDI by clicking onthe X at the top of the screen.

Setting up ClassQue

Setting up Dr. Java

The following procedure will create a new Dr. Java shortcut on your desktop.

Download and run this script.


This shortcut will store the Dr. Java configuration files on the V drive so that they are remembered each time you log in.
It also creates the following directories: It is recommended that the programs written in class be stored in the V:\drjava\lectures directory.

When you start Dr. Java, use this icon: Dr. Java icon instead of Dr. Java icon
Today's News: August 29
Lab 0 is due on Tuesday of next week.
There are special requirements for turning in Lab 0. See below.

Special requirements for turning in Lab 0

In addition to turning in your Lab 0 on blackboard, do the following:

Your First Program: HelloWorld

These instructions assume that you are using a development environment called DrJava.
This program will be discussed in more detail below.  Here are more detailed instructions for running DrJava.  You can also install DrJava on your own computer.

Your First Quiz

All the quizzes will be available on Thursday, Friday, and Saturday of most weeks.  (Always check your calendar.)  That means you will have 3 days to complete the quiz.  The first quiz might be taken together in class if there is time, but from then on the student is responsible for taking the quiz on their own.  One of the goals of the quizzes is for students to read the textbook, so you should not be surprised that you cannot find the information in the lecture notes or that some topic has not been covered in class.

Blackboard can be entered using the following link: http://learn.utsa.edu.  You need to allow popup windows from learn.utsa.edu and utsa.blackboard.com.  If you see a window asking permission to run an application with Publisher dc.blackboard.com and From https://utsa.blackboard.com, click Run.

Algorithms

An algorithm is a step-by-step description of how to accomplish a task.  To get an idea for algorithmic thinking, and to learn a little bit about how computers work, consider an algorithm for the following task:
Convert a binary number to a decimal number.


Naturally, one of the first questions that should be asked is: What is a binary number?  A binary number is a base-2 number, and is composed of just 0s and 1s (called bits).  Almost everything that is digital (such as data on computers, the internet, and DVDs) is represented by binary numbers.  The following table shows the correspondence from zero through nine to binary.

Decimal     Binary
0 0
1 1
2 10
3 11
4 100
5 101
6 110
7 111
8 1000
9 1001

Each place in a binary number corresponds to a power of two: 1, 2, 4, 8, 16, 32, etc.  For example, going from right to left, the binary number 10110 has:
Adding up the places where there is a 1 results in 2 + 4 + 16 = 22. Here are more examples:
Hopefully, this explanation gives you a good idea of how to convert a binary number to a decimal number.  To become an algorithm, we need to describe how to do the task one step at a time (one bit at time, adding one number at a time, how to start, when to stop, etc.).  Notice there are three things to keep track of: a bit in the binary number, a sum for the decimal number, and a power of two.  Here is one algorithm that does that.
Algorithm for converting a binary number to a decimal number
  1. Let 1 be the current power of two.
  2. Let 0 be the sum.
  3. Consider the bits in the binary number going from right to left.
  4. Obtain the next bit.
  5. If the bit is 1, add the current power of two to the sum; otherwise, do not change the sum.
  6. Multiply the current power of two by 2.
  7. If there are more more bits to process, go back to Step 4.
  8. If there are no more more bits to process, the sum is the decimal number we want as a result.

If this algorithm is applied to the binary number 110, this is what is supposed to happen:
Running the algorithm on the binary number 110
1.  The current power of two becomes 1.
2.The sum becomes 0.
3.Consider the bits in 110 starting with the 0 on the right.
4.The next bit is 0.
5.The bit is not 1, so the sum does not change (remains at 0).
6.The current power of two becomes 2.
7.There are more bits to process, so go back to step 4.
4.The next bit is 1.
5.The bit is 1, so the current power of two (2) is added to sum, which becomes 2.
6.The current power of two becomes 4.
7.There is another bit to process, so go back to step 4.
4.The next bit is 1.
5.The bit is 1, so the current power of two (4) is added to sum, which becomes 6.
6.The current power of two becomes 8.
7.There are no more bits to process.
8.6 (the sum) is the result of the algorithm.
Activity: Follow the steps of this algorithm for other binary numbers.

Developing any algorithm for a computer has the same issues.  What are the elements of the task and what do they mean?  How can these elements be manipulated one step at a time?  How can a combination of steps be arranged to create an algorithm that solves the task?  Does the algorithm work on a variety of examples?  Can the algorithm be justified by a careful argument?

A computer scientist always thinks of other issues that were not considered.  What about negative numbers?  What about fractions?  What if the binary number is written down in a nonstandard way, such as several zeroes at the beginning?  Worrying about where things might go wrong is standard practice in computer science.
Activity: Develop an algorithm to count the number of 1s in a binary number.  Process the binary number one bit at a time.

Activity: Develop an algorithm to determine if a binary number has more 1 bits than 0 bits.  Process the binary number one bit at a time.

Challenge: Develop an algorithm to add one to (or subtract one from) a binary number.

Today's News: September 3
Lab 0 hard copy due in class today.
Find out about using VDI at home here.
Seats available in Section 1: 47 50 55
Seats available in Section 2: 33 44 46 55
New section of CS 1063: Section 6, TR 8:30

Writing Simple Programs

In computer science, we write programs (instructions for computers) to implement algorithms.  Fortunately, we don't have to write our programs as binary numbers or machine code (ask any old-enough programmer), but we can use a modern programming language like Java.  Also, programmers use development environments to help them write programs.  In these notes, we will assume that you are using a development environment called DrJava.

Open your HelloWorld program in DrJava.  If you can't find it, you can always create another one.
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}


Even a simple Java program like HelloWorld consists of several parts that fit together like a jigsaw puzzle.

Class

Every Java program is implemented by a class.  A class corresponds to a .java file on your computer.  For example, the HelloWorld class should be in the HelloWorld.java file.
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

Main Method

Every Java program contains a class with a main method.  When the program starts, the instructions in the main method are executed.
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

Statements

Instructions or statements in the body of the main method (statements between { }) are executed one at a time.  Each statement ends in a semicolon (;).  Notice that our main method has only one statement.
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You can add as many System.out.println statements as you want in the main method.  For example, add the following statements inside the main method, and then compile and run your program.
System.out.println( );
System.out.println("Take me to your leader!");

Strings

A string is a sequence of characters.
It is often represented enclosed in quotation marks.

System.out.println prints a string and then starts a new line.  If there is no string between the parentheses, it just prints a newline.

System.out.print prints a string, but does not start a new line.  For example, the following two statements will print the two strings on one line.
System.out.print("I'm sorry Dave.");
System.out.print("I'm afraid I can't do that.");

If you want to include a " in your string, use the \" escape sequence in the string.  Other escape sequences include \n to include a newline, \t to include a tab, and \\ to include a \.
System.out.println("\"I'm sorry Dave.\n I'm afraid I can't do that.\"");
System.out.println("\t\t\t\\Hal/");
Activity: Add the statements to your HelloWorld file and run it again.

Printing 1

Comments

Comments are used to explain the program to other programmers or to yourself.  Any text enclosed between // and the end of the line is completely ignored by the compiler. For example, this comment could be added to the HelloWorld program before the first println statement.
// display a greeting in the console pane

The compiler also ignores any text between a /* and */  If you have a comment that is longer than one line, then the /*  . . . */ comment is simpler.  For example:
/* This is a simple Java program
   It will print a greeting to the console
*/
Activity: Add the comments to your HelloWorld file and run again.  Was there any change?

Readability

In Java, you can add or remove spaces and newlines as long as there is at least one space (or other punctuation) between words.  For example, the HelloWorld class could have been written like:
public class HelloWorld{public static
void                                     main
(String[]args){                          System
.     out     .                          println
("Hello World!");}}

However, you should follow the conventions given and illustrated in the book.  Making your program unreadable (obfuscation) will result in points taken off.  Here are a few guidelines.

Errors

Much of your programming time will be occupied by debugging, finding and fixing bugs, which are errors in your program.

A syntax error indicates an ill-formed program.  Part of the job of the compiler is to detect and list all of your syntax errors.  Compilers are good at finding syntax errors, but usually provide lousy error messages.  A lot of the time you will need to figure out what is wrong at (or around) the location of the error given by the compiler.  Common syntax errors include misspelled words, improper capitalization, missing semicolons, incorrect punctuation, and mismatched parentheses or braces.

A program has a logic error if it doesn't perform the task correctly when it is executed.  For example, this statement in the HelloWorld program would be incorrect because it doesn't print the right message.
System.out.println("Hollow wood?");

A runtime error is a logic error that Java detects while your program is running.  When this happens, your program will crash.  Examples of runtime errors include division by zero and trying to access the 10th character of a string that only has 5 characters.
Activity: Write a program named SpellingChequer to print the following:
Eye halve a spelling chequer
It came with my pea sea
It plainly marques four my revue
Miss steaks eye kin knot sea.

Activity: Write a program named Diamond to print the following:
   **
  ****
 ******
 ******
  ****
   **

Activity: Write a program named QuotesAndSlashes to print the following:
   /\
  /""\
 /""""\
 \""""/
  \""/
   \/

Program Progress 2

Your First Lab

The labs will be due by Tuesday of most weeks.  (Always check your calendar.)  Generally, that means you start programming and ask questions during one week, and finish the program and upload to Blackboard at the beginning of the next week.  You may collaborate on the labs, but copying is cheating.
Today's News: September 5
Lab 0 hard copy due in class today.
Seats available in Section 1: see me
Seats available in Section 2: 44 55

Using Static Methods

Consider writing a program to print out the lyrics of "Old MacDonald Had a Farm" (a variation of these lyrics).  We could write a class that prints each line in a main method.
public class OldMacDonald {
    public static void main(String[] args) {
        // print title
        System.out.println("Old MacDonald Had a Farm");
        System.out.println( );

        // print first verse
        System.out.println("Old Macdonald had a farm, E-I-E-I-O");
        System.out.println("And on his farm he had a cow, E-I-E-I-O");
        System.out.println("With a moo-moo here and a moo-moo there");
        System.out.println("Here a moo there a moo");
        System.out.println("Everywhere a moo-moo");
        System.out.println("Old Macdonald had a farm, E-I-E-I-O");
        System.out.println( );

        // print second and third verses (not done yet)
    }
}

However, there is some redundancy, and the program does not reflect the structure of the song, which makes the program more difficult to understand and maintain.  We can apply procedural decomposition to identify common subtasks and to separate the overall task into several subtasks.  Then, each subtask can be implemented with a static method.

Common Subtask

An example of a common subtask is the "Old Macdonald had a farm, E-I-E-I-O" line, which appears several times in the song.  We can write a static method that just prints this one line.  This method is named oldMacLine.
// This method prints the Old Macdonald line
public static void oldMacLine( ) {
    System.out.println("Old Macdonald had a farm, E-I-E-I-O");
}

Then, we can rewrite the main method to call the oldMacLine method to print this line as needed.  Note that the new method is included in the class.
public class OldMacDonald {
    public static void main(String[] args) {
        // print title
        System.out.println("Old MacDonald Had a Farm");
        System.out.println( );

        // print first verse with method calls
        oldMacLine( );
        System.out.println("And on his farm he had a cow, E-I-E-I-O");
        System.out.println("With a moo-moo here and a moo-moo there");
        System.out.println("Here a moo there a moo");
        System.out.println("Everywhere a moo-moo");
        oldMacLine( );
        System.out.println( );

        // print second and third verses (not done yet)
    }

    // This method prints the Old Macdonald line
    public static void oldMacLine( ) {
        System.out.println("Old Macdonald had a farm, E-I-E-I-O");
    }
}

Separating a Task into Subtasks

An example of separating the overall task into subtasks is separating the song into the title and its verses.  That is, we might have the following algorithm in mind.
  1. Print the title.
  2. Print the first verse.
  3. Print the second verse.
  4. Print the third verse.

We could write a separate method for the title and each verse.  Here is a method for the first verse, appropriately named firstVerse.
// This method prints the first verse of Old MacDonald
public static void firstVerse( ) {
    oldMacLine( );
    System.out.println("And on his farm he had a cow, E-I-E-I-O");
    System.out.println("With a moo-moo here and a moo-moo there");
    System.out.println("Here a moo there a moo");
    System.out.println("Everywhere a moo-moo");
    oldMacLine( );
    System.out.println( );
}

We can rewrite the main method to call the firstVerse method.  Note again that the new method is included in the class.  Programming by adding one method at a time and rewriting to call the new method is known as iterative enhancement or stepwise refinement.
public class OldMacDonald {
    public static void main(String[] args) {
        // print title
        System.out.println("Old MacDonald Had a Farm");
        System.out.println( );

        // print first verse with a method call
        firstVerse( );

        // print second and third verses (not done yet)
    }

    // This method prints the Old Macdonald line
    public static void oldMacLine( ) {
        System.out.println("Old Macdonald had a farm, E-I-E-I-O");
    }

    // This method prints the first verse of Old MacDonald
    public static void firstVerse( ) {
	oldMacLine( );
	System.out.println("And on his farm he had a cow, E-I-E-I-O");
	System.out.println("With a moo-moo here and a moo-moo there");
	System.out.println("Here a moo there a moo");
	System.out.println("Everywhere a moo-moo");
	oldMacLine( );
        System.out.println( );
    }
}

The order that the three methods are listed in the class do not matter.  The flow of control will proceed by first executing the statements in the main method.  When a statement calls another method (a method call), the statements in that method will be executed from start to finish, and then control will return to the method call.
Activity: Revise the OldMacDonald program so that the main method also calls a method named title to print the title.

Old MacDonald 1

Activity: Revise the OldMacDonald program so that the main method, in addition to calling title, also calls secondVerse and thirdVerse.  Also, identify another common subtask and write a method for it.

Summary of Syntax

The syntax for a class is:
public class ClassName {
    method(s)
}

A class with name ClassName should be saved in ClassName.java.

The syntax for the main method is:
public static void main(String[ ] args) {
    statement(s)
}


The syntax for other static methods is:
public static void methodName( ) {
    statement(s)
}

The syntax for various print statements is:
System.out.println(string);
System.out.print(string);
System.out.println( );

The first println statement prints the string followed by a newline.  The print statement prints the string without any newline.  The last println statement just prints a newline.  A string is a sequence of characters between quotation marks (").

The syntax for a method call statement is:
methodName( );

A method call executes the statements in the method and returns control to the next statement (if any) after the method call.
 next notes
 next notes