Download Adam Gerber, PhD

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Adam Gerber, PhD, SCJP
[email protected]
Evaluations
• 50% homework
• 20% final project (take home)
• 20% two in-class quizzes (not announced, so
come to class prepared)
• 10% class participation
Late homework/final project is penalized 5% every
day late; no exceptions.
Turning in Assignments
• Tar you project using eclipse. Right click the project,
select Export… choose Archive File
• Save in tar format, create Directory structure
• See video called eclipseTar.avi posted to course webpage.
• Homework file naming: hw + <number> + “-” +
<lastname> .tar
• Homework examples: hw1-smith.tar, hw2-smith.tar
• Final project file naming example: fp-smith.tar
• Email to Jing Tie [email protected] and cc me,
[email protected]
Criteria for evaluation on homework
and final project
• 1/ does the program perform per spec 40%
• 2/ is the algorithm elegant/efficient or
clumsy/wasteful 30%
• 3/ have you handled exceptions properly 20%
• 4/ code style; naming variables, formatting,
ease of reading, documented 10%
What is Java?
What Sun (now Oracle) says about
Java
• “…we designed Java as closely to C++ as
possible in order to make the system more
comprehensible. Java omits many rarely used,
poorly understood, confusing features of C++
that, in our experience, bring more grief than
benefit.”
What is Java?
• Java is modeled after C++
• The majority of runtime errors in a C++ program
are due to improper memory management
(memory leaks). Java is a memory-managed
environment. In practice, that means you don’t
have to worry about de-allocating memory when
an object or primitive falls out of scope.
• Java is Write Once Read Anywhere (WORA). A
java program can run on any platform that has a
JVM.
Architecture Neutral
Java Code is compiled to .class files which are interpreted as
bytecode by the JVM. (.NET does this too; only you’re trapped
in an MS op system.)
Strictly OO
• Java is strictly Object-Oriented. Java code
must be encapsulated inside a class . No
procedural programming; and no spaghetti
code.
No operator overloading
• Exception to no Java Op-Overloading
…
int nOne = 2;
int nTwo = 7;
String sName = “Fourteen”;
System.out.println(sName + nTwo * nOne);
…
>Fourteen14
Implementation Independence
• A java int is ALWAYS 32bits; regardless of
operating system.
• A java long is ALWAYS 64bits.
• Etc.
• The same is not true of C/C++.
No Pointers
• There are no pointers in Java
• Instead Java uses references; which for all
intents and purposes, behave like pointers.
• We will discuss references in detail later.
Core Language Features
Java Keywords
abstract
assert***
boolean
break
byte
case
catch
char
class
const*
*not used
continue
default
do
double
else
enum****
extends
final
finally
float
**added
for
goto*
if
implements
import
instanceof
int
interface
long
native
in 1.2
***added
in 1.4
new
package
private
protected
public
return
short
static
strictfp**
super
****added
in 5.0
switch
synchronized
this
throw
throws
transient
try
void
volatile
while
Order of Precedence: PEDMAS
Operator Precedence
Operators
Precedence
postfix
expr++ expr--
unary
++expr --expr +expr -expr ~ !
multiplicative
*/%
additive
+-
shift
<< >> >>>
relational
< > <= >= instanceof
equality
== !=
bitwise AND
&
bitwise exclusive OR
^
bitwise inclusive OR
|
logical AND
&&
logical OR
||
ternary
?:
assignment
= += -= *= /= %= &= ^= |= <<= >>= >>>=
Wrapper Classes
• Every primitive has a corresponding Wrapper
class.
• For example; double has Double, int has
Integer, boolean has Boolean, char has
Character, etc.
• These wrapper classes can be very useful
when storing values in collections which
require you to use objects, not primitives.
Java Primitive Data Types
•
•
•
•
•
•
•
•
boolean 1-bit. May take on the values true and false only. true and false are defined constants of
the language and are not the same as True and False, TRUE and FALSE, zero and nonzero, 1 and 0 or
any other numeric value. Booleans may not be cast into any other type of variable nor may any
other variable be cast into a boolean.
byte 1 signed byte (two's complement). Covers values from -128 to 127.
short 2 bytes, signed (two's complement), -32,768 to 32,767
int 4 bytes, signed (two's complement). -2,147,483,648 to 2,147,483,647. Like all numeric types ints
may be cast into other numeric types (byte, short, long, float, double). When lossy casts are done
(e.g. int to byte) the conversion is done modulo the length of the smaller type.
long 8 bytes signed (two's complement). Ranges from -9,223,372,036,854,775,808 to
+9,223,372,036,854,775,807.
float 4 bytes, IEEE 754. Covers a range from 1.40129846432481707e-45 to
3.40282346638528860e+38 (positive or negative). Like all numeric types floats may be cast into
other numeric types (byte, short, long, int, double). When lossy casts to integer types are done (e.g.
float to short) the fractional part is truncated and the conversion is done modulo the length of the
smaller type.
double 8 bytes IEEE 754. Covers a range from 4.94065645841246544e-324d to
1.79769313486231570e+308d (positive or negative).
char 2 bytes, unsigned, Unicode, 0 to 65,535 Chars are not the same as bytes, ints, shorts or
Strings.
Java Primitives (integers)
Type
byte
short
int
long
Signed?
signed
signed
signed
signed
Bits Bytes Lowest
8
16
32
64
Highest
-27
1
-128
27-1
+127
-215
2
-32,768
215-1
32,767
-231
4 -2,147,483,648
231-1
2,147,483,647
-263
263-1
-9,
9,223,372,036,85
8 223,372,036,854
4,775,807
,775,808
How Java Stores positive Integers
-2(bits -1) to 2(bits -1) – 1
• 0001 0011
• The above is a binary representation of the
number 19 stored in a byte (8 bits).
• The range of a byte is: -128 to 127.
Java Primitives (others)
Type
Signed?
boolean
n/a
char
unsigned
Unicode
float
signed
exponent
and
mantissa
double
signed
exponent
and
mantissa
Bits Bytes Lowest
1
Highest
1 false
true
16
0
2
'\u0000'
216-1
'\uffff'
32
±3.40282346638
528860e+38
±1.40129846432
4
with 6 to 7
481707e-45
significant digits
of accuracy.
64
±1.79769313486
231570e+308
±4.94065645841
8
with 14 to 15
246544e-324
significant digits
of accuracy.
Prefix and Postfix Unary Operators
• when a prefix expression (++x or --x) is used as part of an
expression, the value returned is the value calculated after the
prefix operator is applied
int x = 0;
int y = 0;
y = ++x; // result: y=1, x=1
• when a postfix expression (x++ or x--) is used as part of an
expression, the value returned is the value calculated before the
postfix operator is applied
int x = 0;
int y = 0;
y = x++; // result: y=0, x=1
Primitives versus Objects
nomenclature and conventions
Primitives
Objects
In code, primitives are represented by
variables. Variables have two properties;
name and type.
In code, Objects are represented by
references. References have two
properties; name and type.
A variable name (aka variable) is
lower_case or camel_case, such as: area,
distanceToFinish, width, surfaceArea, etc.
A reference name (aka reference) is
lower_case or camel_case, such as:
student, dinnerTable, deskTop,
tabbedFrame, bankAccount, account etc.
A variable type is the name of the
primitive it represents, such as: boolean,
byte, short, int, long, char, etc.
(lower_case)
A reference type is the name of the class
it represents , such as: Rectangle, House,
Car, StringBuilder, Math, ArrayList, etc.
(UPPER_CASE)
For primitive and Object fields, I use standard camelCase. The reason is that the IDE will
generate getters and setters for me. For local variables and Objects, I tend to use
prefixes. One-letter prefix for primitives; and three letters prefix for objects: nCounter,
nC, datBirthDay, strFirstName, bFlag, dPrice, etc.
Eclipse IDE
Imports and the Java API
• Determine the version of Java you’re using. From the
cmd line> java –version
• http://download.oracle.com/javase/6/docs/api/
• java.lang.* is automatically imported. This default
behavior is know as ‘convention over configuration’. So
• Eclipse is very good about importing packages and
catching compile-time errors.
• To use the javadoc for the core Java API; F1
– JDK\src.zip
• To see source code; F3
Using the debugger
•
•
•
•
•
Perspectives; Java and Debug
Setting breakpoints
Setting conditional breakpoints
Step-over F6, and Step-in F5
Watch expressions
Java Doc
• Generate default JavaDocs.
• Using decorations/tags.
• Project || Generate JavaDoc.
– In Eclipse; navigate to JDK\bin\javadoc.exe to
configure.
• Scope; public to private methods
• Use F1 to pull up your javadocs.
Naming conventions
Naming fields - suggestions
boolean gender
byte
policyExpiry
int students
long population
float
totalTax
double
distanceToMoon
Person director
ArrayList shapes
Use generic camel case for fields of classes.
This is because the IDE will generate getters and setters for you
automatically.
Naming local variables - suggestions
boolean b bFlag
byte y yAge
char c cFirst
short s sRosterSize
int n nStudents; nC
long l lPopulation
float f fPrice
double d dDistanceToMoon
Naming local references - suggestions
Person per perDirector
String str strFirstName
Rectangle rec recShape1
Bee bee beeDrone
Naming local arrays and collections suggestions
Array of boolean barAnswers
Array of byte
yarAges
Array of int narIdentities
Array of Person perStudents
Array of String strCountries
Collection of Bee beeDrones
Collection of Athlete athPlayers
Collection of Cactus cacSaguaros NOT cacCacti
Why use a naming convention?
• metadata is immediately discernable just by
looking at the local variable or local reference
name. This makes your code easy to read and
debug.
• Primitives always have one letter prefix; nNumber
• References have three letter prefix; perDirector.
• Arrays and collections have three letter prefix + s
postfix: beeDrones; strCountries.
Attacking the problem
• 1/ Diagramming
• 2/ Psuedocode
• 3/ Implement in Java
Psuedocode
• Psuedocode is an intermediate language
• It describes an algorithm elegantly
• If you write proper pseudocode; implementing
your algorithm is easy!
• Use diagrams to visualize the data structures
in conjunction with pseudocode.
How to read psuedocode
//processString(strParam) take string as parameter
//initialize an int nPow to zero; and nResult to zero
//for each char in string (iterate over the string backwards) exclude the sign bit
//if char is either 1 or 0 (ignore spaces)
//if the char is 1
//increment the result by 2^nPow
//increment nPow
//return nResult
When writing psuedocode; Indent for either:
1/ looping logic such as do…while, while, for
2/ branching logic such as; if/else, case/switch
Draw boxes around the groups if you need to.
How Java Stores positive Integers
-2(bits -1) to 2(bits -1) – 1
• 0001 0011
• The above is a binary representation of the
number 19 stored in a byte (8 bits).
• The range of a byte is: -128 to 127.
Diagramming
• See blackboard...
Class
Object
• A blueprint is to a house as a class is to an object
• Class = Blueprint
Class
Objects
Class
Object
• A blueprint is to a car as a class is to an object
• Class = Blueprint
Class
Objects
Spot the “class” here
Primitives versus Objects
memory
Primitives
Objects
Variables store values and are allocated
memory depending on their type. How
much?...refer to Java Primitives slide.
References store memory addresses. The
size of the allocation for the object
reference is VM specific, but is usually the
native pointer size; 32bits in 32-bit VM,
and 64bits in a 64-bit VM.
Garbage collected when out-of-scope.
Garbage collected when out-of-scope.
Passed into methods by value
Passed into methods by reference
Using the new Keyword
• Unless you use the ‘new’ keyword, nothing
has been instantiated and the object does
NOT exist in memory.
• (the exception is static; which we’ll talk about
later)
pass by value
pass by reference
Action: Tell my accountant how much
I intend to spend on a new car.
Action: Swipe debit card and enter
pin at the Bently dealership.
Change in net worth: no change.
Change in net worth: -125k.
Control structures
• Branching logic
if
if-else
switch
ternary
• Looping
for
while
do…while
break / continue
Object heirarchies
• You can also see the API online. Determine the
version you using by typing> java –version
• http://download.oracle.com/javase/6/docs/api/
• Class hierarchies.
• The Object class is the grand-daddy of ALL java
classes.
• Every class inherits methods from Object.
• And from all its other ancestry.
• Even if you create a class that extends no other
classes, you still extend Object by default.
Some tools for your homework