Lewis and Clark Community College
Godfrey, Illinois

CIS 210 - Java Programming

Java Lecture: "Rule of 3"

  • many concepts in programming come in groups of 3 rules:

  1. 3 steps to get your programming working
    1. Type in your program                                     edit
    2. Compile your program                                    computer converts your program to zeroes and ones
    3. Run your program                                          computer executes your program as zeroes and ones
  1. 3 types of Errors
    1. Syntax errors                                                  forgetting a semicolon   [compiler checks]
    2. Runtime errors                                                dividing by 0 when running [computer crashes]
    3. Logic errors                                                    using wrong formula      [ugh!]
  1. 3 types of Commenting
    1. Javadoc                                                         /**….*/
    2. Multi-line                                                        /* …. */
    3. Single line                                                     //
  1. 3 steps for an Object
    1. Declare the Type and name of object             PetRock pet1; // pet1 object is declared as a type of PetRock class
    2. Instantiate the object                                  pet1 = new PetRock(); // create/instantiate the first pet object
    3. Call the object's public methods                     pet1.getName(); // go ask the first pet object what its name is.
  1. 3 ways to change the execution flow [lecture later]
      • Typically a program is run from the top line (or statement;) to the bottom line (or statement;). However the following are ways a programmer can change (or jump around) the program execution.
    1. method call statements /* [ i.e. using a pet1.getName()] ...jumps to whichever class or program has the method defined.*/
    2. if () statements // makes a decison between two (or more) choices
    3. loop statements // repeats statements for a certain number of times (jumps back up a few lines of code)
  1. 3 types of loops [lecture later]
    1. for ()
    2. while()
    3. do...while() // we won't be using this 3rd type of loop in this course
  1. 3 rules for Loop Control [lecture later]
    1. Initialize loop control variable                       int counter = 0;
    2. Test loop control variable                              while (counter < 10)
    3. Update loop control variable                          {   counter = counter + 1; }
  1. 3 features in Classes
    1. variables
    2. methods
    3. ???

 


Java Lecture: objects, Types, Identifiers, and Variables

 

I. OBJECT

  • An object is a storage area in the computer's memory that contains any data (information) and the methods (actions/functions) that change the data. An object is described by a Class that is written by the programmer.

II. TYPE (also called a class)

  • Definition of a TYPE - A description of the object. Usually, in a program, a variable gives a name to the object. 
  • A programmer creates a TYPE by writing a Class.
  • Example:
    • private String name = "Fred"; /* String is the TYPE (i.e. describes a bunch of alphabet letters) , while name is the variable that references the actual person's name in memory...in this case the word "Fred" is stored in the computer's memory */
  • Java has 2 kinds of variables: A. PRIMITIVE TYPES and B. REFERENCE TYPES.
  • A. PRIMITIVE TYPES – predefined Types in Java (mostly numbers)
  • Keyword memory  range Notes
    int 4 bytes - 2,147,483,648  TO  +2,147,483,647 + or - 2 billion
    float 4 bytes +/- 3.40282347 E 38  6 significant digits
    double 8 bytes +/- 1.79769313 E 308 15 significant digits
    byte 1 byte -128 TO +127  total of 256 different numbers
    char 2 bytes Unicode (65535 different characters) see http://www.unicode.org
    boolean ------- true or false (incomplete list ...)

     Notes:

  1. don’t convert "more accurate" numbers to "less accurate" numbers...you will get a loss of precision error
  2. "less accurate" numbers are converted to "more accurate" numbers (upcast)
  3. you can "cast" or convert one number type to another by:
    1. int y = 3;      double x = y;            // upcast to x = 3.00000000;
    2. double x = 5.99;   int y = (int) x;  // discards the decimal so y=5
    3. char and boolean are NOT numbers... no casting.
  • B. REFERENCE TYPES – everything that is not a primitive in Java are refered to as "objects." Every object has 2 parts:
    1. variables sometimes called as instance fields (nouns or ingredients)
    2. methods (verbs, actions or functions)

    Java comes with many (several thousand) Reference Types.  For example:

    1. String              // look in the String.java file in C:\ProgramFiles\java\jdk…\lang\
      1. String objects hold one or more letters/characters. 
      2. String name = "Fred";              // “Fred” is a String literal (like using a typewriter) stored in the variable called name
      3. String greet = “Hello” + name;     // greet now stores "HelloFred"
    2. Color            // look in Color.java file in the “java.awt” folder
      1. Color c1 = Color.red;                                    // Color.red is a literal color
      2. Color c2 = new Color(1.0,0.0,1.0);             // 1.0 red + 0.0 green + 1.0 blue will be purple

III. IDENTIFIERS

    1. used by programmers to give names to variables, methods, or Classes
    2. cannot be the same as a “reserved” Java word (i.e. private int)
    3. must start with a letter
    4. can be followed by any number of letters or digits
    5. are case-sensitive
    6. must be unique within the local scope (i.e. within {...} )

