Java for Android

Foundation language for Android — OOP, classes, and the Android SDK built on Java

Basics OOP Inheritance Android

Table of Contents

Java Overview

Java was the original language for Android development. The entire Android SDK is written in Java, and millions of existing apps use it. While Kotlin is now preferred for new projects, understanding Java remains essential for maintaining legacy code and reading Android documentation.

Java Source Code (.java) ↓ compile Bytecode (.class) ↓ run on Android Runtime (ART) ↓ Android App
AspectJava on Android
PlatformRuns on Android Runtime (ART), not JVM
UIActivities, Fragments, XML layouts
InteropJava and Kotlin work together in same project
LegacyMany libraries and tutorials still use Java

1Java Basics

Java is a statically typed, object-oriented language. Every Android Activity, Service, and Adapter is ultimately a Java (or Kotlin) class with variables, methods, and control flow.

Hello World and program structure

Java — Main.javapublic class Main { public static void main(String[] args) { System.out.println("Hello, Android!"); } }

Variables and data types

Java — Variables// Primitives int count = 0; double price = 99.99; boolean isActive = true; char grade = 'A'; // Reference types String name = "Nikhil"; Integer boxedCount = 42; // wrapper class // Constants final int MAX_RETRIES = 3; final String BASE_URL = "https://api.example.com/";

Control flow

Java — if, switch, loops// if-else if (score >= 50) { System.out.println("Pass"); } else { System.out.println("Fail"); } // switch switch (networkType) { case "WIFI": showMessage("Wi-Fi connected"); break; case "MOBILE": showMessage("Mobile data"); break; default: showMessage("No connection"); } // for loop for (int i = 0; i < 5; i++) { System.out.println(i); } // enhanced for (for-each) for (String item : items) { System.out.println(item); }

Arrays and ArrayList

Java — Collections basics// Fixed-size array String[] fruits = {"Apple", "Banana", "Mango"}; // Dynamic list — common in Android adapters ArrayList<String> tasks = new ArrayList<>(); tasks.add("Learn Java"); tasks.add("Build App"); tasks.remove(0);

2OOP Concepts

Object-Oriented Programming (OOP) organizes code around objects that combine data (fields) and behavior (methods). Android is built entirely on OOP — Activities, Views, Adapters, and Services are all classes.

Four pillars of OOP

PillarMeaningAndroid Example
EncapsulationHide internal data, expose via methodsPrivate fields + public getters/setters
AbstractionShow essential features, hide complexityRecyclerView.Adapter abstract methods
InheritanceReuse code from parent classMainActivity extends AppCompatActivity
PolymorphismSame interface, different behaviorOverride onClick() in different listeners

Encapsulation example

