2: Basic Coding Skills

What We Will Cover


Continuations

Homework Questions?

Questions from last class?

  • What to do when WebCT has problems
  • How does the Java Virtual Machine (JVM) help Java achieve platform independence?

    1. Interprets the source code.
    2. Interprets the bytecodes.
    3. Interprets the virtual code.
    4. Interprets the machine code.

2.1: Starting Out

Objectives

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

  • Write appropriate comments in programs
  • List the rules for creating an identifier
  • Identify statements in programs
  • Code classes and main methods

2.1.1: Comments

  • Comments are ... comments -- notes to people reading the code
  • Comments ignored by compiler
  • Use comments to document and describe 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

  • Use block comments like the following at the start of a program file
  • /**
     * CS-12J Asn 3
     * HelloWorld.java
     * Purpose: Prints a message to the screen.
     *
     * @author Jane User
     * @version 1.0 8/20/03
     */
    

2.1.2: 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

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.3: 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 HelloWorld program
    • public
    • class
    • static
    • void
    public class HelloWorld {
         public static void main(String[] args) {
            System.out.println("Hello, world!");
        }
    }
    
  • 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 less than 50 keywords
  • Part of learning a language is learning what the words mean

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 HelloWorld {
        // class definition goes here
    }
    
  • Keyword public means all parts of the program can use this class
  • Keyword class tells compiler that a class is being defined
  • Left brace { begins body of every class
  • Likewise, 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)
  • Otherwise, follow the rules for naming an identifier

Source Code Files and Classes

  • File name must be same as the class name, with .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
  • Similar to functions in 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
  • Left brace { begins body of every method
  • Right brace } ends body of every method

2.1.6: Summary

  • Comments help document what a program does
    • Useful for humans to read
  • Java has three styles of comments
    • //
    • /* ... */
    • /** ... */
  • Statements direct what a program does
  • Identifiers are any name you create in a Java program
  • Keyword is a special word reserved by Java
  • You develop Java programs writing one or more classes
  • Every Java application starts with a main method

Exercise 2.1

With a single partner, if needed, 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. public class HelloWorld {
         public static void main(String[] args) {
            System.out.println("Hello, world!");
        }
    }
    
  3. Save the file as "HelloWorld.java".
  4. Q1: Which lines of code contain an identifier?

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

  7. Add a block comment as shown in section 2.1.1
  8. Re-compile and execute the code.
  9. Q3: How does the added block comment change the execution of the code?

  10. Remove the word "static" from the HelloWorld program. Then, re-compile and execute the code.
  11. Q4: What message does the compiler report?

2.2: Data and Data Types

Objectives

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

  • Describe the eight primitive data types
  • Distinguish between an integer, a floating-point number, and a boolean value
  • Decide which data type is appropriate for representing data

2.2.1: Bits and Bytes

    "There are only 10 kinds of people in the world, those who understand binary and those who don't."
    -- Unknown

  • Bit - (Binary Digit) smallest unit of information within a computer
  • Bit has two values: 0 and 1
  • Byte - a group of 8 bits
    • Usually the smallest addressable amount of memory
  • A byte has 256 possible combinations of values -- Why 256?
  • What is the binary number represented by the picture above?
  • What is the decimal equivalent?
  • How do you think computers store the following data?
    • 12
    • 512
    • 16,384
    • 2,147,483,648
    • 1.23
    • 2.34159...
    • The letter 'A'
    • The values true or false

More Information

2.2.2: Primitive Data Types

  • Java has built-in data types for numbers, characters and booleans
  • These built-in types are called primitive types
  • A data type tells a computer how to interpret the data
  • Java can recognize literal values for each primitive type
  • Literal values are a sequence of characters in a certain form
  • General Type Explanation Examples
    Integers Numbers without decimal points 123
    -987
    Floating-Point Numbers with decimal points 1.23
    -0.01
    Characters Single letters, digits and special symbols 'A'
    '9'
    Booleans Logical values true or false true
    false

  • Since these literal values are compiled into our programs, they cannot be changed

2.2.3: Integers

  • An integer is zero or any positive or negative number without a decimal point
  • For example:
  • 0   1   -1    +5    -27   1000    -128
  • Integer literals may have a sign (+ or -) before the number
  • Cannot have any commas, decimal points or special symbols (like $)

Integer Data Types

  • Java has four integer data types
  • Type Name Memory Size Range of Values
    byte 1 byte -128 to 127
    short 2 bytes -32768 to 32767
    int 4 bytes -2,147,483,648 to 2,147,483,647
    long 8 bytes -9,223,372,036,854,775,808 to
     9,223,374,036,854,775,807

  • Default integer type is int
  • Long integers are written the same as an int but with an L appended
  • For example:
  • 9876543L    2147483649L
  • Java supports small integer types byte and short
    • But no way to explicitly specify them as literals

