Mr. Meinzen - Java Lectures (first 9 weeks)

"Success is the ability to go from one failure to another with no loss of enthusiasm." Winston Churchill

Java Lecture: "Groups of Three"

  • many concepts in programming come in groups of 3 (i.e. 3 rules, 3 types, 3 steps, or 3 principles/purposes):

  1. Three 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. Three types of Errors
    1. Syntax errors                                                 compiler checks Java rules [ex: forgetting a semicolon]
    2. Runtime errors                                               computer program crashes [ex: dividing by 0 when running]
    3. Logic errors                                                   mis-understanding by programmer [ex: using wrong formula]  
  1. Three types of Commenting
    1. Javadoc : above Classes & methods                             /**….*/
    2. Single line   (or inline) : single statements or formulas   //
    3. Multi-line : for everything else                                     /* …. */
  1. Three steps for Case (lower-case and upper-case letters)
    1. First letter Capitalized : Classes, Constructors, Constants
    2. First letter lower-case : methods, variables, primitives
    3. Everything uses camelCase (starting letter of every word after the first word is capitalized)
  2. Three steps for Indenting (vertical alignment)
    1. start and stop curly brackets should align vertically
      • {
      • }
    2. declarations (start of each word should align vertically)
      1. private int       length;
      2. private double pi;
    3. assignments (equal sign should align vertically)
      1. length = 40;
      2. pi       = 3.1415;
  3. Three types of Identifiers (spelling picked by programmer)
    1. Classes
    2. variables
    3. methods()
  4. Three 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.
  5. Three Principles (main ideas) of Object Oriented Programming (OOP)
    1. Encapsulation - each object (or method) "owns" its own private (or local) data stored in variables. Such data can be kept separate (or private/local) from other objects/methods.
    2. Abstraction - the ability to identify a common feature among a group of objects.
      Example: two abstractions that every student in a classroom have in common are "height" [i.e. a variable abstraction] and "calculateGPA()" [i.e. a method abstraction]
    3. Algorithms - a sequence of statements (or commands) that have a purpose. These statements may include a conditional (if..else...) or iteration (loop). Such algorithms are usually encapsulated and abstracted into a method.

      Example: Below, the abstraction "swapDimensions()" is a method that encapsulates (i.e. put inside the method body {...}) a sequence of 3 steps (i.e. algorithm) that exchanges the length and width of a rectangle.

      public void swapDimensions()
      {
         int t  = length;
         length = width;
         width  = t;
      }


      [there are more Principles, but we will focus on the above 3 in this course]
  6. Three ways to control 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 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)
  7. Three 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
  8. Three 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; }
  9. Three questions to ask when designing methods:
    1. What is the method's name or purpose?
    2. What answer does the method return, if any?
    3. What additional information is needed in parenthesis, if any(i.e. parameters)
  10. Three 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

  • 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 (or "referenced") 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 III. 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 = 17;

"math" calculations can only be on right side and the variable must be on the left side

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...

 

All 41 Java Operators and Order of Operations

Operator Type

Category

Precedence

x and y are a numeric variables, b is a boolean variable

Unary [8]

postfix

x++ x--

prefix

++x --x +x -x ~x !b

Arithmetic [5]

multiplicative

* / %

additive

+ -

Shift [3]

shift

<< >> >>>

Relational [7]

comparison

< > <= >= instanceof

equality

== !=

Bitwise [3]

bitwise AND

&

bitwise exclusive OR

^

bitwise inclusive OR

|

Logical [2]

logical AND

&&

logical OR

||

Ternary [1]

ternary

? :

Assignment [12]

assignment

= += -= *= /= %= &= ^= |= <<= >>= >>>=

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) ;

 

Java Lecture: Keywords (i.e. Java Reserved Words)

 

The following words have special meaning in the Java language and cannot be used as identifiers (i.e. names of variables, methods, or classes) by the programmer:

Keywords (or Reserved Words) used in

Programming in Java (& Honors)

Keywords used in

AP Computer Science - A

Other Keywords that are not explicitly taught in EHS courses:

  1. boolean
  2. byte
  3. char
  4. class
  5. double
  6. else
  7. extends
  8. false
  9. float
  10. for
  11. if
  12. implements
  13. int
  14. import
  15. new
  16. null
  17. private
  18. public
  19. return
  20. this
  21. true
  22. while
  23. void
  1. abstract
  2. catch
  3. do
  4. final
  5. finally
  6. instanceof
  7. interface
  8. long
  9. package
  10. short
  11. static
  12. super
  13. switch
  14. throw
  15. throws
  16. try
  1. assert
  2. break
  3. case
  4. const
  5. continue
  6. default
  7. enum
  8. goto
  9. native
  10. protected
  11. strictfp
  12. synchronized
  13. transient
  14. volatile

