CIS 3020 Part 3

From In The Wings
Jump to navigation Jump to search

Syntactic Elements

class SpecialTurtle extends Turtle {
  public void drawTriangle( double sideLength ) {
    final double DEGREES_IN_CIRCLE = 360.0;
    double turnAngle = DEGREES_IN_CIRCLE / 3;
    this.tailDown();
    this.move(sideLength);
    this.turnLeft(turnAngle);
    this.move(sideLength);
    this.turnLeft(turnAngle);
    this.move(sideLength);
    return;
  } // end drawTriangle
} // end class SpecialTurtle
  • Keywords (a.k.a. Reserved Words):
    • Examples: class, public, static, void, new, extends, double, this, return, const
    • Have a predefined meaning
    • Can only be used in specific locations within your program
  • class - used to define a class
  • public - allows everone to access
  • static - belonds to the class as a whole, not to an instance of the class
  • void - a "return value" of nothing
  • new - instantiate an instance (object) of a class
  • extends - define a specialized version of a class
  • double - defines a type - real number
  • this - refers to the current object
  • return - stop processing and return the specifed value, if one is given:
    • return;
    • return( expr );
  • final - used to define a constant:
    • final double DEGREES_IN_CIRCL 360.0;

Identifiers

  • Programmer selected symbolic names for data, operations, and classes
  • Contain letters, numbers, underscore
  • Start with letter or underscore
  • Class names: Demo, Island, Turtle
    • Start with capital letter (stylistic convention)
    • Each subsequent word also is capitalized
  • Method names: main, drawTriangle
    • start with lower case letter
    • Each subsequent word is capitalized
  • Data names
    • Constants - DEGREES_IN_CIRCLE
      • values that cannot change
      • All upper-case characters with underscores between words
    • Variables - sideLength, turnAngle, tina
      • Start with lower case
      • Each subsequent word is capitalized

Operators

  • Predefined by the language
    • [] - array index operator
    • = - gets (the value of), assignment operator
    • . - dot operator - send the message on the right to the object on the left. Not the same as decimal point in number.
    • + - addition operator
    • - - subtraction operator
    • * - multiplication operator
    • / - division operator
    •  % - modulus operator - remainder from division

Literals

  • A.K.A. Manifest constants
  • String
    • Examples: "a" "1" "Hi!"
  • Primitives
    • boolean
      • Used to represent the values true and false
    • Char
      • Uses 16-bits to represent a unicode glyph
      • Examples: 'a' 'A' '1' '.' Note single quotes
      • Is a number having a symbolic interpretation
  • Numeric Values
    • Int
      • 32 bit signed integer
      • Represents numbers ~ +/- 2,147,000,000
    • Double
      • 64-bit signed real number
      • 15 digits of accuracy
      • Represents numbers ~ +/- 2.2*10^308

Delimiters

  • Used to separate elements of the program
  • White space:
    • space, tab, newline
    • Are sometimes required
    • Use liberally to aid in readability
  • Punctuation
    • () - argument lists, parameter lists, subexpressions
    • {} - defines logical block (scope), array list initializers
    •  ; - end of a statement
    • , - separate elements in a list

Comments

  • Used to provide documentation on what the code does
  • Ignored by the compiler/interpreter
  • // everything until end of line is comment
  • /* everything between is comment */
  • Example:
int a /* not a good comment */ = 23;
int b = 47; // better comment
/*
 * multi-line comment */

Expressions

  • Produce a value when executed
  • Operators combine values
  • Evaluated left to right obeying operator precedence
  • Subexpression with operator of higher precedence is evaluated prior to expression with lower precedence
    • Example: a+b*c
    • Best to always clarify precedence with ()'s: a+(b*c)

Structure of Class Definition

class Example {
  // define class data members
  //        (constants and variables)
  // define instance data members
  //        (constants and variables)
  // define class methods
  // define constructors
  // define instance methods
}

Class vs. Instance

  • Class data member:
    • Associated with the class
    • A single value shared by entire class
    • Defined as a class value through use of "static" keyword
  • Instance data member:
    • Associated with an instance (object) of a class
    • Each object has its own independant value
  • Class method:
    • Used independant of any object of the class
  • Instance method:
    • Use is associated with an object of the class

Example

class USCitizen {
  // class variables
  private static int numUSPresidents;
  private static String USPresident;

  // Instance variables
  private String name;
  private int age;
  private USCitzen sigOther;

  // Class method
  public static String getPresidentName() {
    return USCitizen.presidentName;
  }