Java — Encapsulationpublic class BankAccount { private double balance; // hidden from outside public BankAccount(double initialBalance) { this.balance = initialBalance; } public double getBalance() { return balance; } public void deposit(double amount) { if (amount > 0) { balance += amount; } } public boolean withdraw(double amount) { if (amount > 0 && amount <= balance) { balance -= amount; return true; } return false; } }

Abstraction with interface

Java — Interface abstractionpublic interface OnTaskClickListener { void onTaskClick(Task task); void onTaskLongClick(Task task); } public class TaskAdapter extends RecyclerView.Adapter<TaskViewHolder> { private OnTaskClickListener listener; public void setOnTaskClickListener(OnTaskClickListener listener) { this.listener = listener; } }

3Classes & Objects

A class is a blueprint; an object is an instance of that class. In Android, you create objects for users, tasks, adapters, and every screen component.

Class with constructor and methods

Java — User.javapublic class User { private int id; private String name; private String email; // Constructor public User(int id, String name, String email) { this.id = id; this.name = name; this.email = email; } // Getters and setters public int getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public String getDisplayName() { return name.toUpperCase(); } @Override public String toString() { return "User{id=" + id + ", name='" + name + "'}"; } }

Creating and using objects

Java — Instantiate objectsUser user = new User(1, "Nikhil", "nikhil@example.com"); System.out.println(user.getDisplayName()); List<User> users = new ArrayList<>(); users.add(new User(1, "Alice", "alice@example.com")); users.add(new User(2, "Bob", "bob@example.com"));

Static members

Java — Static fields and methodspublic class ApiConfig { public static final String BASE_URL = "https://api.example.com/"; public static final int TIMEOUT = 30; public static boolean isValidUrl(String url) { return url != null && url.startsWith("http"); } } // Usage — no object needed String url = ApiConfig.BASE_URL; boolean valid = ApiConfig.isValidUrl(url);

Access modifiers

ModifierClassPackageSubclassWorld
public
protected
default
private

4Inheritance

Inheritance lets a class inherit fields and methods from a parent class. Android relies heavily on inheritance — every Activity extends AppCompatActivity, every adapter extends RecyclerView.Adapter.

extends keyword

Java — Class inheritancepublic class Animal { protected String name; public Animal(String name) { this.name = name; } public String speak() { return "..."; } } public class Dog extends Animal { public Dog(String name) { super(name); // call parent constructor } @Override public String speak() { return "Woof!"; } }

Activity inheritance chain

Object └── Context └── ContextWrapper └── Activity └── FragmentActivity └── AppCompatActivity └── MainActivity (your class)

Override and super

Java — MainActivity.javapublic class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // must call parent first setContentView(R.layout.activity_main); Button btnSubmit = findViewById(R.id.btnSubmit); btnSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { submitForm(); } }); } @Override protected void onDestroy() { super.onDestroy(); // cleanup resources } }

Interfaces and abstract classes

Java — Interface vs abstract class// Interface — contract only, multiple inheritance allowed public interface ClickListener { void onClick(); } // Abstract class — can have implemented + abstract methods public abstract class BaseFragment extends Fragment { protected abstract void setupViews(); protected abstract void loadData(); protected void showToast(String message) { Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show(); } }

5Exception Handling

Exceptions handle runtime errors gracefully. Android apps encounter exceptions from network failures, parsing errors, and null references — proper handling prevents crashes and improves user experience.

try-catch-finally

Java — Basic exception handlingpublic int parseAge(String input) { try { return Integer.parseInt(input); } catch (NumberFormatException e) { Log.e("Parser", "Invalid number: " + input, e); return 0; } finally { Log.d("Parser", "Parse attempt completed"); } }

Multiple catch blocks

Java — Handle different exceptionspublic List<Post> fetchPosts() { List<Post> posts = new ArrayList<>(); try { String json = downloadFromApi(); posts = parseJson(json); } catch (IOException e) { Log.e("API", "Network error", e); showError("No internet connection"); } catch (JSONException e) { Log.e("API", "Invalid JSON", e); showError("Failed to parse response"); } catch (Exception e) { Log.e("API", "Unexpected error", e); showError("Something went wrong"); } return posts; }

Common Android exceptions

ExceptionCausePrevention
NullPointerExceptionCalling method on null objectNull checks, Optional, Kotlin
IOExceptionNetwork/file read failuretry-catch, check connectivity
JSONExceptionMalformed JSONValidate response, use Gson
ActivityNotFoundExceptionIntent target missingCheck intent resolves
IllegalStateExceptionWrong lifecycle stateObserve lifecycle, use ViewModel

Custom exception

Java — Custom exception classpublic class ApiException extends Exception { private final int statusCode; public ApiException(String message, int statusCode) { super(message); this.statusCode = statusCode; } public int getStatusCode() { return statusCode; } } // Throw and catch public User getUser(int id) throws ApiException { if (id <= 0) { throw new ApiException("Invalid user ID", 400); } // fetch user... return user; }

6Java in Android

Java integrates directly with the Android SDK. Activities, Fragments, RecyclerView adapters, AsyncTask (legacy), and Intent handling are commonly written in Java — especially in older codebases.

Activity with findViewById

Java — MainActivity.javapublic class MainActivity extends AppCompatActivity { private EditText etName; private Button btnSubmit; private TextView tvResult; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etName = findViewById(R.id.etName); btnSubmit = findViewById(R.id.btnSubmit); tvResult = findViewById(R.id.tvResult); btnSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name = etName.getText().toString().trim(); if (name.isEmpty()) { etName.setError("Name required"); return; } tvResult.setText("Hello, " + name + "!"); } }); } }

