Download javaProgLec01

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Adam Gerber, PhD, SCJP
[email protected]
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 submitProjects2012.
1/ tar-up your project in Eclipse using proper naming
format. e.g. hw1-gerbera.tar.
2/ send an email with your tar file attached to your
assigned grader (see table on course website) and copy
me; [email protected]
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 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 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
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.
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
16
int
long
signed
signed
Bits Bytes Lowest
Highest
7
1 -2
-128
27-1
+127
15
2 -2
-32,768
215-1
32,767
32
-231
4 -2,147,483,648
231-1
2,147,483,647
64
-263
63-1
2
-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
64
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.
8 ±4.9406564584
1246544e-324
±1.79769313486
231570e+308
with 14 to 15
significant digits
of accuracy.
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 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<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
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
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
Eclipse IDE
The API Documentation of the Standard Java Library
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley &
Sons. All rights reserved.
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 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
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 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.