Download javaProgLec01-2014

Document related concepts
no text concepts found
Transcript
Adam Gerber, PhD, SCJP
[email protected]
office: Young Building 305B
office hrs: 8:30-10:30pm Mon
Survey of the class
Portfolio:
http://www.flickr.com/photos/89831807@N02/show/
Survey of the class
How many people understand how to program using object
orientation?
How many people have taken Immersion Programming (at UChicago)?
Name, hailing from, what you studied in undergrad, what you want to
accomplish with this degree?
Evaluations
proControl 5%
proArrays 5%
proObjects 5%
proInterfaces 5%
proDice 5%
proDesign 5%
proBlackJack 5%
proFinal 25%
Quarterterm exam 10%
Midterm exam 20%
Class participation 10%
Turning in Projects
Be sure to push you latest commit(s) to your remote repo
prior to the deadline.
Projects are automatically fetched from your remote
repos at the due date/time-- typically 11:59pm.
The branch with the latest commit 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, have you
handled exceptions properly
>33% code style; naming variables, formatting, ease-ofreading, well-documented
Lecture 01 Agenda:
1/ intro
2/ setup dev environment
3/ bitBucket, register, clone lab and
projects
4/ set-up git
5/ intro to Java
6/ lab01
Cloning labJava
Fork-and-Clone projects
GIT architecture
git config --global user.name "Your Name"
git config --global user.email "[email protected]"
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) 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
Pulling from remotes:
To see the remotes:
git remote -v show
To pull from a remote:
git pull --all
git pull origin eval
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.
• 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 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.
Java Primitives (integers)
Type
Signed?
byte
signed
8
short
signed
int
long
signed
signed
Bits Bytes Lowest
Highest
7
1 -2
-128
27-1
+127
16
15
2 -2
-32,768
215-1
32,767
32
-231
4 -2,147,483,648
231-1
2,147,483,647
64
-263
263-1
-9,
8 223,372,036,854 9,223,372,036,85
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.
We will return to this with an example
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
16
32
Highest
1 false
true
2 0
'\u0000'
216-1
'\uffff'
4 ±1.4012984643
2481707e-45
±3.40282346638
528860e+38
with 6 to 7
significant digits
of accuracy.
±1.79769313486
231570e+308
with 14 to 15
64
8 ±4.9406564584
1246544e-324
significant digits
of accuracy.
See lec01 notes upcasting and downcasting
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 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
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
See EnterSomething.java & attackingProblem.webm
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