IV. VARIABLES

    1. are identifiers (see rules in II. above)
    2. must be declared as a certain Type (primitive or reference/object)
      • int counter;   
      • boolean found;      
      • Color c1; 
      • String name;
    3. may be initialized/instantiated when declared (assigned a starting value)
      • int j = 5; 
      • boolean found = true; // the variable found is being declared and assigned to a literal boolean type (true)
      • Color flower = Color.red; // the variable flower is being declared and assigned to a literal Color type (i.e. red)
    4. may be assigned values corresponding to their Type
      • double area;  //declaration of an area variable that will hold a decimal value later in the program
      • int radius = 5; // declaration of a radius variable and assigned a starting value of 5
      • String name // declaration of a name variable that will (later in program) hold a String of characters (letters) in quotes.
      • area = 3.1415*radius;    // assigning the area variable to a calculation using the radius variable. Careful of logic errors!
      • name = 3 + 4;      // No! String variable types cannot be assigned to numbers...letters and numbers are different Types

Java Lecture: Operators

 

   1. common math expressions

description

operator

example

notes

assignment

=

x=65

Similar to "equals to" in math but not exactly the same. Left side must be a variable, right side can be mathematical expression/calculation OR non-numeric (i.e. name = "Fred").

multiplication

*

x=3*4

careful of overflow! (x = 2000*2000*2000)

division

/

x=13/5

if x is integer, answer is dividend (x=2)

addition

+

x=3+2

 

subtraction

-

x=15-2

 

modulus

%

x=13%5 

x is integer, answer is remainder (x=3)

                           

   2. conditionals (or comparisons): relational and boolean operators (note: each is either true or false)

description

operator

example

notes

is equal  

==

x == 7 

tests if x is equal to 7 (this is NOT an assignment).

is not equal 

!=

x != 7 

do NOT test equality of double or float values

is greater than

>

x > 7 

tests if x is greater than 7 (may also use x >= 7)

is less than

<

x < 7

tests if x is less than 7 (may also use x <= 7 )

AND  

&&

(x>=7) && (x<8)

test if x is greater than or equal to 7 AND x is less then 8. Parenthesis are required.

OR   

||

(x<=4)||(x>8)

test if x is less than or equal to 4 OR x is greater than 8

            

   3. shortcuts and other operators

description

operator

example

notes

increment

++

x++;

same as x = x + 1; adds one to x

decrement

--

x--;

same as x = x - 1; subtracts one from x

add by

+=

x+=3;

same as x = x + 3; adds y to x and stores in x 

subtract by

-=

x-=5;

same as x = x - 5; subtract y from x & store in x

square root 

Math.sqrt(double)

x=Math.sqrt(2.0)

will return the square root of 2 (x=1.414...)

exponent

Math.pow(double,double)

x=Math.pow(2.0,3.0)

will return the power of 2^3 (x = 8)

trig functions

Math.sin(double)

x=Math.sin(3.14)

will return the sine of the angle (radians)

constants

Math.PI

x=Math.PI

x = 3.141592...

 


Java Lecture: Execution Control

 

