adam gerber, phd, scjp office: ryerson 154 office hrs: 3:30-5:30 tuesday

Download Adam Gerber, PhD, SCJP office: Ryerson 154 office hrs: 3:30-5:30 Tuesday

If you can't read please download the document

Upload: darren-boyd

Post on 18-Jan-2018

221 views

Category:

Documents


0 download

DESCRIPTION

Turning in Assignments See video entitled submitProjects / tar-up your project in Eclipse using proper naming format. e.g. hw1-gerbera.tar. 2/ send an with your tar file attached to your assigned grader (see table on course website) and copy me; homeworks and final-project typically due on Monday nights at 11:59pm. Late homeworks/final project is penalized 10% every day late; no exceptions.

TRANSCRIPT

Adam Gerber, PhD, SCJP office: Ryerson 154 office hrs: 3:30-5:30 Tuesday Evaluations Quizz 10% Midterm exam 15% Final exam 25% 4 homeworks 28% (7% each) Final project 12% Student participation 10% Turning in Assignments See video entitled submitProjects / tar-up your project in Eclipse using proper naming format. e.g. hw1-gerbera.tar. 2/ send anwith your tar file attached to your assigned grader (see table on course website) and copy me; homeworks and final-project typically due on Monday nights at 11:59pm. Late homeworks/final project is penalized 10% every day late; no exceptions. Criteria for evaluation on homework and final project >34% does the program perform per spec, or as expected >33% is the algorithm elegant/efficient, have you handled exceptions properly >33% code style; naming variables, formatting, ease-of-reading, well-documented What is Java? 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 dont have to worry about de-allocating memory when an object which was allocated on the heap falls out of scope. Java is Write Once Run Anywhere (WORA). A java program can run on any platform that has a JVM. 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. Architecture Neutral Java Code is compiled to.class files which are interpreted as bytecode by the JVM. (.NET does this too; only youre trapped in an MS op system.) JIT compilers are very fast little difference between in performance between machine-binary and interpreted byte- code. 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 much detail later. Version numbers in Java Jdk1.5 == Java 5.0 Jdk1.6 == Java 6.0 Jdk1.7 == Java 7.0 Core Language Features Java Keywords *not used ** added in 1.2 *** added in 1.4 **** added in 5.0 Don't be overwhelmed by the number of keywords; java programming all comes down to two control logics; branching and looping. 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= += -= *= /= %= &= ^= |= >= >>>= 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, and forbid the use of 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 e-45 to 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 e-324d to e+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) TypeSigned?BitsBytesLowestHighest byte signed shortsigned , ,767 intsigned ,147,483, ,147,483,647 longsigned , 223,372,036,854,775, ,223,372,036,85 4,775,807 How Java Stores positive Integers -2 (bits -1) to 2 (bits -1) 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. We will return to this with an example TypeSigned?BitsBytesLowestHighest booleann/a11falsetrue char unsigned Unicode '\u0000' '\uffff' float signed exponent and mantissa 324 e-45 e+38 with 6 to 7 significant digits of accuracy. double signed exponent and mantissa 648 e-324 e+308 with 14 to 15 significant digits of accuracy. Java Primitives (others) Prefix and Postfix Unary Operators when a prefix expression (++nX or --nX) is used as part of an expression, the value returned is the value calculated after the prefix operator is applied int nX = 0; int nY = 0; nY = ++nX; // result: nY=1, nX=1 when a postfix expression (nX++ or nX--) is used as part of an expression, the value returned is the value calculated before the postfix operator is applied int nX = 0; int nY = 0; nY = nX++; // result: nY=0, nX=1 We will return to this with an example 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 primitive variable name (aka variable) is lower_case or camelCase, such as: dArea, nDistanceToFinish, dWidth, fSurfaceArea, etc. A reference name (aka reference) is lower_case or camelCase, such as: stuStudent, tblDinnerTable, bnkAccount, etc. A variable type is the name of the primitive it represents, such as: boolean, byte, short, int, long, char, etc. A reference type is the name of the class it represents, such as: Rectangle, House, Car, StringBuilder, ArrayList, etc. Naming conventions Letter cases in Java Class names are UpperCase; public class Person {} Constants and enums are ALL_UPPER_CASE; private final int MAX_OCCUPANCY; public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } Everything else is lowerCamelCase. private int nValue; private double calcArea(double dWidth, double dHeight); private String strFirstName; Hungarian Notation Invented by Charles Simonyi, a programmer who worked at Xerox PARC circa 19721981. Simonyi is Hungarian. Hungarian names, like Korean names, are FamilyName GivenName There are several flavors of Hungarian Notation. The unadulterated Apps flavor is extremely verbose and redundant in Java. Using Apps Hungarian is way overkill in Java. We will use Caste Hungarian, which is a MUCH simplified version. Caste Hungarian: 1/ Describes metadata about the reference, primitive-variable, or collection. 2/ You do not need to continually refer back to the declarations section of the code to know what these references and primitive-variables contain. Naming primitive variables boolean bFlag byte yAge char cFirst short sRosterSize int nStudent; nC long lPopulation float fPrice double dDistanceToMoon Naming references Person perDirector String strFirstName Rectangle recShape1 Bee beeDrone Naming arrays and collections boolean[] bAnswers byte[] yAges int[] nIdentities Person[] perStudents String[] strCountries Collection of Bee beeDrones Collection of Athlete athPlayers ArrayList perVoters Avoid using 's' with names that indicate an single object or single primitive. e.g. -- use dRadiux, instead of dRadius. 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. Primitive-variables always have one letter prefix; nNumber Object-references have three letter prefix; perDirector. Arrays and collections always have s postfix: beeDrones; strCountries, dGrades Characters in Java Java uses 16bit Unicode character set which supposedly has enough values to cover all languages. chars can be treated as integers in Java which is convenient. When in doubt, use a String. Putting a single character in single quotes is a char in Java, whereas putting that same char in double quotes is a String. char cLetter = 'a'; String strLetter = a; Attacking the problem 1/ Describe the problem in your native language. Make sure you understand it. 2/ write Psuedocode 3/ Implement in Java 4/ Test and re-implement as required. Useful methods of String char charAt(int index) int compareTo(String anotherString) boolean endsWith(String suffix) int indexOf(multiple) int length() String substring(int begin, int end) String trim() Psuedocode Psuedocode is an intermediate language It describes an algorithm in simple terms If you write proper pseudocode; implementing your algorithm is easy! There are two kinds of logic in programming; looping logic and branching logic. In pseudocode, each loop and each branch has a body which you must indent. That's it! Psuedocode example //get input-message from user //Store input-message in StringTokenizer //for each word in input-message //if even word //print word all lower-case //else (word is odd) //print word all uppper-case //print space Psuedocode example //get input-message from user //create a boolean flag to switch between upper and lower case //for each char in input-message //if char is a space //flip boolean flag //If flag is upper //print char as upper //else //print char as lower How to read psuedocode Each loop and each branch of the conditional logic has a body that is indented. This body belongs to the loop or branch. Some examples: //get input-string from user //print your message in unicode is: //for each char in input-string //extract the char //cast char (unicode) to an int //print the int as String within brackets //print a space Control structures Branching (conditional) logic if if-else switch ternary Looping for while dowhile break / continue Object heirarchies You can also see the API online. Determine the version you using by typing> java versionClass 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 Eclipse IDE Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved. The API Documentation of the Standard Java Library Some Eclipse Shorcuts Quick-fix: left-click error flag in left margin will resolve imports will suggest fixes, such as surround with try/catch Code assist: begin typing then press ctrl-space Window > Preferences > Java > Editor > Templates surround, main, if, switch, for, while, etc. Control-click navigate: jump to the definition jump to varialbe/reference definitons jump to method definitions jump to Class definitions More Eclipse Shortcuts Keyboard shortcuts: ctrl-shift-G: searches for references to a highlighted class, method, field, or variable ctrl-shift-F4: closes all open editor windows ctrl-o: outline popup - quickly jump to a method in a large class F4: shows the hierarchy viewer for a class (ctrl-T shows similar data in a popup version) ctrl-m: toggle maximize of the current editor or view alt-shift-J: javadocs More Eclipse Shorcuts Quick Open: pressing ctrl-shift-T will open java files pressing ctrl-shift-R will open other resources use wildcards Rename: alt-shift-R highlight the variable/reference and press alt-shift-R renames all variables/references in class ctrl-shift-L: shows all keyboard shortcuts available in that context More Eclipse Shorcuts sysout ctrl-shift-F to format. Be careful! windows || preferences || Java || code styel || formatter || new profile || comments uncheck enable line comment formatting to preserve indents in psuedocode. clt-shift-forward_slash to surround with /* */ clt-forward_slash to make // comments Imports and the Java API Determine the version of Java youre using. From the cmd line> java versionjava.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 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. Using the debugger Perspectives; Java and Debug Setting breakpoints Setting conditional breakpoints Step-over F6, and Step-in F5 Watch expressions How to read psuedocode //get binary number from user //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 nResult by 2^nPow //increment nPow //return nResult When writing psuedocode; Indent for either: 1/ looping logic such as dowhile, while, for 2/ conditional logic such as; if/else, case/switch Each loop and each branch has a body. How Java Stores positive Integers -2 (bits -1) to 2 (bits -1) 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.