RecyclerView Adapter

Java — TaskAdapter.javapublic class TaskAdapter extends RecyclerView.Adapter<TaskAdapter.TaskViewHolder> { private List<Task> tasks = new ArrayList<>(); private OnTaskClickListener listener; public void setTasks(List<Task> newTasks) { this.tasks = newTasks; notifyDataSetChanged(); } @NonNull @Override public TaskViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_task, parent, false); return new TaskViewHolder(view); } @Override public void onBindViewHolder(@NonNull TaskViewHolder holder, int position) { Task task = tasks.get(position); holder.bind(task); } @Override public int getItemCount() { return tasks.size(); } class TaskViewHolder extends RecyclerView.ViewHolder { TextView tvTitle; TaskViewHolder(@NonNull View itemView) { super(itemView); tvTitle = itemView.findViewById(R.id.tvTitle); itemView.setOnClickListener(v -> { int pos = getAdapterPosition(); if (pos != RecyclerView.NO_POSITION && listener != null) { listener.onTaskClick(tasks.get(pos)); } }); } void bind(Task task) { tvTitle.setText(task.getTitle()); } } }

Intent navigation

Java — Start Activity with Intent// Navigate to DetailActivity Intent intent = new Intent(MainActivity.this, DetailActivity.class); intent.putExtra("task_id", task.getId()); intent.putExtra("title", task.getTitle()); startActivity(intent); // Receive in DetailActivity public class DetailActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); int taskId = getIntent().getIntExtra("task_id", -1); String title = getIntent().getStringExtra("title"); } }

Java vs Kotlin on Android

TaskJavaKotlin
Click listenernew View.OnClickListener() { ... }{ view -> ... }
Null checkif (user != null) user.getName()user?.name
Data modelPOJO + getters/settersdata class User(...)
SingletonDouble-checked lockingobject NetworkManager
AsyncExecutorService, callbacksCoroutines

7Hands-On Exercises

1

Write a Java program covering basics — variables, if-else, loops, and an ArrayList.

2

Implement a BankAccount class demonstrating encapsulation with private fields and public methods.

3

Create a User class with constructor, getters/setters, and toString(). Instantiate multiple objects.

4

Build an inheritance hierarchy: AnimalDog → override speak(). Then extend AppCompatActivity.

5

Parse user input with try-catch for NumberFormatException. Log errors with Log.e().

6

Build an Android screen in Java — Activity, XML layout, button click, and TextView update.

7

Bonus: Create a RecyclerView.Adapter in Java to display a list of tasks with click handling.

Java for Android MCQ Practice

10 Basic MCQs 10 Advanced MCQs

10 Basic Java for Android MCQs

1

Java is?

AMarkup language
BObject-oriented language running on JVM/ART
CDatabase
DLayout editor
Explanation: Java was primary Android language before Kotlin adoption.
2

class keyword defines?

APackage only
BFunction only
CBlueprint for objects
DManifest
Explanation: Classes contain fields and methods.
3

extends in Java?

APackage import
BMultiple classes
CInterface implementation
DSingle class inheritance
Explanation: Java allows one superclass; multiple interfaces.
4

implements keyword?

AInterface contract implementation
BClass inheritance
CException throw
DPackage
Explanation: class MainActivity extends AppCompatActivity implements ClickListener
5

public static void main?

AAndroid Activity entry
BEntry point in standalone Java apps
CService start
DManifest tag
Explanation: Android uses Activity onCreate not main as entry.
6

try-catch handles?

AIntents
BLayout inflation
CExceptions
DGradle
Explanation: Catch IOException, NullPointerException, etc.
7

new keyword?

AStatic method
BImports class
CDefines interface
DCreates object instance
Explanation: User user = new User("Ali");
8

@Override annotates?

AMethod overriding superclass
BNew method
CStatic field
DDeprecated class
Explanation: Compiler verifies correct override of onCreate etc.
9

Interface in Java?

AConcrete class only
BContract of abstract methods (Java 8+ default methods)
CXML layout
DAPK
Explanation: Interfaces define behavior contracts.
10

