Estimated time: 20 minutes
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.
In this reading, you will learn:
Every Java program contains at least one class and a main
method, which serves as the entry point of the application.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Explanation:
public class HelloWorld
: Declares a public class named
HelloWorld
.
public static void main(String[] args)
: Defines the main
method that starts program execution.
System.out.println()
: Prints the text to the console.
In Java, variables must be declared with a specific data type, determining the kind of data the variable can hold.
int
: Integer numbers
double
: Decimal numbers
String
: Text
boolean
: True/False values
int age = 25;
double height = 5.9;
String name = "John Doe";
boolean isStudent = false;
Explanation:
Methods in Java encapsulate code to perform specific tasks. They can accept parameters and return values.
public int add(int a, int b) {
return a + b;
}
Explanation:
public int add(int a, int b)
: Declares a method that adds
two integers and returns their sum.
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 like if-else
and loops help control the
flow of a Java program.
if (age >= 18) {
System.out.println("Adult");
} else {
System.out.println("Minor");
}
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
Explanation:
if-else
structure checks a condition and executes
different code blocks based on whether the condition is true or false.
However, the for
loop iterates over a block of code several
times.
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.
public class Dog {
String name;
int age;
public void bark() {
System.out.println(name + " says Woof!");
}
}
Explanation:
Dog
class has properties (name
and
age
) and a method (bark
) that simulates a
dog's bark.
A package in Java organizes classes and avoids name conflicts.
package com.example.myapp;
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.
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
Explanation:
import
statements allow access to the Android framework
classes needed to build the user interface and manage application
behavior.
An Activity is a core component in Android development, representing a screen with which the user interacts.
The onCreate
method is where you initialize your activity,
load the layout, and prepare the app's first screen.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Explanation:
@Override
: Indicates that the method
is overriding a superclass method.
onCreate
: Initializes the activity and sets up the UI.
setContentView
: Links the activity to a layout file.
The setContentView
method connects your activity to a
specific layout defined in an XML file, which contains the app's visual
structure.
setContentView(R.layout.activity_main);
Explanation:
To manipulate UI components in your Java code, you need to reference
them using the findViewById
method.
Button myButton = findViewById(R.id.my_button);
Explanation:
findViewById
method returns a reference to a UI element
(e.g., a button) that you can modify or add listeners to.
You can make your app interactive by setting event listeners on UI components such as buttons.
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Button Clicked!", Toast.LENGTH_SHORT).show();
}
});
Explanation:
setOnClickListener
: Registers a listener to detect user
interaction.
Toast.makeText()
: Displays a short message to the user when
the button is clicked.
Here are a few common functions you will often use when working with Android:
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
Explanation:
Intent
: A messaging object used to navigate between
activities.
startActivity(intent):
Launches a new activity.
Java handles runtime errors using try-catch blocks.
try {
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
Explanation:
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.