Adam C. Champion and Dong Xuan CSE 4471: Information Security Autumn 2013 Based on material from C. Horstmann [1], J. Bloch [2], C. Collins et al. [4], M.L. Sichitiu (NCSU), V. Janjic (Imperial College London), CSE 2221 (OSU), and other sources Outline Getting Started Java: The Basics Java: ObjectOriented Programming Android Programming Getting Started (1) Need to install Java Development Kit (JDK) to write Java (and Android) programs Do not install Java Runtime Environment (JRE); JDK and JRE are different! Can download the JDK for your OS at http://java.oracle.com Alternatively, for OS X, Linux: OS X: Open !"##$%&'(%)*+!,(%$%(%-+!.-/0%*'$1'## Type 3'4'& at command line Install Java when prompt appears Linux: Type +56) '#(78-( %*+('$$ 6-9'5$(736: at command line (Debian, Ubuntu) Other distributions: consult distributions documentation Install! Getting Started (2) After installing JDK, download Android SDK from http://developer.android.com Simplest: download and install Android Developer Tools (ADT) bundle (including Android SDK) for your OS Alternatives: Download/install Android Studio (beta) from this site (based on IntelliJ IDEA) Install Android SDK tools by themselves, then install ADT for Eclipse separately (from this site) Well use ADT with SDK (easiest) Install! Getting Started (3) Unzip ADT package to directory ;'6(7<5*6$-7)+=, then run ;'6(7<5*6$-7)+=!-&$%#+-!>&$%#+- app. You should see this: Getting Started (4) Go to Eclipse preferences (Window!Preferences or ADT!Preferences), select Android tab Make sure the Android SDK path is correct (;'6(7 <5*6$-7)+=!+6:) Strongly recommend testing with real Android device Android emulator: very slow Install USB drivers for your Android device Getting Started (5) Bring up the Android SDK Manager Recommended: Install Android 2.2, 2.3.3 APIs and 4.x API Do not worry about Intel x86 Atom, MIPS system images In Eclipse, click Window!Show View!Other and select views Android!Devices, Android!LogCat Now youre ready for Android development! Outline Getting Started Java: The Basics Java: ObjectOriented Programming Android Programming Java Programming Language Java: generalpurpose language designed so developers write code once, it runs anywhere The key: Java Virtual Machine (JVM) Program code compiled to JVM bytecode JVM bytecode interpreted on JVM Well focus on Java 5 (Android uses this). See chapters 17 in [1]. Our First Java Program (1) #5<$%& &$'++ ?-$$)@)/$6 A #5<$%& +('(%& 4)%6 0'%*BC(/%*8DE '/8+F A CG+(-01)5(1#/%*($*BH?-$$) I)/$6JKFL M M Dont forget to match curly braces A,M or semicolon at the end! In Eclipse: File!New!Java Project, name project ?-$$)@)/$6 (no quotes), click Finish. Open ?-$$)@)/$6 in Package Explorer. Rightclick +/& directory, select New!Class, and create a class ?-$$)@)/$6 with a 0'%*BF method. To run the program, rightclick HelloWorld project, click Run As Our First Java Program (2) Rightclick, New!Class Explaining the Program Every .java source file contains one class We create a class ?-$$)@)/$6 that greets user The class ?-$$)@)/$6 must have the same name as the source file ?-$$)@)/$613'4' Our class has #5<$%& scope, so other classes can see it Well talk more about classes and objects later Every Java program has a method 0'%*BF that executes the program Method signature must be exactly #5<$%& +('(%& 4)%6 0'%*BC(/%*8DE '/8+F A 111 M This means: (1) 0'%*BF is visible to other methods; (2) there is only one 0'%*BF method in the class; and (3) 0'%*BF has one argument ('/8+, an array of C(/%*8 variables) Java thinks 0'%*BF, N'%*BF, 0%"OBF are different methods Every Java method has curly braces A,M surrounding its code Every statement in Java ends with a semicolon, e.g., CG+(-01)5(1#/%*($*BH?-$$) I)/$6JKFL Program prints ?-$$) I)/$6J to the console, then quits Basic Data Types (1) Java variables are instances of mathematical types Variables can store (almost) any value their type can have Example: the value of a boolean variable can be either (/5- or 9'$+- because any (mathematical) boolean value is true or false Caveats for integer, floatingpoint variables: their values are subsets of values of mathematical integers, real numbers. Cannot assign mathematical 2 500 to integer variable (limited range) or mathematical !2 to a floatingpoint variable (limited precision; irrational number). Variable names must start with lowercase letter, contain only letters, numbers, P Variable declaration: <))$-'* < Q (/5-L Later in the program, we might assign 9'$+- to <: < Q 9'$+-L Java strongly suggests that variables be initialized at the time of declaration, e.g., <))$-'* <L gives a compiler warning (*5$$ pointer) Constants defined using 9%*'$ keyword, e.g., 9%*'$ <))$-'* 9'$+-R))$ Q S"TC>L Basic Data Types (2) Javas primitive data types: [5] Primitive type Size Minimum Maximum Wrapper type <))$-'* 1bit N/A N/A R))$-'* &U'/ 16bit Unicode 0 Unicode 2 16 1 VU'/'&(-/ <G(- 8bit 128 +127 RG(- +U)/( 16bit 2 15 +2 15 1 CU)/( %*( 32bit 2 31 +2 31 1 W*(-8-/ $)*8 64bit 2 63 +2 63 1 T)*8 9$)'( 32bit IEEE 754 IEEE 754 S$)'( 6)5<$- 64bit IEEE 754 IEEE 754 X)5<$- Note: All these types are signed, except &U'/. Basic Data Types (3) Sometimes variables need to be cast to another type, e.g., if finding average of integers: %*( %*(Y*- Q Z[ %*(.I) Q \[ %*(.U/-- Q ][ *50W*(+ Q \L 6)5<$- 6)5<Y*- Q B6)5<$-F%*(Y*-[ 6)5<.I) Q B6)5<$-F0GW*(.I)[ 6)5<.U/-- Q B6)5<$-F%*(.U/--L 6)5<$- '48 Q B6)5<Y*- ^ 6)5<.I) ^ 6)5<.U/--F!B6)5<$-F*50W*(+L N'(U library has math operations like +_/(BF, #)IBF, etc. C(/%*8: immutable type for sequence of characters Every Java variable can be converted to C(/%*8 via ()C(/%*8BF The ^ operation concatenates C(/%*8s with other variables Let +(/ be a C(/%*8. We can find +(/s length (+(/1$-*8(UBF), substrings of +(/ (+(/1+5<+(/%*8BF), and so on [6] Basic Data Types (4) A literal is a fixed value of a variable type .`,>, S"TC> are <))$-'* literals ", a(, aK, and a5b]&b are &U'/ literals (escaped tab, quote characters, Unicode value for \pi) 7Z, b, b]c, bdZ' are %*( literals (last two are octal and hexadecimal) b1c, Z1b, Z>e, e1b\]>\] are 6)5<$- literals "( YC,, ?-$$) I)/$6J are C(/%*8 literals Comments: Single-line: !! +)0- &)00-*( () -*6 )9 $%*- Multi-line: !f &)00-*(+ +#'* 05$(%#$- $%*-+ f! Common Operators in Java !"#$%& ())*+,% -.,# $%" /)0(*+ J ^^ gg ^ hh ^ g ^ g ii f ! j f ! ; = ;Q =Q QQ JQ ; = ;Q =Q QQ JQ ; =
Notes: Compare C(/%*8 objects using the -_5'$+BF method, not QQ or JQ ii and hh use short-circuit evaluation. To see this, say <))$-'* &'*k%8+S$G Q S"TC> and we evaluate (&'*k%8+S$G ii ;+)0- R))$-'* -d#/-++%)*=). Since &'*k%8+S$G is S"TC>, the second part of the expression wont be evaluated. The second operand of j (integer modulus) must be positive. Dont compare 6)5<$-s for equality. Instead, define a constant like so: 9%*'$ 6)5<$- >kCWTYO Q Z>geL !! )/ +)0- )(U-/ (U/-+U)$6 l !! &U-&: %9 N'(U1'<+B6)5<$-Z 7 6)5<$-\F ; >kCWTYO Control Structures: Decision (1) Programs dont always follow straight line execution; they branch based on certain conditions Java decision idioms: if-then-else, switch if-then-else idiom: %9 B;+)0- R))$-'* -d#/-++%)*=F A !! (':- +)0- '&(%)* M -$+- %9 B;+)0- )(U-/ R))$-'* -d#/-++%)*F A !! (':- +)0- )(U-/ '&(%)* M -$+- A !! 6) +)0-(U%*8 -$+- M Control Structures: Decision (2) Example:
9%*'$ 6)5<$- YTXPX`YWX Q \1b[ 9%*'$ 6)5<$- O>@PX`YWX Q m1bL 6)5<$- 0GX/)%6 Q m1ZL %9 B0GX/)%6 ; YTXPX`YWXF A CG+(-01)5(1#/%*($*BH"*(%_5-JKFL M -$+- %9 B0GX/)%6 = O>@PX`YWXF A CG+(-01)5(1#/%*($*BHn-/G 0)6-/*JKFL M -$+- A CG+(-01)5(1#/%*($*BHo)5/ 6-4%&-p <'/-$G +5##)/(-61KFL M
Code prints n-/G 0)6-/*J to the screen. What if 0GX/)%6 QQ Z1Z? 0GX/)%6 QQ \1]? Control Structures: Decision (3) Example two:
9%*'$ 6)5<$- q>TToPR>"O Q m1Z[ 9%*'$ 6)5<$- WV>PV`>"N Q m1bL 9%*'$ 6)5<$- >kCWTYO Q Z>geL 6)5<$- 0GX/)%6 Q m1ZL %9 B0GX/)%6 = WV>PV`>"NF A %9 BN'(U1'<+B0GX/)%6 7 WV>PV`>"NF ; >kCWTYOF A CG+(-01)5(1#/%*($*BHW&- V/-'0 C'*6I%&UKFL M -$+- A CG+(-01)5(1#/%*($*BHq-$$G R-'*KFL M M -$+- A CG+(-01)5(1#/%*($*BHY$6 4-/+%)*KFL M
Code prints q-$$G R-'* to screen. Note nested if-then-else, >kCWTYO usage. Control Structures: Decision (4) Other idiom: switch Only works when comparing an int or boolean variable against a fixed set of alternatives Example: %*( '#% Q ZbL +I%(&U B'#%F A &'+- ]p CG+(-01)5(1#/%*($*BHV5#&':-KFL </-':L &'+- mp CG+(-01)5(1#/%*($*BHX)*5(KFL </-':L &'+- rp CG+(-01)5(1#/%*($*BHs&$'%/KFL </-':L &'+- tp CG+(-01)5(1#/%*($*BHS/)G)KFL </-':L &'+- Zbp CG+(-01)5(1#/%*($*BHu%*8-/</-'6KFL </-':L &'+- ZZp CG+(-01)5(1#/%*($*BH?)*-G&)0<KFL </-':L &'+- Zcp CG+(-01)5(1#/%*($*BHW&- V/-'0 C'*6I%&UKFL </-':L &'+- Zep CG+(-01)5(1#/%*($*BHq-$$G R-'*KFL </-':L 6-9'5$(p CG+(-01)5(1#/%*($*BHY(U-/KFL </-':L M Control Structures: Iteration (1) Often, blocks of code should loop while a condition holds (or fixed # of times) Java iteration idioms: while, do-while, for While loop: execute loop as long as condition is true (checked each iteration) Example:
C(/%*8 +(/ Q H'''''KL %*( 0%*T-*8(U Q ZbL
IU%$- B+(/1$-*8(UBF ; 0%*T-*8(UF A +(/ Q +(/ ^ H'KL M
CG+(-01)5(1#/%*($*B+(/FL
Loop executes 5 times; code terminates when +(/ Q H''''''''''K Notice: if the length of +(/ was 0%*T-*8(U, the while loop would not execute Control Structures: Iteration (2) While Loop C(/%*8 +(/ Q H''''''''''KL %*( 0%*T-*8(U Q ZbL
IU%$- B+(/1$-*8(UBF ; 0%*T-*8(UF A +(/ Q +(/ ^ H'KL M
6) A +(/ Q +(/ ^ H'KL M IU%$- B+(/1$-*8(UBF ; 0%*T-*8(UF
CG+(-01)5(1#/%*($*B+(/FL
Unlike the while loop, the do-while loop executes at least once so long as condition is true. The while loop prints '''''''''' whereas the do-while loop prints ''''''''''' (11 's) Control Structures: Iteration (3) The for loop has the following structure:
9)/ B;-d#/-++%)*Z=L ;-d#/-++%)*\=L ;-d#/-++%)*]=F A 1 1 1 M
Semantics: ;-d#/-++%)*Z= is loop initialization (run once) ;-d#/-++%)*\= is loop execution condition (checked every iteration) ;-d#/-++%)*]= is loop update (run every iteration) Example:
%*( %L 9)/ B% Q bL % ; ZbL %^^F A CG+(-01)5(1#/%*($*BH% Q K ^ %FL M CG+(-01)5(1#/%*($*BH% Q K ^ %FL
What do you think this code does? Methods and Design-by-Contract (1) Design your own methods to perform specific, well-defined tasks Each method has a signature: #5<$%& +('(%& `-(5/*.G#- 0-(U)6B#'/'0.G#-Z #'/'0Z[ l #'/'0.G#-O #'/'0OF A !! #-/9)/0 &-/('%* ('+: M Example: a method to compute area of rectangle: #5<$%& +('(%& 6)5<$- 9%*6`-&("/-'B6)5<$- $-*8(U[ 6)5<$- I%6(UF A /-(5/* $-*8(U f I%6(UL M Each method has a precondition and a postcondition Precondition: constraints methods caller must satisfy to call method Postcondition: guarantees method provides if preconditions are met For our example: Precondition: $-*8(U = b1b, I%6(U = b1b Postcondition: returns $-*8(U v I%6(U (area of rectangle) Methods and Design-by-Contract (2) In practice, methods are annotated via JavaDoc, e.g., !ff V)0#5(- '/-' )9 /-&('*8$-1
w#'/'0 $-*8(U T-*8(U )9 /-&('*8$- w#'/'0 I%6(U @%6(U )9 /-&('*8$- w/-(5/* "/-' )9 /-&('*8$- f! Methods called from 0'%*BF (which is +('(%&) need to be defined +('(%& too Some methods may not return anything (4)%6) Array Data Structure Array: fixed-length sequence of variable types; cannot change length at run-time Examples: 9%*'$ %*( O,NC.,X>O.C Q ZbL C(/%*8DE +(56-*(+L !! X-&$'/'(%)* C(/%*8DE +(56-*(+ Q *-I C(/%*8DO,NC.,X>O.CEL !! X-&$'/'(%)* '*6 %*%(%'$%x'(%)* C(/%*8DE 0)/-C(56-*(+ Q A H"$%&-K[ HR)<K[ H`)U%(K[ H@-%KML !! X-&$'/'(%)* '*6 -d#$%&%( %*%(%'$%x'(%)* CG+(-01)5(1#/%*($*B0)/-C(56-*(+1$-*8(UF !! k/%*(+ m Enhanced 9)/ loop: executed for each element in array Example: 9)/ BC(/%*8 +(56-*(p 0)/-C(56-*(+F A CG+(-01)5(1#/%*($*B+(56-*( ^ H[ KFL M Prints "$%&-[ R)<[ `)U%([ @-%[ to screen Array indices are numbered 0, , N1; watch for off-by-one errors! 0)/-C(56-*(+DbE is "$%&-; 0)/-C(56-*(+D]E is @-% Two-Dimensional Arrays We can have two-dimensional arrays. Example: 9%*'$ %*( `Y@C Q ]L 9%*'$ %*( VYT,NOC Q ]L &U'/DEDE (%&.'&.)- Q *-I &U'/D`Y@CEDVYT,NOCEL !! 6-&$'/- 9)/ B%*( % Q bL % ; `Y@CL %^^F A 9)/ B%*( 3 Q bL 3 ; VYT,NOCL 3^^F A (%&.'&.)-D%ED3E Q yPzL !! W*%(%'$%x- () y<$'*:z M M !! .%&g('&g()- $)8%& 8)-+ U-/- BI%(U y{z+[ yYz+F (%&.'&.)-1$-*8(U returns number of rows; (%&.'&.)-DbE1$-*8(U returns number of columns Higher-dimensional arrays are possible too Parameterized Data Structures We can define data structures in terms of an arbitrary variable type (call it Item). "//'GT%+(;W(-0=, a variable-length array that can be modified at run-time. Examples: "//'GT%+(;C(/%*8= '//C(/%*8+ Q *-I "//'GT%+(;C(/%*8=BFL "//'GT%+(;X)5<$-= '//X)5<$-+ Q *-I "//'GT%+(;X)5<$-=BFL '//C(/%*8+1'66BH"$%&-KFL '//C(/%*8+1'66BHR)<KFL '//C(/%*8+1'66BH`)U%(KFL '//C(/%*8+1'66BH@-%KFL C(/%*8 +(/ Q '//C(/%*8+18-(BZFL !! +(/ <-&)0-+ HR)<K '//C(/%*8+1+-(B\[ H`'3KFL !! H`'3K /-#$'&-+ H`)U%(K CG+(-01)5(1#/%*($*B'//C(/%*8+1+%x-BFFL !! #/%*(+ m Notice: Need to call %0#)/( 3'4'15(%$1"//'GT%+(L at beginning of program Off-by-one indexing: cannot call '//C(/%*8+18-(BmFL Auto-boxing: we cannot create an "//'GT%+( of 6)5<$-s. We need to replace 6)5<$- with wrapper class X)5<$-. (Recall the primitive data types table) Other parameterized data types include T%+(s, C-(s, N'#s, C('&:s, |5-5-s, ./--s (see chapters 1416 in [1]) Exception Handling (1) If we had called '//C(/%*8+18-(BmF, we would have an error condition The JVM throws an W*6-dY5(Y9R)5*6+ exception, halts execution Exception Handling (2) We handle exceptions using the try-catch-finally structure: (/G A !! V)6- (U'( &)5$6 (/%88-/ '* -d&-#(%)* M &'(&U BW*6-dY5(Y9R)5*6+>d&-#(%)* -F !! Y/ '*)(U-/ >d&-#(%)* A !! V)6- (U'( H/-+#)*6+K () -d&-#(%)*[ -181[ -1#/%*(C('&:./'&-BFL M 9%*'$$G A !! V)6- (U'( -d-&5(-+ /-8'/6$-++ )9 IU-(U-/ -d&-#(%)* )&&5/+ M There can be many &'(&U blocks for different >d&-#(%)*s, but there is only one (/G block and one (optional) 9%*'$$G block. (See Section 7.4 in [1] for the full hierarchy of >d&-#(%)*s) Exceptions always need to be caught and reported, especially in Android Outline Getting Started Java: The Basics Java: ObjectOriented Programming Android Programming Objects and Classes (1) Classes serve as blueprints that describe the states and behaviors of objects, which are actual instances of classes For example, a Vehicle class describes a motor vehicles blueprint: States: on/off, driver in seat, fuel in tank, speed, etc. Behaviors: startup, shutdown, drive forward, shift transmission, etc. There are many possible Vehicles, e.g., Honda Accord, Mack truck, etc. These are instances of the Vehicle blueprint Many Vehicle states are specific to each Vehicle object, e.g., on/off, driver in seat, fuel remaining. Other states are specific to the class of Vehicles, not any particular Vehicle (e.g., keeping track of the last Vehicle ID # assigned). These correspond to instance fields and static fields in a class. Notice: we can operate a vehicle without knowing its implementation under the hood. Similarly, a class makes public instance methods by which objects of this class can be manipulated. Other methods apply to the set of all Vehicles (e.g., set min. fuel economy). These correspond to static methods in a class Objects and Classes (2) #5<$%& &$'++ n-U%&$- A !! W*+('*&- 9%-$6+ B+)0- )0%((-6 9)/ </-4%(GF #/%4'(- <))$-'* %+Y* Q 9'$+-L #/%4'(- <))$-'* %+X/%4-/W*C-'( Q 9'$+-L #/%4'(- 6)5<$- 95-$W*.'*: Q Zb1bL #/%4'(- 6)5<$- +#--6 Q b1bL
!! W*+('*&- 0-(U)6+ B+)0- )0%((-6 9)/ </-4%(GF 10(*$- n-U%&$-BF A l M !! V)*+(/5&()/ 10(*$- 4)%6 +('/(,#BF A l M 10(*$- 4)%6 +U5(Y99BF A l M 10(*$- 4)%6 8-(W+X/%4-/W*C-'(BF A l M !! 8-((-/[ +-((-/ 0-(U)6+ 10(*$- 4)%6 +-(W+X/%4-/W*C-'(BF A l M #/%4'(- 4)%6 0'*'8-N)()/BF A l M !! N)/- #/%4'(- 0-(U)6+ l
!! C('(%& 0-(U)6+ 10(*$- +('(%& 4)%6 +-(n%*BC(/%*8 *-In%*F A l M M Objects and Classes (3) How to use the n-U%&$- class: First, create a new object via constructor n-U%&$-BF, e.g., n-U%&$- 0GV'/ Q *-I n-U%&$-BFL Change Vehicle states, e.g., +('/(,#BF or +U5(Y99BF the n-U%&$- You can imagine other use cases Mark a new n-U%&$-s ID number (VIN) as taken by calling n-U%&$-1+-(n%*BlF Caveat: VINs more complex than this (simple) implementation [7] Notes: Aliasing: If we set n-U%&$- 0G./5&: Q 0GV'/, both 0GV'/ and 0G./5&: point to the same variable. Better to perform deep copy of 0GV'/ and store the copy in 0G./5&: *5$$ reference: refers to no object, cannot invoke methods on *5$$ Implicit parameter and the (U%+ reference Access control: public, protected, private Inheritance (1) Types of n-U%&$-s: N)()/&G&$-, V'/, ./5&:, etc. Types of V'/s: C-6'*, V)5#-, C,n. Types of ./5&:s: k%&:5#, S$'(<-6. Induces inheritance hierarchy Subclasses inherit fields/methods from superclasses. Subclasses can add new fields/methods, override those of parent classes For example, N)()/&G&$-s 6/%4-S)/I'/6BF method differs from ./5&:s 6/%4-S)/I'/6BF method Inheritance (2) #5<$%& &$'++ n-U%&$- A l #5<$%& 4)%6 6/%4-S)/I'/6 B6)5<$- +#--6F A !! R'+- &$'++ 0-(U)6 M M #5<$%& &$'++ N)()/&G&$- +2"+%/3 n-U%&$- A l #5<$%& 4)%6 6/%4-S)/I'/6 B6)5<$- +#--6F A !! "##$G #)I-/l M M Inheritance denoted via -d(-*6+ keyword Inheritance (3) #5<$%& &$'++ ./5&: -d(-*6+ n-U%&$- A #/%4'(- <))$-'* 5+-"I6 Q (/5-L l #5<$%& ./5&:B<))$-'* 5+-"I6F A (U%+15+-"I6 Q 5+-"I6L M l #5<$%& 4)%6 6/%4-S)/I'/6B6)5<$- +#--6F A %9 B5+-"I6F A !! "##$G #)I-/ () '$$ IU--$+l M -$+- A !! "##$G #)I-/ () )*$G 9/)*(!<'&: IU--$+l M M M Polymorphism Suppose we create n-U%&$-s and invoke the 6/%4-S)/I'/6BF method: n-U%&$- 4-U%&$- Q *-I n-U%&$-BFL n-U%&$- 0)()/&G&$- Q *-I N)()/&G&$-BFL ./5&: (/5&:Z Q *-I ./5&:B(/5-FL n-U%&$- (/5&:\ Q *-I ./5&:B9'$+-FL !! V)6- U-/- () +('/( 4-U%&$-+l 4-U%&$-16/%4-S)/I'/6Bc1bFL 0)()/&G&$-16/%4-S)/I'/6BZb1bFL (/5&:Z16/%4-S)/I'/6BZc1bFL (/5&:\16/%4-S)/I'/6BZb1bFL For 4-U%&$-, n-U%&$-s 6/%4-S)/I'/6() method is invoked For 0)()/&G&$-, N)()/&G&$-s 6/%4-S)/I'/6BF method is invoked With (/5&:Z and (/5&:\, ./5&:s 6/%4-S)/I'/6BF function is invoked (with all-wheel drive for (/5&:Z, not for (/5&:\). Dynamic method lookup: Java looks at objects actual types in determining which method to invoke Polymorphism: feature where objects of different subclasses can be treated the same way. All n-U%&$-s 6/%4-S)/I'/6BF regardless of (sub)class. The Y<3-&( Class Every class in Java is a subclass of Y<3-&( Important methods in Y<3-&(: ()C(/%*8BF: Converts the Y<3-&( into a C(/%*8 representation -_5'$+BF: Compares contents of Y<3-&(s to see if theyre the same U'+UV)6-BF: Hashes the Y<3-&( to a fixed-length C(/%*8, useful for data structures like ?'+UN'#, ?'+UC-( If you create your own class, you should override ()C(/%*8BF and U'+UV)6-BF Interfaces Java interfaces abstractly specify methods to be implemented Intuition: decouple method definitions from implementations (clean design) Interfaces, implementations denoted by %*(-/9'&-, %0#$-0-*(+ keywords Example:
#5<$%& %*(-/9'&- X/%4-'<$- A #5<$%& 4)%6 6/%4-S)/I'/6B6)5<$- +#--6FL M
#5<$%& &$'++ n-U%&$- %0#$-0-*(+ X/%4-'<$- A #5<$%& 4)%6 6/%4-S)/I'/6B6)5<$- +#--6F A !! %0#$-0-*('(%)* M M
#5<$%& &$'++ N)()/&G&$- -d(-*6+ n-U%&$- %0#$-0-*(+ X/%4-'<$- A #5<$%& 4)%6 6/%4-S)/I'/6B6)5<$- +#--6F A !! %0#$-0-*('(%)* M M The V)0#'/'<$- Interface Comparing Y<3-&(s is important, e.g., sorting in data structures The V)0#'/'<$- interface compares two Y<3-&(s, e.g., ' and <: #5<$%& %*(-/9'&- V)0#'/'<$- A %*( &)0#'/-.)BY<3-&( )(U-/Y<3-&(FL M '1&)0#'/-.)B<F returns negative integer if ' comes before <, b if ' is the same as <, and a positive integer otherwise In your classes, you should implement V)0#'/'<$- to facilitate Y<3-&( comparison Object-Oriented Design Principles Each class should represent a single concept Dont try to fit all functionality into a single class Consider a class per noun in problem description Factor functionality into classes, interfaces, etc. that express the functionality with minimal coupling For software projects, start from use cases (how customers will use software: high level) Then identify classes of interest In each class, identify fields and methods Class relationships should be identified: is-a (inheritance), has-a (aggregation), implements interface, etc. Packages provide class organization mechanism Examples: java.lang.*, java.util.*, etc. Critical for organizing large numbers of classes! All classes in a package can see each other (scope) Outline Getting Started Java: The Basics Java: ObjectOriented Programming Android Programming Introduction to Android Popular mobile device OS: 52% of U.S. smartphone market [8] Developed by Open Handset Alliance, led by Google Google claims 900,000 Android device activations [9] Source: [8] Android Highlights (1) Android apps execute on Dalvik VM, a clean-room implementation of JVM Dalvik optimized for efficient execution Dalvik: register-based VM, unlike Oracles stack-based JVM Java .class bytecode translated to Dalvik EXecutable (DEX) bytecode, which Dalvik interprets Android Highlights (2) Android apps written in Java 5 Actually, a Java dialect (Apache Harmony) Everything weve learned still holds Apps use four main components: "&(%4%(G: A single screen thats visible to user C-/4%&-: Long-running background part of app (not separate process or thread) V)*(-*(k/)4%6-/: Manages app data (usually stored in database) and data access for queries R/)'6&'+(`-&-%4-/: Component that listens for particular Android system events, e.g., found wireless device, and responds accordingly App Manifest Every Android app must include an "*6/)%6N'*%9-+(1d0$ file describing functionality The manifest specifies: Apps Activities, Services, etc. Permissions requested by app Minimum API required Hardware features required, e.g., camera with autofocus External libraries to which app is linked, e.g., Google Maps library Activity Lifecycle "&(%4%(G: key building block of Android apps Extend "&(%4%(G class, override )*V/-'(-BF, )*k'5+-BF, )*`-+50-BF methods Dalvik VM can stop any "&(%4%(G without warning, so saving state is important! Activities need to be responsive, otherwise Android shows user App Not Responsive warning: Place lengthy operations in .U/-'6s, "+G*&.'+:s Source: [12] App Creation Checklist If you own an Android device: Ensure drivers are installed Enable developer options on device under Settings, specifically USB Debugging Android 4.2, 4.3: Go to Settings!About phone, press Build number 7 times to enable developer options For Eclipse: Make sure youve enabled LogCat, Devices views. Click a connected device in Devices to see its log Programs should log states via '*6/)%615(%$1T)8s T)816B"kkP."uPC.`[ H6-<58KF, where "kkP."uPC.` is a 9%*'$ C(/%*8 tag denoting your app Other commands: T)81-BF (error); T)81%BF (info); T)81IBF (warning); T)814BF (verbose) same parameters Creating Android App (1) Creating Android app project in Eclipse: Go to File!New!Other, select Android Application Project (Android folder), click Next Enter app, project name Choose package name using reverse URL notation, e.g., -651)+510G'## Select APIs for app, then click Next Creating Android App (2) Click Next for the next two windows Youll see the Create Activity window. Select Blank Activity and click Next. Enter Activitys name and click Finish This automatically creates Hello World app Deploying the App Two choices for deployment: Real Android device Android virtual device Plug in your real device; otherwise, create an Android virtual device Emulator is slow. Try Intel accelerated version, or perhaps U((#p!!III18-*G0)(%)*1&)0! Run the app: right click project name, select Run As!Android Application Underlying Source Code #'&:'8- -651)+51U-$$)'*6/)%6L
#5<$%& &$'++ N'%*"&(%4%(G -d(-*6+ "&(%4%(G A wY4-//%6- #/)(-&(-6 4)%6 )*V/-'(-BR5*6$- +'4-6W*+('*&-C('(-F A +5#-/1)*V/-'(-B+'4-6W*+('*&-C('(-FL +-(V)*(-*(n%-IB`1$'G)5(1'&(%4%(GP0'%*FL M
;'##$%&'(%)* '*6/)%6p'$$)IR'&:5#Q!#/B)! '*6/)%6p%&)*Q!6./+>+H4)&1(54+B-(")/! '*6/)%6p$'<-$Q!6'#/1-9&+$$5-+*)! '*6/)%6p(U-0-Q!6'#84)&<$$I")*)! = ;'&(%4%(G '*6/)%6p*'0-Q!).B,0'B,")440+-./01.,;+1-<(#171#8! '*6/)%6p$'<-$Q!6'#/1-9&+$$5-+*)! = ;%*(-*(g9%$(-/= ;'&(%)* '*6/)%6p*'0-Q!+-./01.,1-#)-#,+(#10-,;<JK! &= ;&'(-8)/G '*6/)%6p*'0-Q!+-./01.,1-#)-#,(+#)90/8,L<MKNOPQ! &= ;!%*(-*(g9%$(-/= ;!'&(%4%(G= ;!'##$%&'(%)*= ;!0'*%9-+(= 7%/#)$/6,%$>+3":2=* A More Interesting App Well now examine an app with more features: WiFi Tester (code on class website) Press a button, scan for WiFi access points (APs), display them Underlying Source Code (1) wY4-//%6- 10(*$- 8)$/ )%?#+,"+@A0%/*+ 3,8+/B%3",%-+!","+C A 301+#:)%?#+,"+@3,8+/B%3",%-+!","+CD +-(V)*(-*(n%-IB`1$'G)5(1+(#171#85>15C1RS
!! C-( 5# W*(-*(S%$(-/ 9)/ @%S% +&'* /-+5$(+ '4'%$'<$- W*(-*(1 0W*(-*(S%$(-/ Q %+E B%"+%"M$*"+#@CD 0W*(-*(S%$(-/1'66"&(%)*B@%9%N'*'8-/1VN<K5QPVMLIV5<W<JL<XLP5<NIJYKRS M Underlying Source Code (2) Code much more complex First get system @%9%N'*'8-/ Create listener Y<3-&( for button that performs scans We register Broadcast Receiver, 0`-&-%4-/, to listen for @%9%N'*'8-/s finished scan system event (expressed as W*(-*( @%9%N'*'8-/1CV"OP`>C,T.CP "n"WT"RT>P"V.WYO) Unregister Broadcast Receiver when leaving "&(%4%(G wY4-//%6- 1#)"+-"+/ 8)$/ )%N+30=+@C A 301+#:)%N+30=+@CD /-8%+(-/`-&-%4-/B0`-&-%4-/[ 0W*(-*(S%$(-/FL M
wY4-//%6- 1#)"+-"+/ 8)$/ )%O,03+@C A 301+#:)%O,03+@CD 5*/-8%+(-/`-&-%4-/B0`-&-%4-/FL M
The Broadcast Receiver #/%4'(- 9%*'$ R/)'6&'+(`-&-%4-/ 0`-&-%4-/ Q *-I R/)'6&'+(`-&-%4-/BF A wY4-//%6- #5<$%& 4)%6 )*`-&-%4-BV)*(-d( &)*(-d([ W*(-*( %*(-*(F A C(/%*8 '&(%)* Q %*(-*(18-("&(%)*BFL %9 B@%9%N'*'8-/1CV"OP`>C,T.CP"n"WT"RT>P"V.WYO1-_5'$+B'&(%)*FF A T)81-B."u[ C&'* /-+5$(+ '4'%$'<$-FL T%+(;C&'*`-+5$(= +&'*`-+5$(+ Q 0@%9%N'*'8-/18-(C&'*`-+5$(+BFL 0"#C(/ Q L 9)/ BC&'*`-+5$( /-+5$( p +&'*`-+5$(+F A 0"#C(/ Q 0"#C(/ ^ /-+5$(1CCWX ^ L L 0"#C(/ Q 0"#C(/ ^ /-+5$(1RCCWX ^ L L 0"#C(/ Q 0"#C(/ ^ /-+5$(1&'#'<%$%(%-+ ^ L L 0"#C(/ Q 0"#C(/ ^ /-+5$(19/-_5-*&G ^ N?xLL 0"#C(/ Q 0"#C(/ ^ /-+5$(1$-4-$ ^ 6R0a*a*L M !! ,#6'(- ,W () +U)I '$$ (U%+ %*9)/0'(%)*1 +-(.-d(n%-IB0"#C(/FL M M ML User Interface Updating UI in code 1#$8,"+ 8)$/ 3+"P+2"F$+E@!"#$%& 3"#C A .-d(n%-I (4 Q B.-d(n%-IF 9%*6n%-IRGW6B`1%61#)Z#71)>RL (41+-(N)4-0-*(N-(U)6B%+E !-#)**$%&6)8+=+%"6+".)/@CCD (41+-(.-d(B+(/FL M
This code simply has the UI display all collected WiFi APs, makes the text information scrollable UI Layout (XML) ;T%*-'/T'G)5( d0$*+p'*6/)%6Q!"##$%&&'(")*+',+-./01.,(0*&+$2& /)'&+-./01.! d0$*+p())$+Q!"##$%&&'(")*+',+-./01.,(0*'! '*6/)%6p$'G)5(PI%6(UQ!C1445$+/)-#! '*6/)%6p$'G)5(PU-%8U(Q!C1445$+/)-#! '*6/)%6p)/%-*('(%)*Q!7)/#1(+4!=
Android Programming Notes Android apps have multiple points of entry: no 0'%*BF method Cannot sleep in Android During each entrance, certain Y<3-&(s may be *5$$ Defensive programming is very useful to avoid crashes, e.g., %9 BJB0GY<3 QQ *5$$FF A !! 6) +)0-(U%*8 M Java concurrency techniques are required Dont block the main thread in Activities Implement long-running tasks such as network connections asynchronously, e.g., as "+G*&.'+:s Recommendation: read [4]; chapter 20 [10]; [11] Logging state via '*6/)%615(%$1T)8 throughout app is essential when debugging (finding root causes) Better to have too many permissions than too few Otherwise, app crashes due to security exceptions! Remove unnecessary permissions before releasing app to public Event handling in Android GUIs entails many listener Y<3-&(s Concurrency: .U/-'6s (1) .U/-'6: program unit (within process) executing independently Basic idea: create class that implements `5**'<$- interface `5**'<$- has one method, /5*BF, that contains code to be executed Example: #5<$%& &$'++ Y5/`5**'<$- %0#$-0-*(+ `5**'<$- A #5<$%& 4)%6 /5*BF A !! /5* &)6- M M Create a .U/-'6 object from `5**'<$- and +('/(BF .U/-'6, e.g., `5**'<$- / Q *-I Y5/`5**'<$-BFL .U/-'6 ( Q *-I .U/-'6B/FL (1+('/(BFL Problem: this is cumbersome unless .U/-'6 code is reused Concurrency: .U/-'6s (2) Easier approach: anonymous inner classes, e.g., .U/-'6 ( Q *-I .U/-'6B*-I `5**'<$-B A #5<$%& 4)%6 /5*BF A !! &)6- () /5* M MFL (1+('/(BFL Idiom essential for one-time network connections in Activities However, Threads can be difficult to synchronize, especially with UI thread in Activity. AsyncTasks are better suited for this Concurrency: AsyncTasks "+G*&.'+: encapsulates asynchronous task that interacts with UI thread in "&(%4%(G: #5<$%& &$'++ "+G*&.'+:;k'/'0+[ k/)8/-++[ `-+5$(= A #/)(-&(-6 `-+5$( 6)W*R'&:8/)5*6Bk'/'0.G#- #'/'0F A !! &)6- () /5* %* <'&:8/)5*6 #5<$%+Uk/)8/-++Bk/)8/-++.G#- #/)8/-++FL !! ,W l /-(5/* `-+5$(L M
#/)(-&(-6 4)%6 )*k/)8/-++,#6'(-Bk/)8/-++.G#- #/)8/-++F A !! %*4):- 0-(U)6 %* "&(%4%(G () 5#6'(- ,W M M Extend "+G*&.'+: with your own class Documentation at http://developer.android.com Thank You Any questions? References (1) 1. C. Horstmann, Big Java Late Objects, Wiley, 2012. Online: http://proquest.safaribooksonline. com.proxy.lib.ohiostate.edu/book//9781118087886 2. J. Bloch, Effective Java, 2nd ed., AddisonWesley, 2008. Online: http://proquest. safaribooksonline.com.proxy.lib.ohiostate.edu/book/programming/java/9780137150021 3. S.B. Zakhour, S. Kannan, and R. Gallardo, The Java Tutorial: A Short Course on the Basics, 5th ed., AddisonWesley, 2013. Online: http://proquest.safaribooksonline.com.proxy.lib. ohiostate.edu/book/programming/java/9780132761987 4. C. Collins, M. Galpin, and M. Kaeppler, Android in Practice, Manning, 2011. Online: http://proquest.safaribooksonline.com.proxy.lib.ohiostate.edu/book/programming/android/ 9781935182924 5. M.L. Sichitiu, 2011, http://www.ece.ncsu.edu/wireless/MadeInWALAN/AndroidTutorial/PPTs/ javaReview.ppt 6. Oracle, http://docs.oracle.com/javase/1.5.0/docs/api/index.html 7. Wikipedia, https://en.wikipedia.org/wiki/Vehicle_Identification_Number 8. Nielsen Co., Whos Winning the U.S. Smartphone Market?, 6 Aug. 2013, http://www.nielsen.com/us/en/newswire/2013/whos-winning-the-u-s-smartphone-market-.html 9. Android Open Source Project, http://www.android.com References (2) 10. http://bcs.wiley.com/he-bcs/Books?action=index&itemId=1118087887&bcsId=7006 11. B. Goetz, T. Peierls, J. Bloch, J. Bowbeer, D. Holmes, and D. Lea, Java Concurrency in Practice, Addison-Wesley, 2006, online at http://proquest.safaribooksonline.com/book/programming/java/0321349601 12. https://developer.android.com/guide/components/activities.html 13. https://developer.android.com/guide/topics/ui/declaring-layout.html#CommonLayouts