Android Activity in Java extends?

AService
BThread
CAppCompatActivity typically
DApplication only
Explanation: public class MainActivity extends AppCompatActivity

10 Advanced Java for Android MCQs

11

Anonymous inner class?

ASingleton
BClass without name — callbacks like OnClickListener
CSealed type
DGradle script
Explanation: button.setOnClickListener(new View.OnClickListener() { ... });
12

Lambda in Java 8 on Android?

AKotlin only
BNot supported
Cview -> view.setVisibility(GONE) with desugar
DAPI 34 only
Explanation: Desugar enables lambdas on lower API levels.
13

Abstract class vs interface?

AAbstract no methods
BIdentical
CInterface has fields always
DAbstract can have state and partial impl; interface contract
Explanation: Choose based on shared implementation need.
14

Garbage collector on Android?

AART GC reclaims unused objects
BManual delete always
CNo GC
DCompile time only
Explanation: Avoid memory leaks — GC doesn't fix retained references.
15

Serializable vsParcelable?

ASerializable faster always
BParcelable faster for Android IPC
CSame
DNeither for Intent
Explanation: Parcelable optimized; Serializable uses reflection.
16

static field leak risk?

ARequired pattern
BAlways safe
CStatic Activity reference prevents GC
DLint ignores
Explanation: Never static Context/Activity references.
17

Generics erasure?

ASQL feature
BFull reified always
CAndroid-only
DType params removed at runtime in JVM
Explanation: List becomes List at runtime — TypeToken needed for Gson.
18

synchronized keyword?

AThread mutual exclusion on method/block
BUI update
CNetwork async
DLayout lock
Explanation: Prefer concurrent structures over heavy synchronized.
19

Java interop calling Kotlin?

AImpossible
BKotlin generates Java-friendly bytecode; check null annotations
CSeparate APK
DManifest flag
Explanation: Kotlin classes visible as Java with nullable platform types.
20

ExecutorService vs AsyncTask?

ABoth deprecated
BAsyncTask preferred
CExecutorService flexible; AsyncTask deprecated
DMain thread only
Explanation: Use coroutines or Executor; AsyncTask removed.
Click an option to select, then check answers.

Java for Android Interview Q&A

15 topic-focused questions for interviews and revision.

1Java vs Kotlin on Android today.easy
Answer: Kotlin preferred for new code; Java still supported; interop seamless.
2Basic Activity onCreate Java.easy
Answer: protected void onCreate(Bundle saved) { super.onCreate(saved); setContentView(R.layout.activity_main); }
3OOP pillars in Java.easy
Answer: Encapsulation, inheritance, polymorphism, abstraction.
4Interface vs abstract class example.medium
Answer: Interface: OnClickListener. Abstract: BaseActivity with shared toolbar setup.
5Exception handling best practice.medium
Answer: Catch specific exceptions; don't swallow; log; user-friendly message.
6Memory leak static Activity.hard
Answer: Static field holding Activity — fix: weak reference or avoid static context.
7OnClickListener anonymous class.easy
Answer: button.setOnClickListener(v -> { /* action */ }); or anonymous inner class.
8Parcelable implementation.hard
Answer: Implement writeToParcel, CREATOR; or use Kotlin @Parcelize.
9Why Google moved to Kotlin.easy
Answer: Boilerplate reduction, null safety, coroutines, modern language features.
10Java generics in collections.medium
Answer: List users = new ArrayList<>(); raw types lose type safety.
11findViewById in Java.easy
Answer: TextView tv = findViewById(R.id.title); — ViewBinding replaces this.
12Runnable for background thread.medium
Answer: new Thread(() -> { /* work */ runOnUiThread(() -> updateUI()); }).start(); — prefer coroutines.
13Override onCreate importance.easy
Answer: Must call super.onCreate(); initialize UI and listeners.
14Migrating Java to Kotlin.medium
Answer: Android Studio Code → Convert Java File to Kotlin File; test thoroughly.
15Common Java Android pitfalls.medium
Answer: Memory leaks, blocking main thread, not calling super lifecycle, raw types.