Controlling which statements are executed (run) in what order

  • The normal flow of execution is that statements -- commands ending in a semicolon or curly bracket } -- are run from one statement to the next (top to bottom) in the order that the programmer typed the statements in.
  • However, this flow of execution can be changed by the programmer using either 1) method calls, 2) conditionals, or 3) loops. Loops will be in another lecture.
  1. Method calls
    • After an object is declared and instantiated, the object's public methods can be used or called whenever the programmer chooses.
    • The programmer may use the dot-notation to go inside an object and use any public method available in that object as written by the programmer of the object's Class.
    • examples
      • calculateArea(); /* jump to the calculateArea() method inside the same class being programmed (note that this is the same as this.calculateArea();) */
      • pet1.eat(); /* go to the pet1 object and call the eat() method that was programmed inside another class (i.e. if declared as PetRock pet1; then the eat() method would be found in the PetRock.java class */
      • System.out.println("help"); /*the computer will find to the System class, go inside to find the out object, then go inside the out object and call the println() method to put the String "help" on the computer screen*/
  2. Conditionals  (also known as: decisions, if...then, comparisons)
    1. Syntax - there are 2 styles…one without {} and one with {}…also may have an optional else{}
      1. if (condition) statement;
      2. if (condition)
        {
             statement1;
             statement2;
             ...            
        }
    2. Examples
      1. if (age >= 16) System.out.println("old enough to drive"); //  <-- pay attention to SEMICOLONS
      2. if ((score >= 80) && (score < 90)) // No SEMICOLON before { and watch out for matching ()
        {
            System.out.println ("congratulations! You have paseed the class with a B");
        
        }
      3. if (hours <= 40) // watch out for logic errors!
        {
            overtime = hours - 40;
            System.out.println ("overtime hours is " + overtime);
                            
        }
        else
        {
            System.out.println ("regular work time is " + hours);
                            
        }
    3. Comments
      1. Common Errors
        • semicolon after if (condition); rather than after the statement if (condition) statement;
        • no semicolon before the else --                                 Hint: ALWAYS use {}
          • unless NOT using {} in which case you DO need the semicolon before the else --
        • indentation problems -- especially with complex conditionals
        • forgetting the ( )
        • the condition must be able to evaluate to either a true or false (boolean)
      2. the condition must be of the form:
        • (boolean) or (operand relationOperator operand)
        • operand is either:
          • a variable or
          • a literal value
        • relationOperator is one of the following
          • <   >   <=   >=   ==   !=
        • may be combined (conjunction, junction, what's your function) by
          • && -- the "AND" conjunction.  BOTH must be true
          • || -- the "OR" conjunction, EITHER one can be true
          • ! -- the "NOT" operator,  REVERSES the answer
      3. complex conditionals  (also called nested if...else)
        1. example:  suppose we want to record grades...we could do the following
        2. if (score >= 90) 
          {     
                grade = 'A';  
          }
          else
          {     
                if (score >= 80)
                {    
                      grade = 'B';    
                }
                else
                {     
                      if (score >= 70)               ... //UGLY indentation problems
        3. however, we could make it look better by this arrangement
        4. if (score >= 90)
          {  
               grade = 'A';  
          }
          else if (score >= 80)       // note that the else...if are actually 2 different statements
          {  
               grade = 'B';  
          }
          else if (score >= 70)
          {  
               grade = 'C';  
          }                  
                    
        5. rule-of-thumb:  if there will be more than 2 nested if...else, then use 2nd method.

 


Java Lecture: Loops

 

  1. Loops
    1. there are 3 ways to do loops (repetitive or iterative tasks)
      1. while loops
      2. for loops
      3. do-while loops (not covered in this class)
    2. all loops have the following properties that MUST be memorized
      1. a single loop control variable or, rarely, several variables (LCV)
      2. initialize the LCV (i.e. give it a starting value) by either:
        1. assigning the LCV a value  (ex.  int x = 0;) or
        2. calling a method that returns a value or
        3. reading it from the keyboard or file
      3. test the LCV (this is similar to the conditional in an if...else statement)
      4. update the LCV (i.e. give it a new value by either)
        1. assigning it (ex. x = x + 1)
        2. reading a new value from the keyboard or file
      • failure to do any of the above 3 properties will result in a non-performing loop
      • failure to update the LCV properly will result in an infinite loop (i.e. never stops)
    3. the for loop
      1. Syntax:
      2. for (initialize LCV ; test LCV ; update LCV)
        { 
            statements;
        }
                  
      3. Result: 
        1. The LCV is first given the initialize value.
        2. The LCV is then tested and
          1. if TRUE then
            1. the statements in the loop body {...} are executed,
            2. the LCV is updated, and
            3. the LCV is tested and the process repeated
          2. if FALSE then
            1. the loop body {} is skipped and the program continues after the end }
      4. examples.  
        1. To print out the numbers from 1 to 100
        2. for (int j=1; j <= 100; j=j+1)           // what is the LCV?// where is initialize LCV
               System.out.println("counting:"+j);  // where is test LCV // where is update LCV
                            
        3. what will the following do and what problems might there be?
        4. int n = 20;
          float f;
          for (int k = 2; k <= n; k++)
          { 
               f *= k;
          }
                            
    4. the while loop
      1. Syntax:
      2. while (condition) 
        {
               statements;
        }
                        
      3. Result:
        1. the condition is evaluated to either true or false
          1. if true then
            1. the block statements are executed and
            2. the condition is tested again then
            3. the process repeated
          2. if false then
            1. the block statements are ignored and
            2. the program continues with the next statement after the end }
      4. comments
        1. looks easier then the for loop
        2. it's not because...
        3. you must initialize the LCV, test the LCV and update the LCV yourself!!!
      5. example:  to print out the numbers from 1 to 100
      6. int j = 1;                                     // initialize LCV
        while (j <= 100)                               // test LCV
        { 
              System.out.println( "counting : " + j);
              j++;                                     // update LCV
        }  
                        
      7. when should we use for loop versus while loop?
        1. in a for loop we must know a head of time how many time to repeat
        2. while loops are more flexible... we control all 3 properties of LCV
          1. do NOT change the LCV inside a for loop... why not?
        3. while loops require more care and we make more syntax mistakes
      8. typical mistakes
        1. forgetting one of the 3  properties of LCV's
        2. misplacing one of the 3 properties in a while loop
          1. initialize LCV goes before the loop
          2. testing LCV goes inside the while ()
          3. update LCV goes inside the while loop body -- i.e. between {  and  }
        3. putting a semicolon at the end of the beginning...
          1. for (j = 1 ; j < 100; j++) ;
          2. while (j < 100) ;

 

 

 

www.lc.edu

Revision Date: February, 2015