2: Programming Basics

What We Will Cover


Continuations

Homework Questions?

Questions from last class?

Quiz

2.1: Elements of a Java Program

Objectives

At the end of the lesson the student will be able to:

  • Write comments in programs
  • Identify statements in programs
  • Code classes and main() methods
  • Explain the rules for creating an identifier

2.1.1: Example Program

  • Here is the example program like the one we looked at before
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    /**
     * Hello.java
     * Purpose: Prints a message to the screen.
     *
     * @author Ed Parrish
     * @version 1.0 8/30/05
     */
    public class Hello {
        public static void main(String[] args) {
            System.out.println("Hello, world!");
        } // end of main method
    } // end of Hello class
    

Brief Explanation by Line Number

  • Lines 1-7: comments -- notes to programmers
  • Line 8: the class declaration
  • Line 9: the main() method where all programs start
  • Line 10: a programming statements that gives instructions to the computer
  • Line 11: the end of the main() method followed by another comment
  • Line 12: the end of the Hello class followed by another comment

2.1.2: Comments

  • Comments are ... comments -- notes to people reading the code
  • Comments are ignored by compiler
  • You use comments to document program blocks and describe unusual code
  • Comments can start with // and last to end of the line
  • // this is a comment
  • Comments can span multiple lines: /* ... */
  • /* This is a multi-line comment
          which can be split
       over many lines or a portion of one line. */
    

Programming Style: Block Comments

  • Block comments are the main way to document your code
  • Use block comments like the following just before the class declaration
  • /**
     * CS-12J Asn 3
     * HelloWorld.java
     * Purpose: Prints a message to the screen.
     *
     * @author Jane User
     * @version 1.0 8/20/03
     */
    

2.1.3: Statements

  • Statements direct the operation of the program
  • Most statements end in a semicolon (;)
  • System.out.println("Hello, world!");
  • However, statements requiring a set of braces {} end with the right brace
  • public static void main(String[] args) {
        System.out.println("Hello, world!");
    }
    
  • Note that we can have multiple statements within a pair of curly braces

Whitespace

  • Whitespace: blank lines, spaces, and tabs
  • Whitespace is ignored by compiler
  • Use whitespace to make programs more readable

Programming Style: Line Length

  • Limit your line length to 80 characters
  • Longer lines can cause problems with many text editors and other tools

2.1.4: Declaring Classes

  • When you develop a Java program, you code one or more classes for it
  • Each class starts with a declaration like the following:
  • public class Hello {
        // class definition goes here
    }
    
  • Keyword public means all parts of the program can use this class
  • Keyword class tells the compiler that a class is being defined
  • A left brace { begins body of every class
  • Likewise, a right brace } ends body of every class
  • Any code between the curly braces is called the class definition

Naming Conventions

  • Always start the name of a class with a capital letter
  • Use letters and digits only (no underscores)

Source Code Files and Classes

  • The file name must be same as the class name, with a .java suffix added
    • Capitalization matters!
  • Each file must contain one and only one public class

2.1.5: Declaring a main() Method

  • Method - a block of code that performs a task
  • Every Java program has one or more methods
  • Methods are called functions in some other programming languages
  • Every Java application has a main() method that is declared like this:
  • public static void main(String[] args) {
        // method definition goes here
    }
    
  • Applications begin executing at the main() method
  • Keyword public allows any program to use the main method in this class
  • void means main has no return value
  • args is a parameter name of type String[] -- cover later
  • For now, mimic the first line of main

Blocks

  • Java is known as a block-structured language
  • This means that most source code is contained within pairs of matching delimiters
  • Java uses curly braces { } as delimiters for code blocks
  • Left brace { begins body of every function
  • Right brace } ends body of every function
  • All methods have associated blocks
  • However, as we have seen already, you can use blocks other places as well

