You are on page 1of 38

JAVA PROGRAMMING

FOR
ANDROID DEVELOPMENT

1
Outline
• Getting Started
• Java: The Basics
• Java: Object–Oriented Programming

2
Getting Started
• (1)
Need to install Java Dev. Kit (JDK) to write Java
(Android) programs
– Don’t install Java Runtime Env. (JRE); JDK is different!
– Newer versions of JDK can cause issues with Android
• Can download JDK (free):
– Oracle’s JDK (http://java.oracle.com) free for dev. only;
payment for commercial use
• Alternatively, for macOS, Linux:
• macOS: Install Homebrew (http://brew.sh), then type
brew cask i n f o adoptopenjdk8 at command line
• Linux: Type sudo apt i n s t a l l d e f a u lt – j d k at
command line (Debian, Ubuntu)
3
Outline
• Getting Started
• Java: The Basics
• Java: Object–Oriented Programming

4
Java Programming

Language
Java: general-purpose
language: “write
code once, run
anywhere”
• The key: Java Virtual
Machine (JVM)
– Program code compiled
to JVM bytecode
– JVM bytecode
interpreted on JVM

5
Our First Java Program
p u b l i c class HelloWorld {
public s t a t i c void m a i n ( S t r i n g [ ] args)
{ System.out.println(“Hello
world!”);
}
}

• Don’t forget to match curly braces { ,}


or semicolon at the end!
• Recommended IDEs:
– IntelliJ IDEA CE (free;
http://www.jetbrains.com/student) 6
Explaining the
• Every . j a v aProgram
source file contains one class
– We create a class HelloWorld that greets user
– The class HelloWorld must have the same name as the source file
HelloWorld.java
– Our class has p u b l i c scope, so other classes can “see” it
– We’ll talk more about classes and objects later
• Every Java program has a method main() that executes the program
– Method “signature” must be exactly public static void main(String[] args) { }
– This means: (1) main() is “visible” to other methods; (2) there is “only one”
main() method in the class; and (3) main() has one argument ( args , an array of
S t r i n g variables)
– Java “thinks” main() , Main() , miAN() are different methods
• Every Java method has curly braces { , } surrounding its code
• Every statement in Java ends with a semicolon, e.g.,
Sy s t e m . o u t . p r i n t l n ( “ H e l l o world!”);
• Program prints “ Hello world! ” to the console, then quits
7
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 t r u e or f a l s e
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 assign
mathematical 2500 to integer variable (limited range) or mathematical √2
to a floating–point variable (limited precision; irrational number).
– Variable names must start with lowercase letter, contain only letters,
numbers, _
• Variable declaration: boolean b = t r u e ;
• Later in the program, we might assign f a l s e to b: b = f a l s e ;
• Java strongly suggests that variables be initialized at the time of
declaration, e.g., boolean b ; gives a compiler warning ( n u l l pointer)
• Constants defined using f i n a l keyword, e.g.,
f i n a l boolean falseBool = FALSE;

8
Basic Data Types (2)
• Java’s primitive data types: [5]

Primitive type Size Minimum Maximum Wrapper type


boolean 1–bit N/A N/A Boolean
char 16–bit Unicode 0 Unicode 216 – 1 Character
b yt e 8–bit –128 +127 Byte
short 16–bit –215 +215 – 1 Short
int 32–bit –231 +231 – 1 Integer
lo n g 64–bit –263 +263 – 1 Long
float 32–bit IEEE 754 IEEE 754 Float
double 64–bit IEEE 754 IEEE 754 Double

Note: All these types are signed, except char. 12


Basic Data Types (3)
• Sometimes variables need to be cast to another type, e.g.,
if finding average of integers:
i n t intOne = 1 , intTwo = 2 , intThree = 3 , numInts = 2 ;
double doubOne = (double)intOne, doubTwo = (double)myIntTwo, doubThree =
(doubl e)i nt Thr ee;
double avg = (doubOne + doubTwo + doubThree)/(double)numInts;

• Math library has math operations like s q r t ( ) , pow() , etc.


• St rin g : immutable type for sequence of characters
– Every Java variable can be converted to S t r i n g via
toString()
– The + operation concatenates St rin g s with other variables
– Let s t r be a St rin g . We can find str ’s length
( s t r. l e n g t h ( ) ), substrings of s t r ( s t r. s u b s t r i n g ( ) ), and so
on [6] 10
Basic Data Types (4)
• A literal is a “fixed” value of a variable type
– TRUE, FALSE are boolean literals
– ‘ A’ , ‘ \ t ’ , ‘ \ ” ’ , and ‘ \ u 0 3 c 0 ’ are char literals
(escaped tab, quote characters, Unicode value for
π)
– –1, 0, 035, 0x1a are i n t literals (last two are octal
and hexadecimal)
– 0.5 , 1.0 , 1E6, 6.023E23 are double literals
– “ A t OSU”, “ H e l l o w o r l d ! ” are S t r i n g literals
• Comments:
– Single-line: / / some comment t o end o f
line
– Multi-line: / * comments span m u l t i p l e 11
Common Operators in
String boolean char int
Java! double + --
+
+ || + - + -
&& * / % * /
<> < > < >
< >= < >=
= =
=!= = !=
= =
Notes:
• Compare S t r i n g objects using the e qu als() method, not == or ! =
• && and | | use short-circuit evaluation. Example: boolean canPigsFly = FALSE; we
evaluate ( canPigsFly && <some Boolean expression> ). Since canPigsFly is FALSE,
the second part of the expression won’t be evaluated.
• The second operand of % (integer modulus) must be positive.
• Don’t compare double s for equality. Instead, define a constant like so:
f i n a l double EPSILON = 1E-6; / / o r some other threshold
… / / check i f Math.abs(double1 – double2) < EPSILON 15
Control Structures: Decision
• (1)
Programs don’t always follow “straight line” execution;
they “branch” based on certain conditions
• Java decision idioms: if-then-else, switch
• if-then-else idiom:
if (<some Boolean expression>) {
// take some a c t i o n
}
else i f (<some other Boolean expression) {
// take some other a c t i o n
}
else {
// do something else
}

13
Control Structures: Decision
• (2)
Example:
final double OLD_DROID = 5.0, f i n a l double NEW_DROID =
9.0; double myDroid = 8.1;
if (myDroid < OLD_DROID)
{
System.out.println(“Antique!”);
}
else i f (myDroid > NEW_DROID)
{
S y s t e m. o u t . p ri n t l n ( “Ve r y modern!”);
}
else
{
S y st e m. o u t . p r in t l n ( “Yo u r device: barely
supported.”);
}

• Code prints “Very modern!” to the screen.


• What if myDroid == 4.1 ? myDroid == 10.0 ?
14
Control Structures: Decision
• (3)two:
Example
final double JELLY_BEAN = 4 . 1 , f i n a l double ICE_CREAM =
4.0; f i n a l double EPSILON = 1E-6;
double myDroid = 4 . 1 ;
if (myDroid > ICE_CREAM) {
i f ( Math.abs( myDroid – ICE_CREAM) <
EPSILON) { S y s t e m . o u t . p r i n t l n ( “ I c e Cream
Sandwich”);
}
else {
System.out.println(“Jelly
Bean”);
}
}
else {
System.out.println(“Old version”);
}

• Code prints “ J e l l y Bean” to screen. Note nested if-then-else, 15


EPSILON usage.
Control Structures: Decision

(4)
Other idiom: switch
• Only works when comparing an i n t or boolean
variable against a fixed set of alternatives
• Example:
int ap i =
10; switch
( api )case
{ 3: S y s te m .ou t. pr in tl n (“Cupcake”) ; break;
case 4 : S y s t e m . o u t . p r i n t l n ( “ D o n u t ” ) ; break;
case 7 : S y s t e m . o u t . p r i n t l n ( “ É c l a i r ” ) ; break;
case 8 : S y s t e m . o u t . p r i n t l n ( “ F r o y o ” ) ; break;
case 1 0 : Sy s te m. out . pr int ln ( “ Gingerbread” ) ; break;
case 11: System.out.println(“Honeycomb”); break;
case 1 5 : Sy s te m. out . pr int ln ( “ Ice Cream Sandwich” ) ; break;
case 16: S y s t e m . o u t . p r i n t l n ( “ J e l l y Bean”); break;
default: Sy s te m. out . pr int ln ( “ Other” ) ; break; 19
}
Control Structures: Iteration
• (1)blocks of code loop while a condition holds (or fixed # of times)
Often,
• Java iteration idioms: while, do-while, for
• While loop: execute loop as long as condition is true (checked each iteration)
• Example:
String s t r =
“ aaaaa” ; i n t
minLength = 10;
while
( s t r. l e n g t h ( )
<
minLength)
{
str = str
+ “a”;
}
System.out.println(s 17
tr);
Control Structures: Iteration
(2)
While Loop Do-While Loop
String s t r = String s t r =
“ aaaaaaaaaa” ; i n t “ aaaaaaaaaa” ; i n t
minLength = 10; minLength = 10;
while ( s t r. l e n g t h ( ) do {
< minLength) { str = str +
str = str + “a”;
“a”; } while ( s t r. l e n g t h ( )
} < minLength)
System.out.println(str); System.out.println(str);

Unlike the while loop, the do-while loop executes at least once so long as condition is true.
The while loop prints “aaaaaaaaaa” whereas the do-while loop prints “aaaaaaaaaaa” (11 as)
18
Control Structures: Iteration
• (3)
The for loop has the following structure:
f o r (<expression1>; <expression2>; <expression3>) {
. . .
}

• Semantics:
– <expression1> is loop initialization (run once)
– <expression2> is loop execution condition (checked every iteration)
– <expression3> is loop update (run every iteration)
• Example:
int i ;
f o r ( i = 0 ; i < 10; i + + )
{ System.out.println(“i = ” +
i);
}
System.out.println(“i = ” + i ) ;

• What do you think this code does?


19
Methods and Design-by-Contract
• (1) your own methods to perform specific, well-defined tasks
Design
• Each method has a signature:
public s t a t i c ReturnType method(paramType1 param1, …
paramTypeN paramN) {
// perform c e r t a i n task
}
• Example: a method to compute area of rectangle:
public s t a t i c double findRectArea(double l e n g t h ,
double w i d t h ) {
return length * w i d t h ;
}
• 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: leng th > 0.0, width > 0.0
– Postcondition: returns leng th × width (area of rectangle)
20
Methods and Design-by-Contract
(2)
• In practice, methods are annotated via JavaDoc,
e.g.,
/**
Compute area o f r e c t a n g l e .

@param length Length o f


rectangle @param
width Width o f
rectangle @return Area o f
rectangle
*/
• Methods called from main() (which is
s t a t i c ) need to be defined s t a t i c too
• Some methods may not return anything
( void ) 21
Array Data Structure
• Array: fixed-length sequence of variable types; cannot change length at run-time
Examples:
f i n a l i n t NUMSTUDENTS = 10;
S t r i n g [ ] students; / / Declaration
S t r i n g [ ] students = new
String[NUMSTUDENTS];
/ / Declaration and
initialization
S t r i n g [ ] moreStudents = { “ A l i c e ” ,
“Bob”, “ R o h i t ” , “ We i ” } ;
/ / Declaration and e x p l i c i t i n i t i a l i z a t i o n
System.out.println(moreStudents.length) / / P r i n t s 4
• Enhanced f o r loop: executed for each element in array
Example:
f o r ( S t r i n g stude nt : moreStudents)
{ S ystem.out . pr int ln (st udent + “ ,
”);
} moreStudents[0] is “ Alice ”; moreStudents[3] is 25
Two-Dimensional Arrays
• We can have two-dimensional arrays.
Example:
final i n t ROWS = 3 ; f i n a l i n t
COLUMNS = 3;
char[][] ticTacToe = new char[ROWS][COLUMNS];
/ / declare
for ( i n t i = 0 ; i < ROWS; i + + ) {
for (int j = 0; j < COLUMNS; j+
+ ) { ticTacToe[ i ] [ j ] = ‘_’; //
I n i t i a l i z e to ‘blank’
}
}
// Ti c - t a c - t o e l o g i c goes here ( w i t h ‘ X ’ s , ‘ O ’ s )
• ticTacToe.length returns number of rows;
ticTacToe[0].length returns number of columns
• Higher-dimensional arrays are possible too 23
Parameterized Data Structures
• We can define data structures in terms of an arbitrary variable type
(call it Item).
• ArrayList<Item> , a variable-length array that can be modified at
run-time. Examples:
ArrayList<String> a r r S t r i n g s = new A r r a y L i s t < S t r i n g > ( ) ;
ArrayList<Double> arrDoubles = new ArrayList<Double>();
a r r S t r i n g s . a d d ( “ A l i c e ” ) ; a r r S t r i n gs . a d d ( “ B o b” ) ; a r r S t r i n g s . a d d ( “ R o h i t ” ) ;
a r r S t r i ng s . a dd ( “ We i ” ) ;
S t r i n g s t r = a r r S t r i n g s . g e t ( 1 ) ; / / s t r becomes “Bob”
a r r S t r i n g s . s e t ( 2 , “ R a j ” ) ; / / “ R a j ” replaces “ R o h i t ”
System.out.println(arrStrings.size()); / / prints 4
• Notice:
– Need to call import j a v a . u t i l . A r r a y L i s t ; at
beginning of program
– Off-by-one indexing: cannot call
arrStrings.get(4);
– Auto-boxing: we cannot create an A r r a y L i s t of doubles. We need to
replace double with wrapper class Double. (Recall the “primitive data
types” table)
• Other parameterized data types include L i s t s, Sets, Maps, 24
Stack s, Queues, Tree s (see chapters 14–16 in [1])
Exception Handling
(1)
• If we had called a r r S t r i n g s . g e t ( 4 ) , we
would have an error condition
– The JVM throws an IndexOutOfBounds
exception, halts execution

25
Exception Handling
• (2) using the try-catch-finally structure:
We handle exceptions
try {
// Code t h a t could t r i g g e r an exception
}
catch (IndexOutOfBoundsException e ) { / / Or another
Exception
// Code t h a t “responds” t o
exception, e . g . , e . p r i n t S t a c k Tr a c e ( ) ;
}
finally {
// Code executes regardless o f
whether exception occurs
}
• There can be many catch blocks for different Exception s, but there is
only one t r y block and one (optional) f i n a l l y block. (See Section 7.4 in
[1] for the full hierarchy of Exception s)
• Exceptions always need to be caught and “reported”, especially in Android

26
Outline
• Getting Started
• Java: The Basics
• Java: Object–Oriented Programming

27
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.
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
31
a class
Objects and Classes (2)
p u b l i c class Vehicle {
/ / Instance f i e l d s (some omitted f o r b r e v i t y )
private boolean isOn = f a l s e ;
private boolean i sDriv erInSeat = f a l s e ;
p r i v a t e double fuelInTank = 10.0;
p r i v a t e double speed = 0 . 0 ;
/ / Static fi e l ds
private s t a t i c S t r i n g l a s t Vi n =
“4A4AP3AU*DE999998”;
/ / Instance methods (some omitted f o r
brevity)
public Ve h i c l e ( ) { … } / / Constructor
public void s t a r t U p ( ) { … }
public void s h u t O f f ( ) { … }
public void ge tIs D r i v er In Se at () { … }
/ / g e t t e r, s e t t e r methods
public void s et I s D ri v er I n S ea t ( ) { … }
p r i v a t e void manageMotor() { … }

/ / More p r i v a t e methods …
29
/ / S t a t i c methods
Objects and Classes (3)
• How to use the Vehicle class:
– First, create a new object via constructor Vehicl e() , e.g., Vehicle
myCar = new Ve h i c l e ( ) ;
– Change Vehicle states, e.g., s t a r t U p ( ) or s h u t O ff ( ) the Vehicle
– You can imagine other use cases
– Mark a new Vehicle ’s ID number (VIN) as “taken” by calling
Vehicle.setVin(…)
– Caveat: VINs more complex than this (simple) implementation
[7]
• Notes:
– Aliasing: If we set Vehicle myTruck = myCar, both myCar and
myTruck
“point” to the same variable. Better to perform “deep copy” of
myCar and store the copy in myTruck
– n u l l reference: refers to no object, cannot invoke methods on
null 30

Inheritance (1)
• Types of Vehicle s: Motorcycle , Car, Truck , etc. Types of Cars:
Sedan, Coupe, SUV. Types of Truck s: Pickup , Flatbed .
• Induces inheritance hierarchy
• Subclasses inherit fields/methods from superclasses.
• Subclasses can add new fields/methods, override those of
parent classes
• For example, Motorcycle ’s driveForward() method
differs from Truck’s driveForward() method

31
Inheritance (2)
• Inheritance denoted via extends keyword
p u b l i c class Vehicle { p u b l i c class Motorcycle
… extends Vehicle {
p u b l i c void driveForward …
(double speed) { p u b l i c void driveForward
/ / Base class (double speed) {
method / / Apply power…
} }
} }

32
Inheritance (3)
p u b l i c class Truck extends
Vehicle { p r i v a t e boolean
useAwd = true;
// . . .
public Truck(boolean
useAwd) {
this.useAwd =
useAwd; }
// . . .
public void
driveForward(double
speed)
{
if (useAwd) {
// Apply
power to 36
Polymorphism
• Suppose we create Vehicle s and invoke the driveForward() method:
Vehicle ve h icle = new Ve h i c l e ( ) ;
Vehicle motorcycle = new Mo t o rcycl e ();
Truck truck1 = new Tr u c k ( t r u e ) ; Vehicle
truck2 = new Tr u c k ( f a l s e ) ;
/ / Code here t o s t a r t vehicles…
ve h icle .d rive Fo rwa rd (5 . 0 );
motorcycle.driveForward( 1 0 . 0 ) ;
tru ck1 .drive Fo rward (15 .0);
truck2.d riveForwa rd (1 0.0 );
• For vehicle , Vehicle’s
driveForward () method is invoked
• For motorcycle , Motorcycle ’s
driveForward() method is invoked
• With truck1 and truck2 , Truck’s driveForward() function is invoked (with all-wheel
drive for truck1 , not for truck2 ).
• Dynamic method lookup: Java looks at objects’ actual types to find which method to
invoke
34
• Polymorphism: feature where objects of different subclasses are treated same way. (All
The Object Class
• Every class in Java is a subclass of Object
• Important methods in Object :
– t o S t r i n g ( ) : Converts Object to a S t r i n g
representation
– equals() : Compares Object s’ contents for equality
– hashCode() : Hashes the Object to a fixed-length
St ring , useful for data structures like HashMap, HashSet
• If you create your own class, you should override
t o S t r i n g ( ) and hashCode()

35
Interfaces
• Java interfaces abstractly specify methods to be implemented
• Intuition: decouple method definitions from implementations (clean design)
• Interfaces, implementations denoted by i n t e r f a c e , implements keywords
• Examples:

p u b l i c i n t e r f a c e Driveable {
p u b l i c void driveForward(double speed);
}

p u b l i c class Vehicle implements Driveable {


p u b l i c void driveForward(double speed) { / * implementation * / }
}

p u b l i c class Motorcycle extends Vehicle implements Driveable { p u b l i c


void driveForward(double speed) { / * implementation * / }
}
36
The Comparable Interface
• Comparing Object s is important, e.g., sorting in
data structures
• The Comparable interface compares two Object s,
e.g.,
a and b:
public i n t e r f a c e Comparable
{
int compareTo(Object
ot h er O b j ec t );
}
• a.compareTo(b) returns negative integer if a “comes
before” b, 0 if a is the same as b, and a positive integer
otherwise
• In your classes, you should implement Comparable to
facilitate Object comparison 37
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: j a v a . l a n g . * , j a v a . u t i l . * , etc.
– Critical for organizing large numbers of classes!
– All classes in a package can “see” each other (scope)

38

You might also like