4/05 lecture sketch material not covered in lecture: ! new way to draw scope for a class: use double lines ======= ! some notes on printing in java ! SPEC and VISIBILITY of class definitions included (left out accidentally in lecture) ! notes on scalar operations and functions ! more notes on casting ! arithmetic scalar operations ! arithmetic scalar functions ! arithmetic logical operations ! more on arrays ! example also showing short-circuiting boolean operator ! modified version of example at end of lecture, plus more notes on printing announcements + Review session R3: saturday or monday? --> Monday, 4/16, 7-9pm, Olin Hall 155 + T2 ready next week + P4 ready for pick up by weekend \ regrade period ends one week after the + P4 scores online by weekend / later of these two dates + P5 solutions up later today + P5, T2 online feedback forms up over the weekend + P6 up later today + due date negotiable --> 6pm friday, april 13 + outline below: we have covered most of the material you need to do it topics + intro: classes, methods, objects + *target* $class$ with *main* method $public static void main(String[] args)$ + CodeWarrior demo: create project, add .java file, set target class, etc. + P6 outline ! java scalar operations and functions + 1-dimensional java arrays _______________________________________________________________________________ ! printing and output ! ! matlab java ! ! + $fprintf$, $sprintf$ + we'll see formatted java output later ! + $num2str(x)$ + $"" + x$ \ sometimes ! + $disp(x)$ + $System.out.println(x)$ / results are ! not helpful or what you expect ! (see example far below) ! + print value by omitting semicolon + no equivalent: semicolon $;$ is ! required for each statement, it is a ! *statement terminator* ! + note: no need for $...$ in java, can ! just go ahead and split line _______________________________________________________________________________ classes, methods, objects *class* = related java code grouped together into a named unit + box scope + class is a new scope, drawn with double lines: ======= + classes live inside "top-level" BIG enclosing scope ! + *public* classes are visible to each other *method* = java function + *function* = java method that $return$s a value + *procedure* = java method that returns no value *object* = java struct + lives within the scope of a class + contains variables (like matlab); these are called *instance* variables + also contains methods! these are called *instance* methods + more later; for now, mainly for contrast with *static* class syntax: /* SPEC */ VISIBILITY class NAME { DECLARATIONSandDEFINITIONS } ! SPEC: comment with high-level description of the class ! VISIBILITY: $public$ or $private$ + $public$ = everyone is allowed to see + $private$ = visible only within the file (or something like that) + $$ = for us: like $public$, but bad style + NAME: name of the class + DECLARATIONSandDEFINITIONS: + declarations of *instance* and *class* variables + definitions of *instance* and *class* methods + note: methods may call each other but the order they are defined does not matter to the computer -- so try to choose an order that makes it easier for people to follow + box scope: + draw a big scope for the class: draw boundary as double line + label it with $class NAME$: can omit $class$ to be lazy, but it is probably a good idea to include it because there are so many different kinds of boxes method syntax: /* SPEC */ VISIBILITY STATIC RETURN_TYPE NAME(PARAMETERS) { // <-- method *header* BODY } + SPEC: comment containing specification of method behavior + VISIBILITY: $public$ or $private$ (or, later, $protected) + $public$ = everyone is allowed to see + $private$ = visible only within the class where it is defined + $$ = for us: like $public$, but bad style + STATIC: $static$ or $$ (nothing) + $static$ = *class* = exactly one copy, "owned" by the class; box scope: drawn within the scope of the class + reminder: label an activation record with the name of the method, but do NOT treat that label as something visible to others -- it is just for us so we know what all the different boxes are + note: a method can have multiple activation records + one copy + $$ = non-static = *instance* = one copy per object instance of the class: there can be 0 or more copies, depending on how many instances there are (explained in later lectures!) + RETURN_TYPE: + for a function, type of the return value, e.g. $int$, $double$, $String$ + note: unlike matlab, no return variable in the header + for a procedure, $void$: "no value is returned" + NAME: name of the method + PARAMETERS: type and variable name pairs, separated by commas + BODY: method body + for a function: *must* use $return EXPR;$ to return the value $EXPR$ + for a procedure: *may* use $return;$ to return no value important question and answer: + if/since there is lots of code, how does java know where to start running? + answer: + you must specify a *target* or *main* class + the target class must have a *main* method that is: + $public$ + $static$ + return type is $void$ (returns no value) + is named $main$ + has one parameter: name does not matter, but must be of type $String[]$ (an array of strings) -- for now, don't worry what its purpose is note: you now know that you could translate a matlab program into java by putting all the code in a single class. later, we'll see how to better organize code by breaking it up into multiple classes. _______________________________________________________________________________ example of target class and main method matlab: in command window, type: n = 5; i = 0; while i < n i = i+1 % <-- no semicolon, so $i = VALUE$ is printed end java: specify $OneToN$ is main class and define it as: public class OneToN { public static int n = 5; public static void main(String[] args) { int i = 0; while (i < n) { i = i+1; // <-- semicolon is required: statement terminator // no $int$ in front: was already declared System.out.println("i = " + i); } } } tracing the code above using box scope diagrams at very start, before $main$ runs: class OneToN ##==========## || || || +---+ || || n | 5 | || note: 1 copy of $n$ "owned" by class since it is static || +---+ || || || || main || note: 1 copy of $n$ "owned" by class since it is static || || ##==========## draw activation record: class OneToN ##=============## || || || +---+ || || n | 5 | || || +---+ || || || || main || || || || main || || +--------+ || || | | || || | | || || +--------+ || ##=============## draw boxes for parameters, evaluate arguments and place values in parameters: class OneToN ##=================## || || || +---+ || || n | 5 | || || +---+ || || || || main || || || || main || || +------------+ || || | +---+ | || || | args | *-+-+-++---> points to an array of Strings || | +---+ | || || +------------+ || ##=================## run method body inside activation record: class OneToN ##==========================================## || || || +---+ || || n | 5 | || || +---+ || || || || main || || || || main || || +-------------------------------------+ || || | +---+ | || || | args | *-+--------------------------|-++--->points to an array of || | +---+ | || Strings || | | || || | +-----------------------+ | || $i$ gets overwritten || | i | -0- -1- -2- -3- -4- 5 | | || multiple times, ending up || | +-----------------------+ | || equal to $5$ || | | || || | code: | || || | | || || | int i = 0; | || $i$ is found within || | while (i < n) { | || activation record || | i = i+1; | || || | System.out.println("i = " + i); | || $n$ is found within || | } | || class $OneToN$ || | | || || +-------------------------------------+ || ##==========================================## output: i = 1 i = 2 in general, when tracing, i = 3 we also want to know the i = 4 output i = 5 tear down (cross out) activation record when method is done: class OneToN ##==========================================## || || || +---+ || || n | 5 | || || +---+ || || || || main || || || || main || || +----------------/--------------------+ || || | +---+ / | || || | args | *-+---/----------------------|-++---> array of Strings || | +---+ / | || || | / | || note: array does not || | +-------/---------------+ | || immediately go away || | i | -0- -/- -2- -3- -4- 5 | | || just because the || | +-----/-----------------+ | || reference in the || | / | || activation record || | code: / | || goes away || | / | || || | int / = 0; | || || | whi/e (i < n) { | || || | / i = i+1; | || || | / System.out.println("i = " + i); | || || | / | || || |/ | || || /-------------------------------------+ || ##==========================================## _______________________________________________________________________________ codewarrior demo + see E12 for most of the details + to tell codewarrior to insert spaces instead of tabs: + go to the Edit menu + select Preferences + this brings up a window, probably named IDE Preferences + click on Font & Tabs under Editor in the left panel + click on Tab Inserts Spaces (the Revert (Panel) button should become activated) + click on the Save button (the Revert (Panel) button should become de-activated) _______________________________________________________________________________ P6 preview + note: do *not* use $for$ loops at all + P6.1 = debug Java version of P4.1: rightmost longest arith. input sequence code is provided as part of E12 + P6.2 = P5.2 in Java (condorcet(pwm), tallies(election), tally(ballot)) note: no $alldefeats$, no $sort$, no $find$ tip: look at online example of java versions of R1.6, R2.2 + P6.3 = T1.3 in Java (series) tip: look at online example of java version of P2.2 + P6.4 = T2.4 in Java (2nd-to-last mode of pre-sorted input) tip: re-use code from P6.1 to do input note: don't try to use $struct$s or objects + P6.5 = P2.4 in Java (small life, fibonacci, 1D arrays) note: you should now be able to do E12, P6.1, P6.3, P6.4 (once they are up) _______________________________________________________________________________ ! scalar operations and functions ! ! note: java scalars are also called *primitive* *types* ! ! matlab java ! ! *cast* = *coerce* = *convert* from one datatype to another ! + syntax: function call + funny syntax: $(TYPE) VALUE$ ! like parenthetical remark: ! "by the way, think of the following ! value as this particular datatype" ! + no need: integers are a special + int to double: ! case of $double$ + automatic when mix $int$ and ! $double$: $2 + 3.7$ ! + $(double) 5$, $(double) (2+3)$ ! + double to int: $fix(37)$ + $(int) 3.7$ ! + int to char: $char(65)$ + $(char) 65$ ! + char to int: $double('a')$, $'a'+0$ + $(int) 'a'$ ! + to boolean: $logical(0)$ + $(boolean) 0$, $x != 0$, $x != 0.0$ ! ! arithmetic ! + $+$, $-$, $*$, $/$ + the same, except: ! + $/$ for $int$ returns $int$ ! e.g. $17/2$ is $8$ ! + $/$ for $double$ returns $double$ ! e.g. $17.0/2.0$ is $8.5$ ! + cast as appropriate ! + $rem(a,b)$ + $a % b$ <-- integer only ! + $a^b$ + $Math.pow(a,b)$ <-- double only ! ! scalar functions ! + often put $Math.$ in front of name ! + $rand$ + $Math.random()$ ! + $exp$ + stick $Math.$ of name: $Math.exp$ ! + $sign$ + pre-defined equivalent? ! + $abs$, $min$, $max$ + stick $Math.$ in front of name ! + $ceil$, $floor$, $round$ + stick $Math.$ in front of name ! + $fix(x)$ + $(int) x$ <-- overflow can happen ! maybe there is $Math.trunc$ ? ! ! note: you should now be able to do P6.3 (series) ! ! logical boolean ! + $&$, $|$ + $&$, $|$ <-- *strict* ! + no equivalent + $&&$, $||$ <-- *short-circuiting* ! (see example far below) ! + $<$, $<=$, $>$, $>=$, $==$ + the same (see also casting) ! + $~$ + $!$ <-- standard abbreviation ! + $~=$ + $!=$ _______________________________________________________________________________ references -- no matlab equivalent + *value* = data that can be stored in a variable + values are "small": "fit on small scrap of paper" + *objects* are "too big" to be values -- arrays are objects in java + a *reference* (aka *address* or *pointer*) is "small enough" to be a value + box scope diagram: draw reference as an arrow pointing to entire object + copying the reference does not copy what it points to! + analogy: + the room $Upson 322$ is too big to fit on a scrap of paper + the address $Upson 322$ is small enough to fit on a scrap of paper + writing/copying down address $Upson 322$ does not copy/duplicate the room! + operator $new$: create ("big") object and return reference to it + value $null$: no(t a) reference (kind of like $nan$ in matlab) + two references are *aliases* if they point to the same object + *aliasing* is when two or more references point to the same object example: suppose $x$ is or points to an array and $y = x$ is executed: matlab java +---+---+---+ +---+ +---+---+---+ x | 3 | 7 | 9 | x | *-+---->| 3 | 7 | 9 | +---+---+---+ +---+ +---+---+---+ ^ +---+---+---+ +---+ | y | 3 | 7 | 9 | y | *-+------+ +---+---+---+ +---+ y$ gets a copy of the value in $x$: $y$ gets a copy of the value in $x$: $y$ gets a copy of the array $y$ gets a copy of the *reference* $y$ and $x$ are aliases modifying $y(2)$ has no effect on $x$ modifying $y(2)$ also modifies $x(2)$ since $x$ and $y$ point to the same array _______________________________________________________________________________ java arrays versus matlab arrays + arrays are objects and hence are not values + variables can store only *references* to arrays + implied array orientation (horizontal versus vertical) + no vectorizaton, no array concatenation, no deletion, no extension/resizing + 0-relative + $[$-$]$ for indexing + an array of $TYPE$s (e.g. an array of $int$s) has type $TYPE[]$, e.g. $int[]$ + create using $new$ + $String$s have their own syntax (sigh) matlab java + vectors, matrices, arrays /_________\ + not values! can't store in variables! + no equivalent \ / + reference to an array maybe $nan$ + $null$ + note: don't confuse $null$ pointer w/ + (reference to) null/empty string + (reference to) empty array + vectors, matrices, arrays + references to objects, e.g. to arrays $s = 'Hello';$ % string ($char$) $String s = new String("Hello");$ $row = [7 3];$ % row vector $int[] row = new int[] { 7, 3 };$ $col = [7 ; 3];$ % column vector $int[] col = new int[] { 7, 3 };$ $m = [7 3 ; 2 4];$ % matrix array of arrays $int[][] rowmajor = new int[][] { new int[] { 7, 3 }, new int[] { 2, 4 } };$ $int[][] colmajor = new int[][] { new int[] { 7, 2 }, new int[] { 3, 4 } };$ % $struct$ (array) reference to (array of) object(s) % ($cell$) reference to array of objects ... % ($cell$ of arrays) ragged array of arrays note: $row$ and $col$ are not keywords; they are just variable names that i thought would be descriptive one-dimensional array + $i$-th element $x(i)$, $x(i)=5;$ + $x[i]$, $x[i] = 5;$ + copy array + copy array $x = y;$ $x = (int[]) y.clone();$ + no equivalent + copy reference, so both point to the same array! $x = y;$ + $length(x)$ + $x.length$ <-- note no $()$ + *1-relative* indexing: 1.. + *0-relative* indexing: 0.. + concatenation + no equivalent + $[2 3 5]$ + $new int[] { 2, 3, 5 };$ + $[]$ + $new int[] { };$ + $zeros(1,n)$ + $new int[n]$ <-- java fills in $0$s + maybe $nan$ + $null$ + $x(end)$ + $x[x.length-1]$ + reading off left/right end illegal + same + assignment past right end extends + no extension vectorization we'll see no pre-defined equivalent + $abs$, $max$, $min$, $sign$ + $sort$ + $fliplr$, $flipud$, $rot90$, $'$ + indexing multiple elements at once + $+$, $-$, $.*$, $./$, $.^$, $rem$ + $any$, $all$ + $sum$, $cumsum$, $diff$ + $prod$, $cumprod$ ! example, with short-circuiting "and": ! ! x = []; int[] x = new int[0]; ! % no equivalent boolean good = x.length>0 && x[0] == 0; ! bad = length(x)>0 & x(1) == 0; boolean bad = x.length>0 & x[0] == 0; ! % ERROR: $x(1)$ is not defined! // ERROR: $x[0]$ is not defined! _______________________________________________________________________________ modified example from lecture: every other uppercase letter starting from A ! note: includes some notes on printing and strings matlab, unvectorized: n = 5; % number of letters x = char(zeros(1,n)); % row vector of characters i = 0; % number of letters created so far % store every other uppercase letter in $x$ starting from $'A'$ % inv: maintain definition above of $i$ while i < length(x) x(i+1) = char( 2*i + 'A' ); % <-- matlab auto-converts $'A'$ to % double because arithmetic is % performed on it i = i+1; end disp(x) java (e.g. code within main method) -- please run it!: int n = 5; // number of letters <-- declared inside method, so it is a // *local* variable, not a static or instance variable char[] x = new char[n]; // array of characters int i = 0; // number of letters created so far // store every other uppercase letter in $x$ starting from $'A'$ // inv: maintain definition above of $i$ while (i < x.length) { x[i] // <-- not $i+1$ because java is 0-relative, not 1-relative = (char) (2*i + (int) 'A'); i = i+1; } System.out.println("x is " + x); System.out.println(x); // print $x$ <-- java being nice int[] notnice = new int[] { 3, 1, 4 }; System.out.println("notnice is " + notnice); System.out.println(notnice); int[] mynull = null; System.out.println("mynull is " + mynull); System.out.println(mynull); ! output from a sample run: ! ! x is [C@758b6dae ! ACEGI ! notnice is [I@725b6dae ! [I@725b6dae ! mynull is null ! null ! ! question: what the @#$!$# blazes is being printed? ! ! answer: ! + for the most part, java can print only strings ! + java knows how to print an array of characters as if it were a string ! + but in general, java does not know how to print an object unless someone ! tells java how to do so ! + how is java told how to print an object? a method $toString$ is defined ! that returns a reference to a string describing the object ! + the default $toString$ method for objects --including arrays-- is ! a bit information about its type and its address ! + recall: a reference is an address of an object ! + what this means is: an address is a location in computer memory ! + locations in computer memory are integers ! + it is computer tradition to print addresses in *hexadecimal*, i.e. in ! base 16, which uses the digits: 0123456789ABCDEF ! (a=A=10, b=B=11, c=C=12, d=D=13, e=E=14, f=F=15) ! + so it looks like $[C@758b6dae$ has two parts: ! + $[C$ = "array ($[$) of characters ($C$)" ! + $@$ = "marker" to separate the two parts ! + $758b6dae$ = the address (in this particular run -- not necessarily ! always the same in every run!) _______________________________________________________________________________ questions from lecture Q: is $main$ a keyword? A1: no, it is just an identifier like any other, A1: e.g. $alldefeats$, $condorcet$, $issubset$, etc. A2: no, but it is "special" in that the main method must be named $main$ Q: does capitalization matter? A: yes: matlab identifiers work pretty much the same way as java identifiers, A: so case matters. Q: what does $void$ mean/do? A: it means "(returns) no value". Q: can you run/define methods outside of classes? A: no. Q: if you have many methods, which is run first? A: the designated main method of the target class is run. A: other methods run only if they are (called by other methods) called by the A: the main class Q: can a static method in a class call a static method in a different class? A: yes, if class $Buffy$ has static method $stake()$, then the main method of A: class $OneToN$ can call it via $Buffy.stake();$ A: note that like $struct$s in matlab, $.$ is used to mean A: "look inside a scope". note that $.$ cannot be used to look inside of A: activation records -- it is not always legal to use. later we'll see more A: precisely when it is legal to use. Q (follow-up): where do you draw the activation record for $stake()$? A: the old rule "put the activation record in the same place that you A: found the method/function/procedure" still applies: since we found it in A: class $Buffy$, the activation record is drawn inside class $Buffy$. A: note that as in matlab (at least for cs100M this semester), you never draw A: an activation record inside another activation record Q: is the empty line between the variable and method declaration/definitions Q: in class $OneToN$ for style? A: yes: putting a blank line before and after method definitions helps A: readability. Q: does each class have to be in a separate file? A1: in codewarrior no. A2: in some other java environments, not exactly: A2: there might be the restriction that there is at most one public class A2: per file, but any number of private classes