Adam Gerber Ph D SCJP gerbercs uchicago edu
Adam Gerber, Ph. D, SCJP gerber@cs. uchicago. edu
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 eclipse. Tar. avi posted to course webpage. • Homework file naming: hw + <number> + “-” + <lastname>. tar • Homework examples: hw 1 -smith. tar, hw 2 -smith. tar • Final project file naming example: fp-smith. tar • Email to Jing Tie jtie@uchicago. edu and cc me, gerber@cs. uchicago. edu
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 n. One = 2; int n. Two = 7; String s. Name = “Fourteen”; System. out. println(s. Name + n. Two * n. One); … >Fourteen 14
Implementation Independence • A java int is ALWAYS 32 bits; regardless of operating system. • A java long is ALWAYS 64 bits. • 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* continue default do double else enum**** extends finally float for goto* if implements import instanceof interface long native new package private protected public return short static strictfp** super *not used **added in 1. 2 ***added in 1. 4 ****added in 5. 0 switch synchronized this 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. 40129846432481707 e-45 to 3. 40282346638528860 e+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. 94065645841246544 e-324 d to 1. 79769313486231570 e+308 d (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 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 'u 0000' 216 -1 'uffff' 32 ± 3. 40282346638 528860 e+38 ± 1. 40129846432 with 6 to 7 4 481707 e-45 significant digits of accuracy. 64 ± 1. 79769313486 231570 e+308 ± 4. 94065645841 with 14 to 15 8 246544 e-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 A reference name (aka reference) is lower_case or camel_case, such as: area, lower_case or camel_case, such as: distance. To. Finish, width, surface. Area, etc. student, dinner. Table, desk. Top, tabbed. Frame, bank. Account, 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, String. Builder, Math, Array. List, etc. (UPPER_CASE) For primitive and Object fields, I use standard camel. Case. 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: n. Counter, n. C, dat. Birth. Day, str. First. Name, b. Flag, d. Price, 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; F 1 – JDKsrc. zip • To see source code; F 3
Using the debugger • • • Perspectives; Java and Debug Setting breakpoints Setting conditional breakpoints Step-over F 6, and Step-in F 5 Watch expressions
Java Doc • Generate default Java. Docs. • Using decorations/tags. • Project || Generate Java. Doc. – In Eclipse; navigate to JDKbinjavadoc. exe to configure. • Scope; public to private methods • Use F 1 to pull up your javadocs.
Naming conventions
Naming fields - suggestions boolean gender byte policy. Expiry int students long population float total. Tax double distance. To. Moon Person director Array. List 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 b. Flag byte y y. Age char c c. First short s s. Roster. Size int n n. Students; n. C long l l. Population float f f. Price double d d. Distance. To. Moon
Naming local references - suggestions Person per. Director String str. First. Name Rectangle rec. Shape 1 Bee bee. Drone
Naming local arrays and collections - suggestions Array of boolean bar. Answers Array of byte yar. Ages Array of int nar. Identities Array of Person per. Students Array of String str. Countries Collection of Bee bee. Drones Collection of Athlete ath. Players Collection of Cactus cac. Saguaros NOT cac. Cacti
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; n. Number • References have three letter prefix; per. Director. • Arrays and collections have three letter prefix + s postfix: bee. Drones; str. Countries.
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 //process. String(str. Param) take string as parameter //initialize an int n. Pow to zero; and n. Result 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^n. Pow //increment n. Pow //return n. Result When writing psuedocode; Indent for either: 1/ looping logic such as do…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; 32 bits in 32 -bit VM, and 64 bits in a 64 -bit VM. 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: -125 k.
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
- Slides: 48