Java Basics for Android Development

Estimated time: 20 minutes

Introduction to Java

Java is a versatile, object-oriented programming language that is widely used for Android app development. Its "write once, run anywhere" capability, powered by the Java Virtual Machine (JVM), allows developers to write code that can run on any platform. Understanding Java's core concepts is essential for developing robust Android applications.

Objective

In this reading, you will learn:

Basic Syntax

Every Java program contains at least one class and a main method, which serves as the entry point of the application.

Example:


public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Explanation:

Variables and Data Types

In Java, variables must be declared with a specific data type, determining the kind of data the variable can hold.

Common Data Types:

Example:


int age = 25;
double height = 5.9;
String name = "John Doe";
boolean isStudent = false;

Explanation:

Methods

Methods in Java encapsulate code to perform specific tasks. They can accept parameters and return values.

Example:


public int add(int a, int b) {
    return a + b;
}

Explanation:

Method Call:


public static void main(String[] args) {
    HelloWorld hw = new HelloWorld();
    int sum = hw.add(5, 10);
    System.out.println("Sum: " + sum);
}

This code demonstrates how to create an instance of the HelloWorld class, call the add method, and print the result.

Control Structures

Control structures like if-else and loops help control the flow of a Java program.

If-Else Example:


if (age >= 18) {
    System.out.println("Adult");
} else {
    System.out.println("Minor");
}

For Loop Example:


for (int i = 0; i < 5; i++) {
    System.out.println("Iteration: " + i);
}

Explanation:

Object-Oriented Programming (OOP) Concepts

Java is an object-oriented language, meaning it uses objects and classes to organize code. A class defines the structure, while objects are instances of that class.

Example of a Class and an Object:


public class Dog {
    String name;
    int age;

    public void bark() {
        System.out.println(name + " says Woof!");
    }
}

Explanation:

Package Declaration

A package in Java organizes classes and avoids name conflicts.

Example:

package com.example.myapp;

Import Statements

Java uses import statements to include classes and packages that add functionality to the program. This is particularly useful in Android development, where you work with numerous classes from the Android SDK.

Example:

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

Explanation:

Android Activity Lifecycle

An Activity is a core component in Android development, representing a screen with which the user interacts.

onCreate Method

The onCreate method is where you initialize your activity, load the layout, and prepare the app's first screen.

Example:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

Explanation:

Setting the Content View

The setContentView method connects your activity to a specific layout defined in an XML file, which contains the app's visual structure.

Example:

setContentView(R.layout.activity_main);

Explanation:

Finding Views

To manipulate UI components in your Java code, you need to reference them using the findViewById method.

Example:

Button myButton = findViewById(R.id.my_button);

Explanation:

Working with UI Components

You can make your app interactive by setting event listeners on UI components such as buttons.

Example of Button Click Listener:

myButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(getApplicationContext(), "Button Clicked!", Toast.LENGTH_SHORT).show();
    }
});

Explanation:

Common Functions in Android

Here are a few common functions you will often use when working with Android:

  1. onCreate: Initializes the activity when it is first created.
  2. setContentView: Sets the layout for the activity.
  3. findViewById: Locates a view defined in the XML layout.
  4. Toast.makeText(): Displays a quick message to the user.
  5. startActivity(): Launches a new activity.
  6. finish(): Closes the current activity.

Example of Starting a New Activity:

Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);

Explanation:

Error Handling

Java handles runtime errors using try-catch blocks.

Example:

try {
    int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero!");
}

Explanation:

Conclusion

Mastering these foundational Java concepts is essential for any Android developer. As you progress through your Android development journey, practice using these Java basics to write cleaner and more efficient code. Understanding how Java interacts with Android will help you build robust, functional applications more easily. Keep experimenting with different code structures to deepen your comprehension of Java for Android development.

Author

Rajashree Patil