  // Constructors
  public USCitizen(String name, int age) {
    this.name = name;
    this.age = age;
  }
  public USCitizen(String name) {
    this.name = name;
  }

  // Instance methods
  // Accessor
  public String getName() {
    return (this.name);
  }
  public String toString() {
    return "US Citizen named " + this.name;
  }
  
  // Mutators
  public void setName(String name) {
    this.name = name;
  }
  public void haveBirthday() {
    this.age = this.age + 1;
  }
}

Selection Statements

  • A selection statement allows us to conditionally determine which following statement should be executed
  • if statement's general format:
if (expr) {
  statement_1;
} else {
  statement_2;
}

Note that the else clause is optional.

Selection Statement's expr

  • This is a boolean value expression composed of:
    • Literals: true false
    • Boolean values variables and constants
    • Operations returning a boolean value
    • Compound expressions involving logical operators

Truth Tables

A B !A A && B A || B
T T F T T
T F F F T
F T T F T
F F T F F

! is a Unary operator - takes a single value
&& and || are Binary operators - take two values

Flow Charts

Flow charts are used to visually express what a program does

Major components of a Flow Chart:

  • Boxes - represent calculations to perform
  • Diamonds - represent decision to make
  • Lines with arrows - detail the "flow" within the diagram

Example

  • Suppose we have a value, x, and would like to calculate the absolute value of x, setting absol to this value:
if (x>=0) {
  absol=x;
} else {
  absol=-x;
}
  • This is not real useful unless we need this calculated only once, so as a method we might write:
public int abs(int) {
  int absol;
  if (x>=0) {
    absol=x;
  } else {
    absol = -x;
  }
  return (absol);
}

Alternative Implementation 1

public int abs(int x) {
  if (x<0) {
    x=-x;
  }
  return (x);
}

Alternative Implementation 2

public int abs(int x) {
  if (x<0) {
    return (-x);
  } else {
    return (x);
  }
}
NOTE: BAD to use multiple returns!

Alternative Implementation 3

public int abs(int x) {
  if (x<0) {
    return (-x);
  }
  return (x);
}
NOTE: BAD to use multiple returns!

Relational Operators

Java supports several relational operators:

Operator Definition
== equality
!= not equal
> greater than
>= greater than or equal
< less than
<= less than or equal

All return a boolean value of true or false.

Logical Operators

Java supports several logical operators for combining results of relational operations:

Operator Definition
&& Returns true if both are true (short circuit)
& Returns true if both are true (tests both)
|| Returns true if either are true (short circuit)
| Return true if either are true (tests both)
! Negation operation

Use:

(((a<=b)&&(c==d))||!(a==d+2))

Example - Maximum

  • Suppose that we are given two values, first and second, and wish to find their maximum.
  • Create a specification, design, and implementation.

Specification

Inputs first, second
Outputs The larger of first or second
Constraints None
Assumptions None
Relationships None

Design

  1. Given first and second
  2. If first is larger than second, return first
  3. if second is larger than first, return second
  4. What if they are equal?

Implementation

public int max(int first, int second) {
  int maxi=second;
  if (first>second)
    maxi = first;
  return maxi;
}

if-else-if Ladder

  • This is a common programming structure when a series of tests must be performed:
if (expr_1) {
  stmt_1;
} else if (expre_2) {
  stmt_2;
} else if ...
  • As soon as an expression is found to be true, you evaluate the associated statement and quit.

Example

  • Suppose that we are calculating final grades for this class:
if (percScore >= 90) {
  grade="A";
} else if (percScore >= 80) {
  grade="B";
} else if (percScore >= 70) {
  grade="C";
} else if (percScore >= 60) {
  grade="D";
} else {
  grade="E";
}
  • Note: Order is critical!
  • We can also do the following:
if (percScore < 60) {
  grade="E";
} else if (percScore < 70) {
  grade="D";
} else if (percScore < 80) {
  grade="C";
} else if (percScore < 90) {
  grade="B";
} else {
  grade="A";
}
  • But, an arbitray order is bad:
if (percScore < 60) {
  grade="E";
} else if (percScore < 80) {
  grade="C";
} else if (percScore < 70) {
  grade="D";
} else if (percScore < 90) {
  grade="B";
} else {
  grade="A";
}
  • What grade is a score of 69?

Scope

  • Note that {}'s denote scope.
  • They are often used (as above) to clarify what is included in the "then" and "else"...
This: Is equivalent to:
if (x>=0) {
  abs=x;
} else {
  abs=-x;
}
if (x>=0)
abs=x;
else
abs=-x;
  • Which is easier to understand?