Java Lecture: "Rule of 3"
-
many concepts in programming come in groups of 3 rules:
- 3 steps to get your programming working
- Type in your program edit
- Compile your program computer converts your program to zeroes and ones
- Run your program computer executes your program as zeroes and ones
- 3 types of Errors
- Syntax errors forgetting a semicolon [compiler checks]
- Runtime errors dividing by 0 when running [computer crashes]
- Logic errors using wrong formula [ugh!]
- 3 types of Commenting
- Javadoc
- Multi-line
- Single line
- 3 steps for an Object
- Declare the Type and name of object PetRock pet1;
- Instantiate the object pet1 = new PetRock();
- Call the object's public methods pet1.getName();
- 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.
- method call statements
- if () statements
- loop statements
- 3 types of loops [lecture later]
- for ()
- while()
- do...while()
- 3 rules for Loop Control [lecture later]
- Initialize loop control variable int counter = 0;
- Test loop control variable while (counter < 10)
- Update loop control variable { counter = counter + 1; }
- 3 features in Classes
- variables
- methods
- ???
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";
- 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:
- don’t convert "more accurate" numbers to "less accurate" numbers...you will get a loss of precision error
- "less accurate" numbers are converted to "more accurate" numbers (upcast)
- you can "cast" or convert one number type to another by:
- int y = 3; double x = y;
- double x = 5.99; int y = (int) x;
- char and boolean are NOT numbers... no casting.
- String
- String objects hold one or more letters/characters.
- String name = "Fred";
- String greet = “Hello” + name;
- Color
- Color c1 = Color.red;
- Color c2 = new Color(1.0,0.0,1.0);
III. IDENTIFIERS
- used by programmers to give names to variables, methods, or Classes
- cannot be the same as a “reserved” Java word (i.e. private int)
- must start with a letter
- can be followed by any number of letters or digits
- are case-sensitive
- must be unique within the local scope (i.e. within {...} )
IV. VARIABLES
- are identifiers (see rules in II. above)
- must be declared as a certain Type (primitive or reference/object)
- int counter;
- boolean found;
- Color c1;
- String name;
- may be initialized/instantiated when declared (assigned a starting value)
- int j = 5;
- boolean found = true;
- Color flower = Color.red;
- may be assigned values corresponding to their Type
- double area;
- int radius = 5;
- String name
- area = 3.1415*radius;
- name = 3 + 4;
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.
- 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();
- pet1.eat();
- System.out.println("help");
- Conditionals (also known as: decisions, if...then, comparisons)
- Syntax - there are 2 styles…one without {} and one with {}…also may have an optional else{}
- if (condition) statement;
- if (condition)
{
statement1;
statement2;
...
}
- Examples
- if (age >= 16) System.out.println("old enough to drive");
- if ((score >= 80) && (score < 90))
{
System.out.println ("congratulations! You have paseed the class with a B");
}
- if (hours <= 40)
{
overtime = hours - 40;
System.out.println ("overtime hours is " + overtime);
}
else
{
System.out.println ("regular work time is " + hours);
}
- Comments
- 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)
- 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
- complex conditionals (also called nested if...else)
- example: suppose we want to record grades...we could do the following
if (score >= 90)
{
grade = 'A';
}
else
{
if (score >= 80)
{
grade = 'B';
}
else
{
if (score >= 70) ...
- however, we could make it look better by this arrangement
if (score >= 90)
{
grade = 'A';
}
else if (score >= 80)
{
grade = 'B';
}
else if (score >= 70)
{
grade = 'C';
}
- rule-of-thumb: if there will be more than 2 nested if...else, then use 2nd method.
Java Lecture: Loops
- Loops
- there are 3 ways to do loops (repetitive or iterative tasks)
- while loops
- for loops
- do-while loops (not covered in this class)
- all loops have the following properties that MUST be memorized
- a single loop control variable or, rarely, several variables (LCV)
- initialize the LCV (i.e. give it a starting value) by either:
- assigning the LCV a value (ex. int x = 0;) or
- calling a method that returns a value or
- reading it from the keyboard or file
- test the LCV (this is similar to the conditional in an if...else statement)
- update the LCV (i.e. give it a new value by either)
- assigning it (ex. x = x + 1)
- 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)
- the for loop
- Syntax:
for (initialize LCV ; test LCV ; update LCV)
{
statements;
}
- Result:
- The LCV is first given the initialize value.
- The LCV is then tested and
- if TRUE then
- the statements in the loop body {...} are executed,
- the LCV is updated, and
- the LCV is tested and the process repeated
- if FALSE then
- the loop body {} is skipped and the program continues after the end }
- examples.
- To print out the numbers from 1 to 100
for (int j=1; j <= 100; j=j+1)
{
System.out.println("counting:"+j);
}
- what will the following do and what problems might there be?
int n = 20;
float f;
for (int k = 2; k <= n; k++)
{
f *= k;
}
- the while loop
- Syntax:
while (condition)
{
statements;
}
- Result:
- the condition is evaluated to either true or false
- if true then
- the block statements are executed and
- the condition is tested again then
- the process repeated
- if false then
- the block statements are ignored and
- the program continues with the next statement after the end }
- comments
- looks easier then the for loop
- it's not because...
- you must initialize the LCV, test the LCV and update the LCV yourself!!!
- example: to print out the numbers from 1 to 100
int j = 1;
while (j <= 100)
{
System.out.println( "counting : " + j);
j++;
}
- when should we use for loop versus while loop?
- in a for loop we must know a head of time how many time to repeat
- while loops are more flexible... we control all 3 properties of LCV
- do NOT change the LCV inside a for loop... why not?
- while loops require more care and we make more syntax mistakes
- typical mistakes
- forgetting one of the 3 properties of LCV's
- misplacing one of the 3 properties in a while loop
- initialize LCV goes before the loop
- testing LCV goes inside the while ()
- update LCV goes inside the while loop body -- i.e. between { and }
- putting a semicolon at the end of the beginning...
- for (j = 1 ; j < 100; j++) ;
- while (j < 100) ;
|