Download presentation
Presentation is loading. Please wait.
Published byDiane Ward Modified over 8 years ago
1
Adam Gerber, PhD, SCJP gerber@cs.uchicago.edu
2
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.
3
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 + + “-” +.tar Homework examples: hw1-smith.tar, hw2-smith.tar Final project file naming example: fp-smith.tar Email to Jing Tie jtie@uchicago.edu and cc me, gerber@cs.uchicago.edu
4
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%
5
What is Java?
6
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.”
7
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.
8
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.)
9
Strictly OO Java is strictly Object-Oriented. Java code must be encapsulated inside a class. No procedural programming; and no spaghetti code.
10
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
11
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++.
12
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.
13
Core Language Features
14
Java Keywords *not used ** added in 1.2 *** added in 1.4 **** added in 5.0
15
Order of Precedence: PEDMAS Operator Precedence OperatorsPrecedence postfixexpr++ 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= += -= *= /= %= &= ^= |= >= >>>=
16
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.
17
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.
18
Java Primitives (integers) TypeSigned?BitsBytesLowestHighest bytesigned81 -2 7 -128 2 7 -1 +127 shortsigned162 -2 15 -32,768 2 15 -1 32,767 intsigned324 -2 31 -2,147,483,648 2 31 -1 2,147,483,647 longsigned648 -2 63 -9, 223,372,036,854,775,808 2 63 -1 9,223,372,036,85 4,775,807
19
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.
20
TypeSigned?BitsBytesLowestHighest booleann/a11falsetrue char unsigned Unicode 162 0 '\u0000' 2 16 -1 '\uffff' float signed exponent and mantissa 324 ±1.40129846432 481707e-45 ±3.40282346638 528860e+38 with 6 to 7 significant digits of accuracy. double signed exponent and mantissa 648 ±4.94065645841 246544e-324 ±1.79769313486 231570e+308 with 14 to 15 significant digits of accuracy. Java Primitives (others)
21
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
22
Primitives versus Objects nomenclature and conventions PrimitivesObjects 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.
23
Eclipse IDE
24
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
25
Using the debugger Perspectives; Java and Debug Setting breakpoints Setting conditional breakpoints Step-over F6, and Step-in F5 Watch expressions
26
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.
27
Naming conventions
28
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.
29
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
30
Naming local references - suggestions Person per perDirector String str strFirstName Rectangle rec recShape1 Bee bee beeDrone
31
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
32
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.
33
Attacking the problem 1/ Diagramming 2/ Psuedocode 3/ Implement in Java
34
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.
35
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.
36
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.
37
Diagramming See blackboard...
38
Class Object A blueprint is to a house as a class is to an object Class = Blueprint
39
Class Objects
40
Class Object A blueprint is to a car as a class is to an object Class = Blueprint
41
Class Objects
42
Spot the “class” here
43
Primitives versus Objects memory PrimitivesObjects 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. Passed into methods by valuePassed into methods by reference
44
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)
45
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.
46
Control structures Branching logic if if-else switch ternary Looping for while do…while break / continue
47
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.
48
Some tools for your homework
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.