Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Adam Gerber, PhD, SCJP [email protected] Office: Ryerson 251 Office Hours: Mondays 8:30pm to 10:30pm Survey of the class Name, hailing from, what you studied in undergrad, what you want to accomplish with this degree? Evaluations _01Control 5% _02Arrays 5% _03Objects 5% _04Interfaces 5% _05Dice 5% _06Design 5% _07BlackJack 5% _08Final 25% Quarterterm exam 10% (third session) Midterm exam 20% Class participation 10% Turning in Projects Be sure to push your latest commit(s) to your remote repo prior to the deadline. Projects are automatically fetched from your remote proJava at the due date/time-- typically 11:59pm. The master branch will be graded. Your projects are evaluated based on the state that they were in when the TA fetched them. NO EXCEPTIONS. Criteria for evaluation on projects >34% Does the program perform per spec, or as expected? >33% Is the algorithm elegant/efficient with respect to resources such as memory, have you handled exceptions properly? >33% Is your code style; naming variables, formatting, ease-of-reading, well-documented? Possible Curve MPCS policy is that no more than 30% of students can receive an A. I will usually curve the raw scores up to award as many A's as possible, but there's a chance I may need to curve down. Lecture 01 Agenda: Introductions Install course software and set up your dev environment Clone lab and project repos Tutorial on IntelliJ Overview of Java Language First Java Program Java primitive (native) datatypes Quick overview of fundamental programming structures Pseudocode Strings Arrays Type conversions (Integer.parseInt, etc.) Keyboard Input, etc. Random numbers Intro to objects and classes -- some basics Clone labJava, proJava GIT architecture New Boston Git Tutorial (prepare to laugh) https://www.youtube.com/watch?v=cEGIFZDyszA&index=1 &list=PL6gx4Cwl9DGAKWClAD_iKpNC0bGHxGhcx https://www.youtube.com/watch?v=G7kJRkUaVHQ git config --global user.name "Your Name" git config --global user.email "[email protected]" IntelliJ keymap File || settings || keymap 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 don’t have to worry about de-allocating memory when an object which was allocated on the heap falls out of scope. However don't allocate objects with reckless abandon. • 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.” Education -ROI http://www.indeed.com/salary?q1=java&l1=chic ago&q2=c%2B%2B&l2=chicago&tm=1 http://www.tiobe.com/tiobe_index https://www.youtube.com/watch?v=7PqS557XQU (optional – humans need not apply) 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.) JIT compilers are very fast – little difference between in performance between machine-binary and interpreted bytecode. No operator overloading • Exception to no Java Op-Overloading … int nOne = 2; int nTwo = 7; String strName = “Fourteen”; System.out.println(strName + 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 Jdk1.8 == Java 8.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: PEMDAS 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, and forbid the use of primitives. See TypeConversion.java 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. See lec01 PromotionAndCastingPrimitives.java 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. We will return to this with an example 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”; 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 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 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. 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 1972–1981. 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 local variables boolean bFlag byte yAge char cFirst short sRosterSize int nStudent; nC long lPopulation float fPrice double dDistanceToMoon String strFirstName Date datEncounter Naming members (fields) boolean mFlag byte mAge char mFirst short mRosterSize int mStudent long mPopulation float mPrice double mDistanceToMoon String mFirstName Date mEncounter Naming static members static boolean sFlag static byte sAge static char sFirst static short sRosterSize static int sStudent static long sPopulation static float sPrice static double sDistanceToMoon static String sFirstName static Date sEncounter Naming local arrays and collections boolean[] bAnswers byte[] yAges int[] nIdentities Person[] perStudents String[] strCountries Collection of Bee beeDrones Collection of Athlete athPlayers ArrayList<Person> 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 Attacking a Problem Steps for programming • 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. 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 imperative programming; looping logic and branching logic. In pseudocode, each loop and each branch has a body which you must indent. That's it! Psuedocode example1 //get input-message from user //Store input-message in String //Split the String using space as regex //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 example2 //get sentence 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 See EnterSomething.java & attackingProblem.webm & LettersToNumbers 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 More Java Features 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() IntelliJ Utlimate IDE The API Documentation of the Standard Java Library http://docs.oracle.com/javase/8/docs/api/ Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. 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 See DigitalToBinary.java & BinaryToDigital.java When writing psuedocode; Indent for either: 1/ looping logic such as do…while, 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) – 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. Object heirarchies • You can also see the API online. Determine the version you using by typing> java –version http://docs.oracle.com/javase/8/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. • Ctrl-H will show you object hierarchy in IntelliJ More git commands : move files from working-dir to stage-dir(aka index) git add . git add src/. git add src/lec01/glab/DigitalToBinary.java move files from stage-dir(aka index) back to working-dir git reset HEAD . git reset head src/. git reset head src/lec01/glab/DigitalToBinary.java git commit -m “your commit message.” add/reset/commit: move files from working-dir to stage-dir(aka index) git add . git add src/. git add src/lec01/glab/DigitalToBinary.java move files from stage-dir(aka index) back to working-dir git reset HEAD . git reset head src/. git reset head src/lec01/glab/DigitalToBinary.java git commit -m “your commit message.” Amending: Every commit is associated with a sha-1 hash. That hash is derived from 1/ the file changes in that commit and 2/ the previous commit. You can not change any commit unless that commit is at the head. Since no other commits depend on the head, you may safely change the head. To change the head, use git commit --amend -m “your message” git commit --amend --no-edit Reverting: You can roll back a commit (reverse it) by identifying it's sha1 hash like so. git revert --no-edit 71ac Branching: To list the branches in a project: git branch git branch -r git branch --all To create a branch: git checkout -b branchName c39b git checkout -b branchName To delete a branch: git branch -D branchName To checkout a branch: git checkout 7afe git checkout master Pushing to remotes: To see the remotes: git remote -v show To push to a remote: git push origin master:master git push origin master git push --all Fetching from remotes: To see the remotes: git remote -v show To fetch from a remote: git fetch --all