Tutorial: Programming in Java for Android Development 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
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Tutorial: Programming in Javafor Android Development
Adam C. Champion and Dong Xuan
CSE 4471: Information SecurityAutumn 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
Our First Java Program (1)#5<$%& &$'++ ?-$$)@)/$6A
#5<$%& +('(%& 4)%6 0'%*BC(/%*8DE '/8+FA
CG+(-01)5(1#/%*($*BH?-$$) I)/$6JKFLM
M
• Don’t 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 inPackage Explorer. Right–click +/& directory, select New ! Class ,and create a class ?-$$)@)/$6 with a 0'%*BF method. To run the
program, right–click HelloWorld project, click Run As
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 – We’ll 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, floating–point variables: their values are subsets of
values of mathematical integers, real numbers. Cannot assignmathematical 2500 to integer variable (limited range) or mathematical ! 2to a floating–point 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.,
Common Operators in Java!"#$%& ())*+,% -.,# $%" /)0(*+
J ^^ gg^ hh ^ g ^ g
ii f ! j f !; =;Q =QQQ JQ
; =;Q =QQQ 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 isS"TC>, the second part of the expression won’t be evaluated.
• The second operand of j (integer modulus) must be positive.• Don’t compare 6)5<$- s for equality. Instead, define a constant like so:
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(UFA
+(/ Q +(/ ^ H'KLM
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
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)
Semantics: – ;-d#/-++%)*Z= is loop initialization (run once) – ;-d#/-++%)*\= is loop execution condition (checked every iteration) – ;-d#/-++%)*]= is loop update (run every iteration)
• Example:
%*( %L9)/ B% Q bL % ; ZbL %^^FA
CG+(-01)5(1#/%*($*BH% Q K ^ %FLMCG+(-01)5(1#/%*($*BH% Q K ^ %FL
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 #'/'0OFA
!! #-/9)/0 &-/('%* ('+:M
• Example: a method to compute area of rectangle:#5<$%& +('(%& 6)5<$- 9%*6`-&("/-'B6)5<$- $-*8(U[ 6)5<$- I%6(UFA
/-(5/* $-*8(U f I%6(ULM
• Each method has a precondition and a postcondition – Precondition: constraints method’s 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)
• 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 toreplace 6)5<$- with wrapper class X)5<$- . (Recall the “primitive datatypes” table)
• Other parameterized data types include T%+(s, C-( s, N'# s, C('&: s,|5-5- s, ./-- s (see chapters 14–16 in [1])
• There can be many &'(&U blocks for different >d&-#(%)* s, but there is onlyone (/G block and one (optional) 9%*'$$G block. (See Section 7.4 in [1] forthe full “hierarchy” of >d&-#(%)* s)
• Exceptions always need to be caught and “reported”, especially in Android
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 vehicle’s 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. Theseare instances of the Vehicle blueprint
• Many Vehicle states are specific to each Vehicle object, e.g., on/off, driver inseat, 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 objectsof 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
!! W*+('*&- 0-(U)6+ B+)0- )0%((-6 9)/ </-4%(GF10(*$- n-U%&$-BF A l M !! V)*+(/5&()/10(*$- 4)%6 +('/(,#BF A l M10(*$- 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
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 callingn-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” of0GV'/ and store the copy in 0G./5&:
– *5$$ reference: refers to no object, cannot invoke methods on *5$$ – Implicit parameter and the (U%+ reference
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
• 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.
Object-Oriented Design Principles• Each class should represent a single concept
– Don’t 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)
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
– Don’t 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 essentialwhen 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
safaribooksonline.com.proxy.lib.ohio–state.edu/book/programming/java/9780137150021 3. S.B. Zakhour, S. Kannan, and R. Gallardo, The Java® Tutorial: A Short Course on the Basics ,
4. C. Collins, M. Galpin, and M. Kaeppler, Android in Practice , Manning, 2011. Online:http://proquest.safaribooksonline.com.proxy.lib.ohio–state.edu/book/programming/android/9781935182924
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