Getting started with Java for Android
What we will learn
Getting Started
• Java: The Basics
• Java: Object–Oriented Programming
First we Need to install Java Dev. Kit (JDK) version 8 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): https://adoptopenjdk.net/
– 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 info adoptopenjdk8 at command line
• Linux: Type sudo apt install default–jdk at command line
(Debian, Ubuntu) Before we get into it we have to have all the dev tools
After installing JDK, download Android SDK
from http://developer.android.com
• Simplest: download and install Android Studio
bundle (including Android SDK) for your OS
• We’ll use Android Studio with SDK included
(easy)
Java Programming Language
• Java is a general-purpose language: “write code once, run anywhere”
** Java Virtual Machine (JVM)**
– Program code is compiled to JVM bytecode Then the JVM bytecode interpreted on JVM
Our First Java Program
public class HelloWorld {
public static void main(String[] args) {
System.out.println(“Hello world!”);
}
}
Do not forget to match curly braces { , } or semicolon at the end!
•** This are the IDEs That i recomend** :
– IntelliJ IDEA CE (free; http://www.jetbrains.com/student)
– Eclipse (free; http://www.eclipse.org)
– Text editor of choice (with Java programming plugin)
**Explaining the Java code **
Every .java source file contains one class That has a class name
– 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 public 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
String variables)
– Java “thinks” main(), Main(), miAN() are different methods Since it is case sensitive
• Every Java method has curly braces {,} surrounding its code
• Every statement in Java ends with a semicolon, e.g.,
System.out.println(“Hello world!”);
• Program prints “Hello world!” to the console, then quits
Basic Data Types
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 true or false
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 = true;
• Later in the program, we might assign false to b: b = false;
• Java strongly suggests that variables be initialized at the time of
declaration, e.g., boolean b; gives a compiler warning (null pointer)
• Constants defined using final keyword, e.g.,
final boolean falseBool = FALSE;
The Primitive datatypes are
.boolean
.Char
.Byte
.Int
.Long
.Float
.Double
Sometimes variables need to be cast to another type, e.g.,
if finding average of integers:
int intOne = 1, intTwo = 2, intThree = 3, numInts = 2;
double doubOne = (double)intOne, doubTwo = (double)myIntTwo, doubThree =
(double)intThree;
double avg = (doubOne + doubTwo + doubThree)/(double)numInts;
• Math library has math operations like sqrt(), pow(), etc.
• String: immutable type for sequence of characters
– Every Java variable can be converted to String via toString()
– The + operation concatenates Strings with other variables
– Let str be a String. We can find str’s length (str.length()),
substrings of str (str.substring()),
Basic Controll Structures
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>) {
// Read some Code
}
else if (<some other Boolean expression) {
// Write Some Code
}
else {
// Read More Code
}
**More example **
final double OLD_DROID = 5.0, final double NEW_DROID = 9.0;
double myDroid = 8.1;
if (myDroid < OLD_DROID)
{
System.out.println(“Antique!”);
}
else if (myDroid > NEW_DROID)
{
System.out.println(“Very modern!”);
}
else
{
System.out.println(“Your device: barely supported.”);
}
The code will print > Very modern! to the screen.
• What if myDroid == 4.1? myDroid == 10.0?
example 2
final double JELLY_BEAN = 4.1, final double ICE_CREAM = 4.0;
final double EPSILON = 1E-6;
double myDroid = 4.1;
if (myDroid > ICE_CREAM) {
if (Math.abs(myDroid – ICE_CREAM) < EPSILON) {
System.out.println(“Ice Cream Sandwich”);
}
else {
System.out.println(“Jelly Bean”);
}
}
else {
System.out.println(“Old version”);
}
The code will print > “Jelly Bean” to screen. Note nested if-then-else, EPSILON usage.
While Loop
String str = “aaaaaaaaaa”;
int minLength = 10;
while (str.length() <
minLength) {
str = str + “a”;
}
System.out.println(str);
Do-While Loop
String str = “aaaaaaaaaa”;
int minLength = 10;
do {
str = str + “a”;
} while (str.length() <
minLength)
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”
The for loop has the following structure:
String str = “aaaaaaaaaa”;
int minLength = 10;
do {
str = str + “a”;
} while (str.length() <
minLength)
System.out.println(str);
• 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;
for (i = 0; i < 10; i++) {
System.out.println(“i = ” + i);
}
System.out.println(“i = ” + i);
## Objects and Classes
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 a
Vehicles (e.g., set min. fuel economy). These correspond to static methods in
public class Vehicle {
// Instance fields (some omitted for brevity)
private boolean isOn = false;
private boolean isDriverInSeat = false;
private double fuelInTank = 10.0;
private double speed = 0.0;
// Static fields
private static String lastVin = “4A4AP3AU*DE999998”;
// Instance methods (some omitted for brevity)
public Vehicle() { … } // Constructor
public void startUp() { … }
public void shutOff() { … }
public void getIsDriverInSeat() { … } // getter, setter methods
public void setIsDriverInSeat() { … }
private void manageMotor() { … } // More private methods …
// Static methods
public static void setVin(String newVin) { … }
}
JAVA METHODS
methods are used to perform specific, well-defined tasks and also has a signature
public static ReturnType method(paramType1 param1, … paramTypeN
paramN) {
// perform certain task
}
The following is an example of a method used to compute area of a triangle
public static double findRectArea(double length, double
width) {
return length * width;
}
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
From the example above :
Precondition: length > 0.0, width > 0.0
*** Postcondition**: returns length × width (area of rectangle)
methods are also annotated via JavaDoc,
e.g.,
/**
Compute area of rectangle.
@param length Length of rectangle
@param width Width of rectangle
@return Area of rectangle
*/
Methods That are called from main() (which is static)
need to be defined static too also Some of The methods may not return anything ten declared by (void) Keyword
ARRAYS DATA STRUCTURE
An Array is a fixed-length sequence of variable types; cannot change length at run-time
Examples:
final int NUMSTUDENTS = 13;
String[] students; // Declaration
String[] students = new String[NUMSTUDENTS];
// Declaration and initialization
String[] moreStudents = { “Jane”, “Kim”, “Jose”, “Mern”};
// Declaration and explicit initialization
System.out.println(moreStudents.length) // Prints 4
Enhanced for loop is executed for each element in array
Example:
for (String student: moreStudents) {
System.out.println(student + “, ”);
}
Exception Handling
If we had called arrStrings.get(4), we
would have an error condition.The JVM throws an IndexOutOfBounds exception,
halts execution
For the code bellow
import java.util.ArrayList;
public class ArrayException {
/**
* @param args
*/
public static void main(String[] args){
//TODO Auto-generated method stub
ArrayList<String> arrStrings = new ArrayList<String>();
arrStrings.add(“Jane”);
arrStrings.add(“Kim”);
arrStrings.add(“Jose”);
arrStrings.add(“Mern”);
int size = arrStrings.size.();
arrStrings.get(size);
}
}
The following code will produce the IndexOutOfBoundsExeption Error.We handle This exceptions By using the try-catch-finally structure As In The Example bellow
try {
// Code that could trigger an exception
}
catch (IndexOutOfBoundsException e) { // Or another Exception
// Code that “responds” to exception, e.g.,
e.printStackTrace();
}
finally {
// Code executes regardless of whether exception occurs
}
This Exceptions always need to be caught and “reported”, especially in Android
Object Oriented Programming Concepts
Inheritance
This Types of Vehicles: Motorcycle, Car, Truck, etc. Types of Cars:
Sedan, Coupe, SUV. Types of Trucks: 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*This types is denoted via extends keyword
As shown in the example bellow As we create a class Motorcycle that will extend Vehicle
public class Vehicle {
…
public void driveForward
(double speed) {
// Base class method
}
}
public class Motorcycle
extends Vehicle {
…
public void driveForward
(double speed) {
// Apply power…
}
}
//Create another class Truck that inherits properties of vehicle
public class Truck extends Vehicle {
private boolean useAwd = true;
// . . .
public Truck(boolean useAwd) { this.useAwd = useAwd; }
// . . .
public void driveForward(double speed)
{
if (useAwd) {
// Apply power to all wheels…
}
else {
// Apply power to only front/back wheels…
}
}
}
** Polymorphism**
Suppose if we create Another Vehicles and invoke the driveForward() method:
Vehicle vehicle = new Vehicle();
Vehicle motorcycle = new Motorcycle();
Truck truck1 = new Truck(true);
Vehicle truck2 = new Truck(false);
// Code here to start vehicles…
vehicle.driveForward(5.0);
motorcycle.driveForward(10.0);
truck1.driveForward(15.0);
truck2.driveForward(10.0);
For Every vehicle, Vehicle’s driveForward() method is invoked and For every motorcycle, Motorcycle’s driveForward() method is invoked and With every truck1 and truck2, Truck’s driveForward() function is invoked (with all-wheel
drive for truck1, not for truck2).
The Dynamic method lookup: Java looks at objects’ actual types to find which method to invoke Hence Polymorphism is a feature where objects of different subclasses are treated same way. (All
Vehicles driveForward() regardless of (sub)class.)
JAVA OBJECTS
For Every class in Java is a subclass of Object
•** Important methods in Object:**
- toString(): Converts Object to a String representation
- equals(): Compares Objects’ contents for equality
- hashCode(): Hashes the Object to a fixed-length
A String is useful for data structures like HashMap, HashSet
When you create your own class, you should override
toString() and hashCode()
Interfaces
Java interfaces are abstractly specify methods to be implemented
• Intuition: decouple method definitions from implementations (clean design)
• Interfaces, implementations denoted by interface, implements keywords
Example
public interface Driveable {
public void driveForward(double speed);
}
public class Vehicle implements Driveable {
public void driveForward(double speed) { /* implementation */ }
}
public class Motorcycle extends Vehicle implements Driveable {
public void driveForward(double speed) { /* implementation */ }
}
Happy learning for more resources visit [https://www.javatpoint.com/java-tutorial](Java tutorials)