adam gerber, phd, scjp [email protected]
DESCRIPTION
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. - PowerPoint PPT PresentationTRANSCRIPT
Adam Gerber, PhD, [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 web-
page.• 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,
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 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.
Order of Precedence: PEDMASOperator 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 Signed? Bits Bytes Lowest Highest
byte signed 8 1-27
-128 27-1+127
short signed 16 2-215
-32,768 215-132,767
int signed 32 4-231
-2,147,483,648 231-1 2,147,483,647
long signed 64 8
-263
-9, 223,372,036,854,775,808
263-19,223,372,036,854,775,807
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.
Type Signed? Bits Bytes Lowest Highest
boolean n/a 1 1 false true
charunsigned Unicode
16 20'\u0000'
216-1'\uffff'
float
signed exponent and mantissa
32 4±1.40129846432481707e-45
±3.40282346638528860e+38with 6 to 7 significant digits of accuracy.
double
signed exponent and mantissa
64 8±4.94065645841246544e-324
±1.79769313486231570e+308with 14 to 15 significant digits of accuracy.
Java Primitives (others)
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 Objectsnomenclature 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.
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 fields - suggestions
boolean genderbyte policyExpiryint studentslong populationfloat totalTaxdouble distanceToMoonPerson directorArrayList 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 bFlagbyte y yAgechar c cFirstshort s sRosterSizeint n nStudents; nClong l lPopulationfloat f fPricedouble d dDistanceToMoon
Naming local references - suggestions
Person per perDirectorString str strFirstNameRectangle rec recShape1Bee bee beeDrone
Naming local arrays and collections - suggestions
Array of boolean barAnswersArray of byte yarAgesArray of int narIdentitiesArray of Person perStudentsArray of String strCountriesCollection of Bee beeDronesCollection of Athlete athPlayersCollection 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.
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, for2/ 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.
Primitives versus Objectsmemory
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. Change in net worth: no change.
Action: Swipe debit card and enter pin at the Bently dealership.
Change in net worth: -125k.
Control structures
• Branching logicifif-elseswitchternary
• Loopingforwhiledo…whilebreak / 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.