Practice Finding Errors (syntax, logic, professionalism):

 

PetRock : Hidden Errors

Find any errors with regards to "syntax", "logic" or "professionalism" (i.e. commenting, indenting, capitalization, etc.)

 

 

public class PetRock
{
	private int    radius;			//width of rectangular rock
	private String name;			// name of rock

	public void PetRock()
	{
		name 	= "Mr. Meinzen's Pet Rock";
		length	= 30;
		     	= 70;
	}

	/**
	* The calculateArea() method calculates and returns
	* the area of the (rectangular) rock.
	*/
	public int calculateArea()
	{
		int area;
		area = 2*Math.PI*radius^2;
		return area;
	}

	public void drawRock ()
	{
		System.out.println("Hello to the Pet Rock Program");
		System.out.println("");
		System.out.println("The name of my rock is "+name);
		System.out.println("The width of my rock is "+radius);
		system.out.println("The area of my rock is "+calculateArea);
	}


	public static void main(String argv)
	{
		PetRock Pet1;
		Pet1 = new PetRock();
		PetRock.drawRock();
	}
}
              
              

PetRock : Colored Errors

Find any errors with regards to syntax, logic, or professionalism" (i.e. commenting, indenting, capitalization, etc.)

 

 

public class PetRock
{
	private int    radius;			// width of rectangular  rock
	private String name;			// name of rock

  /** commenting on every method.*/ 
	public void PetRock()
	{
		name 	= "Mr. Meinzen's Pet Rock";
		length	= 30;
		     	= 70;
	}

	/**
	* The calculateArea() method calculates and returns
	* the area of the (rectangular) rock.
	*/
	public int calculateArea()
	{
		int area;
		area = 2*Math.PI*radius^2;
		return area;
	}

  /** comment on every method.*/ 
	public void drawRock ()
	{
		System.out.println("Hello to the Pet Rock Program");
		System.out.println("");
		System.out.println("The name of my rock is "+name);
		System.out.println("The width of my rock is "+radius);
		system.out.println("The area of my rock is "+calculateArea  );
	}

  /** commenting on every method.*/ 
  public static void main(String argv[])
	{
		PetRock Pet1;
		Pet1 = new PetRock();
		PetRock.drawRock();
	}
}
              
              

Chip.java : Hidden Errors

Find any errors with regards to "syntax", "logic" or "professionalism" (i.e. commenting, indenting, capitalization, etc.)

 

 

public Class Chip()
{
    private color chipColor;
    private int   value;

    /**
     * Creates a new blank chip
     */
    public Chip()
    {
        chipColor = Color.black;
        value     = 0;
    {

    /**
     * Creates a chip with a specified value with default color being white.
     */
    public Chip(v)
    {
        value = v;
        chipColor = Color.white;
        if (value = 10)
        {
            chipColor = new Color(255,0,0)
        }
    }

    public   toString()
    {
        String temp = "I am a Chip of value = "+value+" and color is "+chipColor
        return temp;
    }

    public Color getColor
    {
        return colorOfChip;
    };
}           
              

Chip.java : Bolded Errors

 

 

import ???
public Class Chip()
{
    private color chipColor;
    private int   value;

    /**
     * Creates a new blank chip
     */
    public Chip()
    {
        chipColor = Color.black;
        value     = 0;
    {

    /**
     * Creates a chip with a specified value with default color being white.
     */
    public Chip(v)
    {
        value = v;
        chipColor = Color.white;
        if (value = 10)
        {
            chipColor = new Color(255,0,0)
        }
    }

    /** ???
    public   toString()
    {
        String temp = "I am a Chip of value = "+value+" and color is "+chipColor
        return temp;
    }


    /** ???
    public Color getColor
    {
        return colorOfChip;
    };
}           
              

 

Challenging Concepts and Terms

Note: the following are not definitions but rather English words that are essential to communicating ideas and concepts in computer science. Some are listed as pairs of similar but distinct concepts and others are listed as synonym separated by back-slashes (/).

  1. bits and bytes and powers of 2 (i.e. binary number system)
  2. professional code and conventions (i.e. indenting, commenting, & camelCase and get/set methods)
  3. conditions in if statements and loop sgtatements / boolean
  4. syntax vs symantics vs logic
  5. compile vs execution (i.e. syntax errors vs runtime errors vs logic errors)
  6. objects/references vs Classes/Types
  7. variables/nouns vs methods/functions/verbs
  8. declare vs instantiation vs calling/using
  9. interfaces vs data hiding (i.e. public vs private vs local)
  10. Algorithms & Data Abstractions:
    1. swap, shuffle, sort
    2. arrays [index vs element] and objects (i.e. encapsulating field variables and methods)