2.1.6: Identifiers

    Identifier - the name of a variable, procedure, class or other programming construct.

  • Purpose of an identifier is to provide a name for something
  • Programmers create identifiers for the names of many things in a program:
    • variables
    • methods
    • files
    • classes
  • Identifiers are made up of a sequence of characters
  • Each character can be a:
    • Letter
    • Digit
    • Connecting punctuation (e.g. underscore _)
    • Currency symbol (e.g. $, ¢, £, ¥)
  • Can not start with a digit
  • Can not contain any periods or spaces
  • Can not be a keyword (e.g. "if, "for", etc.: see Java Language Keywords)
  • Are cAsE sEnSiTiVe!
    • id, ID, iD and Id are all valid but different identifiers
  • Programming style: identifiers have naming conventions

Keywords

  • Keywords are reserved words with predefined meanings
  • We used keywords in our Hello program
    • public
    • class
    • static
    • void
    /**
     * Hello.java
     * Purpose: Prints a message to the screen.
     *
     * @author Ed Parrish
     * @version 1.0 8/30/05
     */
    public class Hello {
        public static void main(String[] args) {
            System.out.println("Hello, world!");
        } // end of main method
    } // end of Hello class
    
  • All keywords have special meaning in Java
    • Can only be used for their specified purpose
    • Attempting to use for any other purpose will generate a compiler error
    • Thus cannot use keywords as identifiers
  • For a current list, see Java Language Keywords
  • Note that the entire language has only 50 keywords
  • Part of learning a language is learning what the words mean

2.1.7: Compiling and Running a Program Using TextPad

  • Many text editors have provision for compiling within the editor
  • We use TextPad in our class room as a text editor
  • Note that you can install TextPad at home
  • To make your in-class exercises easier, we have set up TextPad to compile and run C++ programs
  • We will use the following program for demonstration
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    /**
     * Hello.java
     * Purpose: Prints a message to the screen.
     *
     * @author Ed Parrish
     * @version 1.0 8/30/05
     */
    public class Hello {
        public static void main(String[] args) {
            System.out.println("Hello, world!");
        } // end of main method
    } // end of Hello class
    

Compiling with TextPad

  1. Load your source code into the active TextPad window
  2. Select the Tools menu
  3. Select Compile Java
  4. If there are any syntax errors, you will see a page showing them
  5. Otherwise, you will return to your source code page

Running Programs with TextPad

  1. Load your source code into the active TextPad window
  2. Select the Tools menu
  3. Select Run Java Application
  4. Your program will run in a console window

2.1.8: Summary

  • Comments help document what a program does
    • Useful for humans to read
  • Java has three styles of comments
    • //
    • /* ... */
    • /** ... */
  • You develop Java programs writing one or more classes
  • Every Java application starts with a main method
  • Statements direct what a program does
  • Identifiers are any name you create in a Java program
  • Keywords are words with a special meaning and are reserved by Java
    • Cannot use a keyword as an identifier
  • To make your testing and debugging easier, we have set up TextPad to compile and run Java programs

Check Yourself

  1. What styles of comments are allowed in Java?
  2. What code do you write for a main() method?
  3. How can you tell which lines are program statements?
  4. What are the rules for creating an identifier?

Exercise 2.1

With no more than a single partner, take 5 minutes to complete the following:

  1. Start a text file named exercise2.txt.
  2. Prepare the exercise header as described in the HowTo on submitting exercises
  3. Label this exercise: Exercise 2.1
  4. Submit all exercises for this lesson in one file unless instructed otherwise
  5. Complete the following and record the answers to any questions in exercise2.txt.

Exercises and Questions

  1. Start your text editor and enter the following code:
  2. 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    /**
     * Hello.java
     * Purpose: Prints a message to the screen.
     *
     * @author Ed Parrish
     * @version 1.0 8/30/05
     */
    public class Hello {
        public static void main(String[] args) {
            System.out.println("Hello, world!");
        } // end of main method
    } // end of Hello class
    
  3. Save the file as "Hello.java".
  4. Q1: Which words are the identifiers? (Please list them)

  5. Compile and execute the code.
  6. Q2: Which lines of code start a statement? How can you tell?

  7. Remove the block comment and then recompile and execute the code
  8. Q3: Does a block comment affect the execution of the code?

  9. Remove the word "static" from the program then recompile and run the code.
  10. Q4: What error message does the compiler report?

2.2: Memory Concepts

Objectives

At the end of the lesson the student will be able to:

  • Describe how to store data in a program
  • Write code for declaring variables and assigning them values
  • Write code for declaring constants and assigning them values

2.2.1: Computer Memory

  • Recall that a computer has five main parts
  • One of these is the main memory

Main Memory

  • Main memory is organized as a long list of memory locations
  • Each memory location contains zeros and ones
  • The contents of a memory location can change while a program runs
  • The smallest unit of memory is the Binary Digit or bit
  • A bit that can only be zero or one

Memory Location

  • Each memory location has eight bits, which are know as a byte
  • The memory address is the number that identifies a memory location
  • Some data is too large for a single byte
  • For instance, most numbers are too large for one byte
  • In these cases, the address refers to the first byte
  • The next few consecutive bytes store the additional bits for larger data

More Information

2.2.2: Memory Addresses and Variables

  • Computer data is stored in and retrieved from main memory
  • Before high-level languages, memory was referred to by its address
  • Storing integers 45 and 12 would allocate memory like the following
  • Quickly becomes cumbersome to write such programs
    • Have to manually keep track of each location
    • Have to make sure locations do not overlap
  • Easier to assign each variable a name
    • Let the computer remember the address and size of the memory
  • Then each memory location can be referred to by a name
  • These named locations are call variables
    • Because the data in them can vary (change)

  • Now our programs can look like the following:
  • num1 = 45;
    num2 = 12;
    total = num1 + num2;
    

2.2.3: Data Types

  • Main memory stores data while a program is running
  • The data is stored in memory locations named by variables
  • The letter 'A’ may look like: 01000001
  • The number 65 may look like: 01000001
  • How does the computer know the meaning of 01000001?
  • Interpretation depends on the data type of the variable

Primitive Data Types

  • A data type tells your computer program how to interpret data
    • Specifies how many bytes are needed to store the data
    • Tells the computer the format in which the data is saved
  • There are four general categories of primitive data types:
  • General Type Explanation Examples
    Integer Numbers without decimal points 123, -987
    Floating-Point Numbers with decimal points 1.23, -0.01
    Character Single letters, digits and special symbols 'A', '9'
    Boolean Logical values true or false true, false

  • These data types are called primitive types because the data is stored directly in a memory location
  • Later we will work with advanced types that store data at a memory location referred to by a variable

Java's Primitive Types

Type Name Category Bytes Use
byte integer 1 Very short integers from -128 to 127
short integer 2 Short integers from -32,768 to 32,767
int integer 4 Integers from -2,147,483,648 to 2,147,483,647
long integer 8 Long integers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float floating point 4 Single-precision, floating-point numbers from ±3.4E38 to ±7.1E-46F with 6 or 7 significant digits.
double floating point 8 Double-precision, floating-point numbers from ±1.7E308 to ±2.5E-324 with from 14 to 15 significant digits.
char single character (Unicode) 2 A single Unicode character that is stored in two bytes.
boolean true or false 1 A true or false value.

  • Note that the number of bytes used for storage is the same on all computers

2.2.4: Declaring Variables

  • All program variables must be declared before using them
  • A declaration statement both names a variable and specifies the data type it can store
  • The data type specifies the size and format of the data
  • General syntax:
  • dataType VariableName1, VariableName2, ...;
    
  • For example:
  • int num1, num2, total;
    long dateNum;
    float firstNum;
    double secNum;
    char letter;
    
  • When variables are declared, the computer allocates storage space
  • The contents of the storage space can be undefined until a value is assigned
  • For instance, after we declare the following variable, what is its value?
  • char letter;
    

Programming Style: Variable Naming Conventions

  • Use meaningful names that are easy to remember as you code
  • Start variable names with a lowercase letter
  • Capitalize the first letter in all words after the first word

2.2.5: Assigning Values to Variables

  • After you declare a variable, you must assign it a value
  • Use the assignment operator "equals sign" (=)
  • variable = expression;
  • Assigns value of expression (right side) to the variable (left side)
  • The simplest expression is a literal value:
  • length = 25;
    width = 17.5;
    
  • In each statement, the value on right is assigned to the variable on the left
  • Also, you can assign results of more complex expressions to a variable
  • total = num1 + num2;
    slope = (y2 - y1) / (x2 - x1);
    
  • Reading variables from memory does not change them
  • Values placed into a variable replace (overwrite) previous values

Assigning Initial Values to Variables

  • Initial values may or may not be assigned when variables are declared:
  • // These are not initialized when declared
    // and have unknown values
    int sum, number1, number2;
    
    // These are initialized when declared
    int sum = 0;
    int number1 = 5, number2 = 10;
    
  • Good programming practice: initialize variables when declared

Constant Variables

  • A constant variable (or constant) is a variable that cannot change after being assigned a value
  • Sounds oxymoronic, but is actually quite useful
  • To declare a constant, use the keyword: final
  • final int MY_CONST = 1;
  • Note that you must assign a value when the constant is declared
  • Also note that the name is all uppercase letters with an underscore separator
  • This is a common coding convention that you must follow

2.2.6: Summary

  • Computers store data and code in main memory
  • Variables are how you can store data in your programs
  • Variables can be assigned new values while your program executes
  • Constants are a variable that cannot change after it is first assigned a value
  • Variables and constants must be declared before use.
  • To initialize a variable or constant, declare a name and assign a value.
  • Simple assignment statements have a variable, equals sign and an expression.
  • variable = expression;
  • The expression is computed before the assignment

Check Yourself

  1. How do you store data in a program
  2. What is the purpose of a data type?
  3. What is the code to declare an int variable named foo and assign it a value of 10?
  4. What is the code to declare a constant double named BIG_NUM and assign it a value of 100,000?

Exercise 2.2

  1. Complete the following program and submit the program along with exercise2.txt.
  2. Name the program file: AssignAndPrint.java
  3. Note: this is a separate file to submit along with your other exercises for this week. Do NOT copy the code into exercise2.txt.

Specifications

  1. Copy the following program into a text editor, save it as AssignAndPrint.java, and then compile and run it
  2. If you have difficulty, ask another student or the instructor for help.

    public class AssignAndPrint {
        public static void main(String[] args) {
            // add code here
        }
    }
    
  3. Add code in main() to declare an int variable named foo and assign it a value of 10.
  4. Add code to display the value of the variable foo.
  5. Compile and run your modified problem.
  6. If you have difficulty, ask another student or the instructor for help.

Wrap Up

Home | WebCT | Announcements | Schedule | Expectations | Course info
Help | FAQ's | HowTo's | Links

Last Updated: October 09 2005 @20:21:11