2.2.4: Floating-Point Numbers

  • A floating-point literal is any signed or unsigned number with a decimal point
  • For example:
  • 0.0   1.0   -1.1    +5.    -6.3    3234.56     0.33
  • Note that 0.0, 1.0 and +5. are floating-point numbers, but could be rewritten as integers
  • Like integers, cannot have any commas or special symbols

Floating-Point Data Types

  • Java has two floating-point data types
  • Type Name Memory Size Range of Values
    float 4 bytes +/- 3.40282346638528860 x 1038 to
    +/- 1.40129846432481707 x 10-45
    double 8 bytes +/- 1.79769313486231570 x 10308 to
    +/- 4.94065645841246544 x 10-324

  • Default floating point type is double
  • Type float needs an "F" or "f" appended
  • For example:
  • 2.34159F     6.28318f

Exponential Notation

  • Floating-point literals can be written in exponential notation
    • Similar to scientific notation
  • Used to express both very large and very small values in compact form
  • For example:
  • Decimal Notation Exponential Notation Scientific Notation
    1234. 1.234E3 1.234 x 103
    98765. 9.87654E4 9.8765 x 104
    .0123 1.23E-2 1.23 x 10-2
    .000625 6.25E-4 6.25 x 10-4

  • Letter E stands for exponent
  • Number following E represents a power of 10
  • Indicates the number of decimal places to move for standard decimal value
  • Note that floating-point numbers follow standard IEEE 754-1985
  • Zero can be either 0.0 or -0.0

How Large is 1.7E308?

  • Largest possible double is 17 followed by 307 zeros
  • How large is that?
  • Current estimate of the number of atoms in the universe: about 1.0E78
  • Mathematicians use the term "google" for a very large number: 1.0E100
  • Data type double easily encompasses these numbers
  • What value is so large that it cannot be represented by type double?

2.2.5: Characters

  • A character is a letter, number or special symbol
  • For example:
  • 'a'   'b'   'Z'   '3'   'q'   '$'   '*'
  • Java provides the char data type to represent characters
  • Stores characters as a 16-bit unsigned value using Unicode
  • Large enough to store 65,536 distinct character codes
  • Unicode was designed to provide codes for all the world's alphabets
  • Internally, Java stores a char as an unsigned 16-bit number
    • Range is from 0 to 65535
    • Only Java type that is unsigned
  • More info: The Unicode® Standard: A Technical Introduction

Escape Sequences

  • First 32 character codes are not visible on our monitors
    • Represent control codes
  • Java can access some of the control codes using escape sequences
  • Backslash (\) directly in front of a select character tells the compiler to escape from the normal interpretation
  • Following table has some nonprinting and hard-to-print characters:
  • Sequence Meaning Unicode Value
      Alert \u0007
    \b Backspace \u0008
    \f Formfeed \u000C
    \n Newline \u000A
    \r Carriage return \u000D
    \t Horizontal tab \u0009
    \\ Backslash \u005C
    \" Double quote \u0022
    \' Single quote \u0027

  • Some examples:
  • System.out.print('\u0007');
    System.out.print('\n');
    System.out.print("Left\tRight");
    System.out.print("one\ntwo\nthree");
    

Programming Style

2.2.6: Boolean Values

  • Boolean types have just one of two values: either true or false
  • Mostly used in conditional statements -- will cover later in course

2.2.7: Summary

  • Computers store data in units of 8 bits called a byte
  • The eight primitive data types are:
  • Type Bytes Use
    byte 1 Very short integers from -128 to 127.
    short 2 Short integers from -32,768 to 32,767.
    int 4 Integers from -2,147,483,648 to 2,147,483,647.
    long 8 Long integers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
    float 4 Single-precision, floating-point numbers from -3.4E38 to 3.4E38 with 6 or 7 significant digits.
    double 8 Double-precision, floating-point numbers from -1.7E308 to 1.7E-324 with from 14 to 15 significant digits.
    char 2 A single Unicode character that’s stored in two bytes.
    boolean 1 A true or false value.

Exercise 2.2

Determine the data types that are appropriate for the following problems and record your answers in exercise2.txt:

  1. The average number of four grades
  2. The number of days in a month
  3. The length of the Golden Gate Bridge
  4. The numbers in the state lottery

Wrap Up

    Reminders

    Due Next:
    Exercise 2 and CodeLab Lesson 2 (9/13/04)

  • When class is over, please shut down your computer
  • You may complete unfinished exercises at the end of the class or at any time before the next class.
  • Instructions on submitting exercises are available from the HowTo's page.

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

Last Updated: September 15 2004 @12:06:25