0% found this document useful (0 votes)
23 views76 pages

Java Basics for Android Development

This document is an introduction to a tutorial series on learning Java specifically for Android development, aimed at beginners with some programming background. It covers Java fundamentals, object-oriented programming concepts, and the importance of Java's platform independence and security in Android app development. The tutorial also outlines the necessary tools, such as the Eclipse IDE, and provides insights into Java's syntax and structure, including classes, inheritance, and interfaces.

Uploaded by

aseem_yadav_1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views76 pages

Java Basics for Android Development

This document is an introduction to a tutorial series on learning Java specifically for Android development, aimed at beginners with some programming background. It covers Java fundamentals, object-oriented programming concepts, and the importance of Java's platform independence and security in Android app development. The tutorial also outlines the necessary tools, such as the Eclipse IDE, and provides insights into Java's syntax and structure, including classes, inheritance, and interfaces.

Uploaded by

aseem_yadav_1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Learn Java for Android Development:

Introduction to Java
Shane Conder & Lauren Darcey on Sep 13th 2010 with 39 comments

Tutorial Details

 Technology: Java (with Android Focus)


 Difficulty: Beginner
 Estimated Completion Time: 45-60 Minutes

This entry is part 1 of 13 in the series Learn Java for Android Development

Learn Java for Android Development

 Learn Java for Android Development: Introduction to Java


 Learn Java for Android Development: Java Syntax
 Learn Java for Android Development: Checking Object Type with Instanceof
 Learn Java for Android Development: Working with Arrays
 Learn Java for Android Development: Reflection Basics
 Learn Java for Android Challenge: Iteration
 Learn Java for Android Development: Inner Classes
 Learn Java for Android Development: More On Inner Classes
 Learn Java for Android Development: Javadoc Code Documentation
 Learn Java for Android Development: String Basics
 Learn Java for Android Development: Date and Time Basics
 Learn Java for Android Challenge: Strings
 Learn Java for Android Development: Java Shorthand

In this tutorial series, you’ll become familiar with Java, the programming language used to
develop Android applications. Our goal is to prepare those already familiar with one
programming language, such as PHP or Objective-C, to become comfortable working with the
Java programming language and dive into Android app development. In this tutorial, you’ll get a
brief introduction to Java fundamentals, including object oriented programming, inheritance and
more. If you’re new to Java, or just looking to brush up on the details, then this is the tutorial
series for you!

Getting Started
As far as prerequisites go, we’re going to assume you understand how to program (perhaps in
PHP, or Visual Basic or C++), but that you are unfamiliar with the specifics of programming in
the Java language. We aren’t going to teach you to program; we’re going to provide you with
clear examples of commonly used Java language constructs and principles, while pointing out
some Android-specific tips and tricks.

What You’ll Need


Technically, you don’t need any tools to complete this tutorial but you will certainly need them
to develop Android applications.

To develop Android applications (or any Java applications, for that matter), you need a
development environment to write and build applications. Eclipse is a very popular development
environment (IDE) for Java and the preferred IDE for Android development. It’s freely available
for Windows, Mac, and Linux operating systems.

For complete instructions on how to install Eclipse (including which versions are supported) and
the Android SDK, see the Android developer website.

What is Java?
Android applications are developed using the Java language. As of now, that’s really your only
option for native applications. Java is a very popular programming language developed by Sun
Microsystems (now owned by Oracle). Developed long after C and C++, Java incorporates many
of the powerful features of those powerful languages while addressing some of their drawbacks.
Still, programming languages are only as powerful as their libraries. These libraries exist to help
developers build applications.

Some of the Java’s important core features are:

 It’s easy to learn and understand


 It’s designed to be platform-independent and secure, using
virtual machines
 It’s object-oriented

Android relies heavily on these Java fundamentals. The Android SDK includes many standard
Java libraries (data structure libraries, math libraries, graphics libraries, networking libraries and
everything else you could want) as well as special Android libraries that will help you develop
awesome Android applications.

Why is Java Easy to Learn?


Java is easy to learn for a variety of reasons. There’s certainly no shortage of Java resources out
there to help you learn the language, including websites, tutorials, books, and classes. Java is one
of the most widely discussed, taught, and used programming languages on the planet. It’s used
for many different types of programming projects, no matter their scale, from web applications to
desktop applications to mobile applications.
If you’re coming from a traditional programming background like C or C++, you’ll find Java
syntax quite similar. If you’re not, then take comfort in knowing that you’ve chosen one of the
easiest languages to learn. You’ll be up and running in no time at all.

Finally, Java is one of the most human-readable languages out there, by which we mean that a
person who knows nothing about programming can often look at some Java code and have at
least an inkling what it’s doing. Consider the following example:

view plaincopy to clipboardprint?

1. char character = 'a';


2. if(character=='a')
3. {
4. doSomething();
5. } else {
6. doSomethingElse();
7. }

If you simply read the code aloud, you can pretty much tell that this snippet of code is doing.
There’s a single letter variable called character. If the character variable equals the letter a, then
we do something (call the doSomething() method), otherwise we do something else (by calling
the doSomethingElse() method).

Why is Platform Independence Important?


With many programming languages, you need to use a compiler to reduce your code down into
machine language that the device can understand. While this is well and good, different devices
use different machine languages. This means that you might need to compile your applications
for each different device or machine language—in other words, your code isn’t very portable.
This is not the case with Java. The Java compilers convert your code from human readable Java
source files to something called “bytecode” in the Java world. These are interpreted by a Java
Virtual Machine, which operates much like a physical CPU might operate on machine code, to
actually execute the compiled code. Although it might seem like this is inefficient, much effort
has been put into making this process very fast and efficient. These efforts have paid off in that
Java performance in generally second only to C/C++ in common language performance
comparisons.

Android applications run in a special virtual machine called the Dalvik VM. While the details of
this VM are unimportant to the average developer, it can be helpful to think of the Dalvik VM as
a bubble in which your Android application runs, allowing you to not have to worry about
whether the device is a Motorola Droid, an HTC Evo, or the latest toaster running Android. You
don’t care so long as the device is Dalvik VM friendly—and that’s the device manufacturer’s job
to implement, not yours.

Why is Java Secure?


Let’s take this bubble idea a bit further. Because Java applications run within the bubble that is a
virtual machine, they are isolated from the underlying device hardware. Therefore, a virtual
machine can encapsulate, contain, and manage code execution in a safe manner compared to
languages that operate in machine code directly. The Android platform takes things a step
further. Each Android application runs on the (Linux-based) operating system using a different
user account and in its own instance of the Dalvik VM. Android applications are closely
monitored by the operating system and shut down if they don’t play nice (e.g. use too much
processing power, become unresponsive, waste resources, etc.). Therefore, it’s important to
develop applications that are stable and responsive. Applications can communicate with one
another using well-defined protocols.

Compiling Your Code


Like many languages, Java is still a compiled language even though it doesn’t compile all the
way down to machine code. This means you, the developer, need to compile your Android
projects and package them up to deploy onto devices. The Eclipse development environment
(used with the Android Development plug-in) makes this pretty painless. In Eclipse, automatic
compilation is often turned on by default. This means that every time you save a project file,
Eclipse recompiles the changes for your application package. You immediately see compile
errors. Eclipse also interprets Java as you type, providing handy code coloring and formatting as
well as showing many types of errors as you go. Often, you can click on the error and have
Eclipse automatically fix a typo, or add an import statement, or provide a method stub for you,
saving lots of typing.

You can still manually compile your code if you so desire. Within Eclipse, you’ll find the Build
settings under the project menu. If you have “Build Automatically” turned on, you can still
choose the “Clean…” option that will allow you to do full rebuild of all files. If “Build
Automatically” is turned off, “Build All” and “Build Project” menu options are enabled. “Build
All” means to build all of the projects in the workspace. You can have many projects in an
Eclipse workspace.

The build process, for regular Java projects, results in a file with the extension of JAR – Java
ARchive. Android applications take JAR files and package them for deployment on devices as
Android PacKage files with an extension .apk. These formats not only include your compiled
Java code, but also any other resources, such as strings, images, or sound files, that your
application requires to run as well as the Application Manifest file, [Link]. The
Android Manifest file is a file required by all Android applications, which you use to define
configuration details about your app.

What is an Object Oriented Programming Language?


Okay. Time for a very brief and 20,000 foot view of object oriented programming (OOP). OOP
is a programming style or technique that relies upon the definition of data structures called
objects. For those new to OOP, an object can be thought of much like a custom data type. For
example, you might have a Dog object, which represents the blueprint for a generic dog, with a
name, breed, and gender. You could then create different instances of the Dog object to represent
specific dogs. Each Dog object must be created by calling its constructor (a method that has the
same name as the object itself, and may or may not have parameters for setting initial values).
For example, the following Dog objects use a constructor with three parameters (name, breed,
gender):

view plaincopy to clipboardprint?

1. Dog dog1 = new Dog("Lassie", collie, female);


2. Dog dog2 = new Dog("Fifi", poodle, female);
3. Dog dog3 = new Dog("Asta", foxterrier, male);

So where is this Dog object defined? Well, here we need to begin defining some of the
fundamental building blocks of the Java programming language. A class provides a definition for
an object. Therefore, there is a Dog class somewhere—either defined by you or in some library
somewhere. Generally speaking, a class will be defined in its own file, with the filename
matching the class name (e.g. [Link]). There are exceptions to this rule, such as classes
defined within other classes (when a class is declared within a class, it is generally defined for
use within the parent class only as a helper class, and referred to as an inner class).

When you want to reference an object from within another class, you need to include an import
statement in the top of your class file, much like you would use a #include statement in a
compiled language like C.

A class typically describes the data and behavior of an object. The behavior is defined using
class methods. Method is the common term for a subroutine in an OOP language. Many common
object classes are defined in shared class libraries like software development kits (SDKs),
whereas others are defined by you, the developer, for your own purposes. Software is then built
up by using and manipulating object instances in different ways.

Please realize this is a very generalized definition of OOP. There are entire books written on this
subject. If you’d like to know more about OOP, here are a few resources you might want to
check out:

 Wikipedia has a nice overview of OOP


 Sun Java Tutorials on Java
 The Java Tutorials at Oracle

Note: We use a lot of different terminology in this tutorial. There are multiple ways to refer to a
given concept (e.g. superclass vs. parent class), which is confusing to those new to object
oriented programming. Different developers use different terms, and so we have tried to mention
synonyms where appropriate. Deciding which terms you will use is a personal choice.

Understanding Inheritance
Here is another important Java concept you’ll run into a lot: inheritance. Simply put, inheritance
means that Java classes (and therefore objects) can be organized into hierarchies with lower,
more specific, classes in the hierarchy inheriting behavior and traits from higher, more generic,
classes.

This concept is best illustrated by example. Let’s pretend we are developing a Java application to
simulate an aquarium. This aquarium has some fish in it. Therefore, we might define a class to
represent a fish. This class, called Fish, could include some data fields (also called attributes, or
class member variables) to describe a fish object: species, color and size; as well as some of its
behavior in the form of methods (also called subroutines, or functions in procedural languages),
like eat(), sleep(), and makeBabyFish().

A special type of method, called a constructor, is used to create and initialize an object;
constructors are named the same as their class and may include parameters. The following Fish
class has two constructors: one for creating a generic Fish object and another for constructing a
specific Fish object with some initial data. You’ll also see that the Fish class has two eat()
methods: one for eating something random, and another for eating another fish, which would be
represented by another instance of the Fish class:

view plaincopy to clipboardprint?

1. public class Fish {


2.
3. private String mSpecies;
4. private String mColor;
5. private int mSize;
6.
7. Fish() {
8. // generic fish
9. mSpecies = "unknown";
10. mColor = "unknown";
11. mSize = 0;
12. }
13.
14. Fish(String species, String color, int size) {
15. mSpecies = species;
16. mColor = color;
17. mSize = size;
18. }
19. public void eat() {
20. // eat some algae
21. };
22.
23. public void eat(Fish fishToEat) {
24. // eat another fish!
25. };
26.
27. public void sleep() {
28. // sleep
29. };
30.
31. public void makeBabyFish(Fish fishSpouse, int numBabies) {
32. // Make numBabies worth of baby fish with Fish spouse
33. };
34. }

Classes can be organized into hierarchies, where a derived class (or subclass) includes all the
features of its parent class (or superclass), but refines and adds to them to define a more specific
object using the extends keyword. This is called inheritance.

For example, the Fish class might have two subclasses: FreshwaterFish and SaltwaterFish. These
subclasses would have all the features of the Fish class, but could further customize the objects
through new attributes and behaviors or modified behaviors from the parent class Fish. For
example, the FreshwaterFish class might include information about the type of freshwater
environment lived in (e.g. river, lake, pond, or puddle). Similarly, the SaltwaterFish class might
customize the makeBabyFish() method such that the fish eats its mate after breeding (as defined
in the super class) by using the override mechanism, like this:

view plaincopy to clipboardprint?

1. public class SaltwaterFish extends Fish


2. {
3. @Override
4. public void makeBabyFish(Fish fishSpouse, int numBabies) {
5. // call parent method
6. [Link](fishSpouse, numBabies);
7. // eat mate
8. eat(fishSpouse);
9. }
10. }

Organizing Object Behavior with Interfaces


In Java, you can organize object behaviors in what are called interfaces. While a class defines an
object, an interface defines some behavior that can be applied to an object. For example, we
could define a Swimmer interface that provides a set of methods that are common across all
objects that can swim, whether they are fish, otters, or submergible androids. The Swimmer
interface might specify four methods: startSwimming(), stopSwimming(), dive(), and surface().

view plaincopy to clipboardprint?

1. public interface Swimmer


2. {
3. void startSwimming();
4. void stopSwimming();
5. void dive();
6. void surface();
7. }

A class like Fish could then implement the Swimmer interface (using the implements keyword)
and provide implementations of the swimming behavior:
view plaincopy to clipboardprint?

1. public class Fish implements Swimmer {


2. // Provide implementations of the four methods within the Swimmer interface
3. }

Organizing Classes and Interfaces with Packages


Class hierarchies, such as our fish classes, can then be organized into packages. A package is
simply a set of classes and interfaces, bundled together. Developers use namespaces to uniquely
name packages. For example, we could use [Link] or
[Link] as our package name to keep track of our fish-related classes.

Wrapping Up
Wow! You’ve just embarked on a crash-course in Java for Android development. We’ve covered
a pretty intense amount of material here, so let things settle for a bit before moving on to the next
lesson of this tutorial series. In Lesson 2, we switch our focus to the nitty-gritty details of Java
syntax.

You’ve only scratched the surface of Java development for Android development. Check out all
the other great tutorials on Mobiletuts+ to dive deeper into Java and Android development. Good
luck!

Learn Java for Android Development: Java


Syntax
Shane Conder & Lauren Darcey on Sep 20th 2010 with 12 comments

Tutorial Details
 Technology: Java with Android Focus
 Difficulty: Beginner
 Estimated Completion Time: 45-60 minutes

This entry is part 2 of 13 in the series Learn Java for Android Development

Learn Java for Android Development

 Learn Java for Android Development: Introduction to Java


 Learn Java for Android Development: Java Syntax
 Learn Java for Android Development: Checking Object Type with Instanceof
 Learn Java for Android Development: Working with Arrays
 Learn Java for Android Development: Reflection Basics
 Learn Java for Android Challenge: Iteration
 Learn Java for Android Development: Inner Classes
 Learn Java for Android Development: More On Inner Classes
 Learn Java for Android Development: Javadoc Code Documentation
 Learn Java for Android Development: String Basics
 Learn Java for Android Development: Date and Time Basics
 Learn Java for Android Challenge: Strings
 Learn Java for Android Development: Java Shorthand

In this tutorial series, you’ll become familiar with Java, the programming language used to
develop Android applications. Our goal is to prepare those already familiar with one
programming language, such as PHP or Objective-C, to become comfortable working with the
Java programming language and dive into Android app development. In this specific tutorial,
you’ll learn the basics of Java syntax, including how to create comments, define variables, craft
conditional statements and iterate using loops. If you’re new to Java, or just looking to brush up
on the details, then this is the tutorial series for you!

Getting Started
As far as prerequisites go, we’re not going to make many assumptions about your programming
experience. We are going to assume you understand how to program (perhaps in PHP, or Visual
Basic or C++), but that you are unfamiliar with the specifics of programming in the Java
language. We’re not going to go into the details of why you would want to do a for-loop versus a
while-loop, but we will show you, in Java, the syntax of both types of loops. Said another way,
we aren’t going to teach you to program; we’re going to provide you with clear examples of
commonly used Java language constructs and principles, while pointing out some Android-
specific tips and tricks.

What You’ll Need


Technically, you don’t need any tools to complete this tutorial but you will certainly need them
to develop Android applications.

To develop Android applications (or any Java applications, for that matter), you need a
development environment to write and build applications. Eclipse is a very popular development
environment (IDE) for Java and the preferred IDE for Android development. It’s freely available
for Windows, Mac, and Linux operating systems.

For complete instructions on how to install Eclipse (including which versions are supported) and
the Android SDK, see the Android developer website.

Now let’s look at some more helpful Java syntax.

Comments
Most programming languages allow for comments and Java is no different. You can encapsulate
any number of lines of text by beginning your comment with /* and ending your comment with
*/. For example:

view plaincopy to clipboardprint?

1. /* MULTILINE
2. COMMENT */

You can also provide comments after code on a single using //. For example:
view plaincopy to clipboardprint?

1. int x = 7; // First variable called x equals seven


2. int y = 8; // Second variable called y equals eight
3. int result = x + y; // The result variable value should equal 15

Java also has a standard type of comments called Javadoc that can be used to not only comment
code, but also easily create code documentation. This topic is rather large on it’s own, but here’s
an example of what Javadoc comments looks like:
view plaincopy to clipboardprint?

1. /** This method does something interesting


2. *
3. * @param someValue processed and returned
4. * @param option changes the type of processing done to someValue
5. * @return The result of someValue being processed
6. */
7. public int sampleMethod(int someValue, boolean option) {
8. //…
9. }
Variables
A variable is simply a piece of data. Java variables generally fall into two categories:

 Primitive data types, like int, float, double, char, etc.


 Java objects (as defined by a class definition)

Variables are used for different purposes. Sometimes variables are used to store values that can
change, or be modified, over time. For example, a variable called counter might be incremented
on occasion. Other variables, notably class variables that remain the same for all instances of a
given class, should be defined using the static keyword. Other times variables might represent
constants—these variables should use the keyword final to show they do not change over time.

A variable is only valid within its territory, or scope. Variable scope is often controlled by curly
braces { }. When a variable is defined, it is valid within those braces. If you try to access a
variable outside of the braces, it will be undefined. Class member variables in object-oriented
languages are often called attributes. They can also be called fields or properties.

Like other common programming languages, you’ve got your assignment operator, the equals
sign:

view plaincopy to clipboardprint?

1. int i = 5;

You’ve also got your arithmetic operators like +, -, *, /. Remember to use parenthesis to force the
order of operations as necessary:
view plaincopy to clipboardprint?

1. int result = (a + b) / c;

Finally, you have your typical unary operators, which allow you to modify a single variable with
a simple statement:
view plaincopy to clipboardprint?

1. iPositive++; // increment by one; equivalent to iPositive = iPositive + 1;


2. iPositive --; // decrement by one; equivalent to iPositive = iPositive - 1;

Note that the increment (++) and decrement (–) operators can be prefix or postfix, meaning that
the increment can be executed before or after any conditionals are determined, if the item is used
in a loop. Generally, we like to stick to postfix statements, so code is more readable.

Primitive Data Types


Let’s look at some of the primitive data types available in the Java programming language:
 byte
o A byte variable is an 8-bit signed integer between -128 and 127. Often used for
arrays.
 short
o A short variable is a 16-bit signed integer between -32,768 and 32,767. Again,
often used for arrays.
 int
o An int variable is a 32-bit signed integer between -2,147,483,648 and
2,147,483,647. This is the most commonly used “number” variable.
 long
o A long variable is a 64-bit signed integer between -9,223,372,036,854,775,808
and 9,223,372,036,854,775,807. Used when the int data type isn’t big enough.
 float
o A float variable is a single precision 32-bit floating point number.
 double
A double variable is a double-precision 64-bit floating point number. Use this
o
data type for decimal values.
 boolean
o A boolean variable has only two possible values: true and false. Use this data type
for conditional statements.
 char
o A char variable is a single 16-bit Unicode character.

Primitive types variables can be defined by specifying the datatype, followed by the variable
name, then an equals sign and an initial value. All Java statements end with an semicolon. For
example, the following Java statement defines a variable called iVal, with an initial value of 1:

view plaincopy to clipboardprint?

1. int iVal = 1;

Like many other languages, you can define a zero-based array of a specific data type. For
example, the following defines an array of three integer values (first four powers of 2):
view plaincopy to clipboardprint?

1. int[] aiPowersOfTwo;
2. aiPowersOfTwo = new int[4];
3. aiPowersOfTwo [0] = 1; // 2^0=1
4. aiPowersOfTwo [1] = 2; // 2^1=2
5. aiPowersOfTwo [2] = 4; // 2^2=4
6. aiPowersOfTwo [3] = 8; // 2^3=8

Commonly Used Java Objects


The Java libraries provide a number of helpful objects for use with common data structures. All
objects are derived from the Object class. There are class counterparts for all primitive data
types. For example, the Integer class encapsulates an int value and provides a number of helpful
methods for manipulating integer data values. For example, the following Java code instantiates
a integer variable called iVal, then creates an Integer object using a constructor that takes an
integer, and then uses an handle method available in the Integer class to extract a float variable
equivalent.

view plaincopy to clipboardprint?

1. int iVal = 1;
2. Integer integ1= new Integer(iVal);
3. float f = [Link]();

Perhaps the most common object you’ll use in Android applications is the String. The String
class is used to encapsulate human-readable text characters, which are often displayed to the
screen. If you are modifying or building strings up from smaller parts, you’ll also want to check
out the StringBuffer and StringBuilder classes.
view plaincopy to clipboardprint?

1. String strHello = new String("Hello World");

For a list of common Java data types, the Android reference includes documentation for the
[Link] package. You can also find the common input/output objects in the [Link] package.

For more complex data structures like lists, queues, stacks, dates, and times, appropriate classes
are in the [Link] package.

Finally, Android applications rely on a number of helpful classes that define the commonly used
application components, like Activity, Application, Dialog, and Service. These classes can be
found in the [Link] package.

Class Permissions and Access


You can control the visibility of a class as well as its variables and methods by specifying an
item’s access level. The access levels are: public, protected and private. Generally speaking, if
you want something to be accessible from outside a class, use public. If a method or variable
should only be accessible from the class itself, use private. Use protected when the class or any
of its subclasses need access.

For example, the following SillySensor class definition defines several variables and methods
with different access levels:

 A class variable called sensorData, which is only visible within the class
 A public constructor that can be called outside the class
 A private method called calibrate(), which can only be called from within the class itself
 A protected method called seedCalibration(), which can be called from within the class
itself, or by a subclass
 A public method called getSensorData(), which can be called from anywhere, allowing
for “read-only” access to the sensorData variable

view plaincopy to clipboardprint?

1. public class SillySensor


2. {
3. private int sensorData;
4.
5. public SillySensor()
6. {
7. sensorData=0;
8. }
9.
10. private void calibrate(int iSeed)
11. {
12. // Do some calibration here
13. }
14.
15. protected void seedCalibration(int iSeed)
16. {
17. calibrate(iSeed);
18. }
19.
20. public int getSensorData()
21. {
22. // Check sensor here
23.
24. return sensorData;
25. }
26.
27. }

Conditionals
Java includes conditional statements, which can be used to execute snippets of code if, and only
if, certain conditions are met. Typically, a conditional statement involves two sides. If the two
sides are equivalent, the statement is true, otherwise it is false.

Java has all the typical conditional operators, such as:

 == equal to, as in (a == b)
 != not equal to, as in (x != y)
 > greater than, as in (z > y)
 >= greater than or equal to, as in (q >= z)
 < less than, as in (b < a)
 <= less than or equal to, as in (a <= z)

And when you need to combine multiple conditional statements into a single larger conditional
test, you can use AND (&&) and OR (||):

 ((a==b)&& (a==c)) // true only if A is equal to B and equal to C


 ((a==b) || (a==c)) // true only if A is equal to B or equal to C

Java has bitwise operators (&, |, ^), shifts (>>, <<), and complement (~) operators as well, should
you need them. See the Java documentation for more details.

Now that you know how to craft a conditional statement, you can create conditional code
segments. The simplest form of a conditional code statement is the if() statement:

view plaincopy to clipboardprint?

1. boolean condition = true;


2. if(condition==true)
3. {
4. // Execute this code only if condition variable is true
5. }

If you want to provide alternative code to run if the condition is not met, then use the else clause
with the if() statement:
view plaincopy to clipboardprint?

1. boolean condition = true;


2. if(condition==true)
3. {
4. // Execute this code only if condition variable value is true
5. } else {
6. // Execute this code only if condition variable value is false
7. }

If you want to handle more than two cases, you can use cascading if-else-if-else statements, like
this:
view plaincopy to clipboardprint?

1. if(iVar==0) {
2. // variable is zero
3. } else if (iVar > 0) {
4. // variable is a positive number
5. } else {
6. // variable is a negative number
7. }
Switch Case Statements
When you have a number of different code paths possible that branch from a single variable
value, you can use a switch() statement. With a switch statement, you supply the variable to
check for and provide numerous options to execute for specific cases. You can also supply a
default option to execute if none other cases apply. Each case can be terminated with a break
statement. If a break statement is not supplied, the code will continue executing into the next
case statement.

view plaincopy to clipboardprint?

1. char singleChar = 'z';


2. switch(singleChar) {
3. case 'a':
4. case 'e':
5. case 'i':
6. case 'o':
7. case 'u':
8. // singleChar is a vowel! Execute this code!
9. break;
10. default:
11. // singleChar is a consonant! Execute this code instead!
12. break;
13. }

Loops
When you want to execute code repeatedly, or using recursion (heh, look that one up if you don’t
know what we’re talking about), Java has support for several different kinds of loops.

To loop continuously provided that a statement is true, use a while() loop:

view plaincopy to clipboardprint?

1. int numItemsToProcess = 3;
2. while(numItemsToProcess > 0)
3. {
4. // process an item
5. numItemsToProcess--;
6. }

If you want to evaluate the conditional loop expression AFTER the first iteration, you can use a
do-while loop instead:
view plaincopy to clipboardprint?
1. do
2. {
3. // check for items to process, update numItemsToProcess as required
4. // process item, updated numItemsToProcess
5. } while (numItemsToProcess > 0);

Finally, if you want to loop for a specific number of iterations, you can use a for() loop. A for()
loop has three parameters: the initial value, the terminating value, and the incrementing value.
For example, to execute a loop 100 times, printing the numbers 1 through 100, you could use the
following for() loop:
view plaincopy to clipboardprint?

1. for(int i = 1; i <=100; i++)


2. {
3. // print i
4. }

Note: You can also use a break statement to get out of a while(), do-while() or for() loop when
necessary. You can also use a continue statement to skip the rest of a current iteration of a loop
and move on to the next iteration (reevaluating the conditional expression, of course).

Passing By Value vs. By Reference


There are no pointers in Java. Ok, ok, go ahead and breathe a sigh of relief. Life is hard enough
without pointers mucking things up, right?

Ok, now it’s time to pay attention again. In Java, method parameters are passed by value.
However, when a method parameter is an object (that is, anything except a primitive type), only
a reference to that object is passed into the method [much like pointers, sorry!]. Therefore, in
order to modify the object passed into a given method, you generally pass in the object reference,
and then act upon it, which modifies the underlying data of the object you passed in. You cannot,
however, swap out the object itself… Here’s a quick example:

Here, we have a class called Cat:

view plaincopy to clipboardprint?

1. public class Cat {


2. private String mCatName;
3.
4. Cat(String name) {
5. mCatName=name;
6. }
7.
8. public String getName() {
9. return mCatName;
10. };
11.
12. public void setName(String strName) {
13. mCatName = strName;
14. };
15. }

Now, let’s try to use this class and pass a Cat object into some functions and see what happens:
view plaincopy to clipboardprint?

1. void messWithCat(Cat kitty) {


2. kitty = new Cat("Han");
3. }
4.
5. void changeKitty(Cat kitty) {
6. [Link]("Wookie");
7. }
8.
9. Cat haveKitten()
10. {
11. Cat kitten = new Cat("Luke");
12. return kitten;
13. }

Finally, let’s call these methods and see how they act upon Cat object instances:
view plaincopy to clipboardprint?

1. Cat cat1 = new Cat("Jabba");


2. Cat cat2 = new Cat("Leia");
3.
4. [Link](); // Returns Jabba
5. [Link](); // Returns Leia
6. messWithCat(cat1);
7. changeKitty(cat2);
8. Cat cat3 = haveKitten();
9. [Link](); // Returns Jabba – Note that object remains unchanged!
10. [Link](); // Returns Wookie
11. [Link](); // Returns Luke

Wrapping Up
You’ve just completed a crash-course of the Java programming language. While you may not be
ready to write your first Java app, you should be able to work through the simplest of the
Android sample application Java classes and determine what they’re up to, at least in terms of
the Java syntax of things. The first class you’re going to want to look into for Android
development is the Activity class. An Android application uses activities to define different
runtime tasks, and therefore you must define an Activity to act as the entry point to your
application. Now that you’ve got a handle on Java syntax, we highly recommend that you work
through a beginner Android tutorial.

You’ve only scratched the surface of Java development for Android development. Check out all
the other great tutorials on Mobiletuts+ to dive deeper into Java and Android development. We
highly recommend the following beginning Android tutorials: Introduction to Android
Development by Gyuri Grell and Beginning Android: Getting Started with Fortune Crunch to
begin dabbling in Android development. Good luck!

Learn Java for Android Development:


Checking Object Type with Instanceof
Shane Conder & Lauren Darcey on Sep 24th 2010 with 4 comments

Tutorial Details

 Technology: Java with Android Focus


 Difficulty: Beginner
 Estimated Completion Time: 15 minutes

This entry is part 3 of 13 in the series Learn Java for Android Development

Learn Java for Android Development

 Learn Java for Android Development: Introduction to Java


 Learn Java for Android Development: Java Syntax
 Learn Java for Android Development: Checking Object Type with Instanceof
 Learn Java for Android Development: Working with Arrays
 Learn Java for Android Development: Reflection Basics
 Learn Java for Android Challenge: Iteration
 Learn Java for Android Development: Inner Classes
 Learn Java for Android Development: More On Inner Classes
 Learn Java for Android Development: Javadoc Code Documentation
 Learn Java for Android Development: String Basics
 Learn Java for Android Development: Date and Time Basics
 Learn Java for Android Challenge: Strings
 Learn Java for Android Development: Java Shorthand
This quick lesson in our Learn Java for Android Development series shows you how to
conditionally check the type of an object using the instanceof keyword in Java.

Basic Conditionals
We talked about many of the basic Java conditional statements in the Learn Java for Android
Development: Java Syntax tutorial. For example, Java provides all the typical conditional
operators one might expect, including those to check for equality, inequality, greater than, less
than, etc.

Here’s some Java code that checks the value of a numeric variable (called iVar) and provides
different code paths depending on whether the value of iVar is zero, negative or positive:

view plaincopy to clipboardprint?

1. if(iVar==0) {
2. // variable is zero
3. } else if (iVar > 0) {
4. // variable is a positive number
5. } else {
6. // variable is a negative number
7. }

Using instanceof in Conditional Statements


Now let’s look at a specific Java feature you can also use in conditional statements. Because Java
is a fully object oriented language, you can also test if an object is of a specific type (an instance
of a specific class) conditionally using the instanceof keyword. The instanceof keyword is a
Boolean operator, used like a regular mathematical Boolean conditional operator to generate a
true or a false result.

Let’s look at a quick example. Let’s assume we have a parent class called Fish, which has two
derived subclasses: SaltwaterFish and FreshwaterFish. We could use the instanceof keyword to
test if an object is an instance of a specific class (or subclass) by name:

view plaincopy to clipboardprint?

1. SaltwaterFish nemo = new SaltwaterFish();


2. if(nemo instanceof Fish) {
3. // we’ve got some sort of Fish
4. // could be a Fish (parent class), or subclass of some kind, like
5. // SaltwaterFish, or FreshwaterFish.
6.
7. if(nemo instanceof SaltwaterFish) {
8. // Nemo is a Saltwater fish!
9. }
10. }

Using instanceof in Android Development


So, when it comes to Android development, when is the instanceof feature useful? Well, for
starters, the Android SDK classes are organized in typical object oriented fashion: hierarchically.
For example, the classes such as Button, TextView, and CheckBox, which represent different
types of user interface controls, are all derived from the same parent class: View. Therefore, if
you wanted to create a method that took a View parameter, but had different behavior depending
upon the specific type of control, you could use the instanceof mechanism to check the
incoming parameter and determine exactly what kind of view control had been passed in.

For example, the following method takes a View parameter, allowing you to pass in any type of
View, but specifically singles out TextView controls for special processing:

view plaincopy to clipboardprint?

1. void checkforTextView(View v)
2. {
3. if(v instanceof TextView)
4. {
5. // This is a TextView control
6. } else {
7. // This is not a TextView control
8. }
9. }

In this example, we might continue by making a call to a method that is only valid for a
TextView object and not the generic View object—in which case, we would likely cast the View
parameter to a TextView prior to making such a call. If, however, we wanted to make a call that
is available in all View objects, but behaves differently in TextView objects, there is no need to
test for this. Java will handle calling the appropriate version of the method specific to TextView.
This is one of the great features of object-oriented programming: the most appropriate version of
a given method is called.

Conclusion
In this quick lesson you have learned how to use the instanceof Java keyword to check the type
of an object at runtime and provide conditional code paths based on the result. This is a handy
Java feature that Android developers often rely upon, since the Android SDK is organized
hierarchically.
Learn Java for Android Development:
Working with Arrays
Shane Conder & Lauren Darcey on Sep 29th 2010 with 3 comments

Tutorial Details

 Technology: Java with Android Focus


 Difficulty: Beginner
 Estimated Completion Time: 15 minutes

This entry is part 4 of 13 in the series Learn Java for Android Development

Learn Java for Android Development

 Learn Java for Android Development: Introduction to Java


 Learn Java for Android Development: Java Syntax
 Learn Java for Android Development: Checking Object Type with Instanceof
 Learn Java for Android Development: Working with Arrays
 Learn Java for Android Development: Reflection Basics
 Learn Java for Android Challenge: Iteration
 Learn Java for Android Development: Inner Classes
 Learn Java for Android Development: More On Inner Classes
 Learn Java for Android Development: Javadoc Code Documentation
 Learn Java for Android Development: String Basics
 Learn Java for Android Development: Date and Time Basics
 Learn Java for Android Challenge: Strings
 Learn Java for Android Development: Java Shorthand

This quick lesson shows you how to work with arrays in Java. This lesson is part of an ongoing
series of tutorials for developers learning Java in order to develop Android applications.

What is an Array?
An array is a common data structure used to store an ordered list of items. The array elements are
typed. For example, you could create an array of characters to represent the vowels in the
alphabet:

view plaincopy to clipboardprint?

1. char aVowels[] = {'a','e','i','o','u'};


Much like C or C++, Java arrays are indexed numerically on a 0-based system. This means the
first element in the array (that is, ‘a’) is at index 0, the second (‘e’) is at index 1, and so on.

Java makes working with arrays easier than many other programming languages. The array itself
is an object (of type array), with all the benefits thereof. For example, you can always check the
size of an array using its length property:

view plaincopy to clipboardprint?

1. int length = [Link];

What Can I Store In An Array?


You can store any object or primitive type in an array. For example, you can store integers in an
array:

view plaincopy to clipboardprint?

1. int aNums[] = { 2, 4, 6 };

Or, you could store non-primitive types like Strings (or any other class) in an array:
view plaincopy to clipboardprint?

1. String aStooges[] = {"Larry", "Moe", "Curly"};

Sometimes, you may want to store objects of different types in an array. You can always take
advantage of inheritance and use a parent class for the array type. For example, the Object class
is the mother of all classes… so you could store different types in a single array like this:
view plaincopy to clipboardprint?

1. float one = 1.0f;


2. Integer two = new Integer(2);
3. String three = "three";
4. Object aObjects[] = {one, two, three};

The elements of a Java object array are references (or handles) to objects, not actual instances of
objects. An element value is null until it is assigned a valid instance of an object (that is, the
array is initialized automatically but you are responsible for assigning its values).

Declaring Arrays
There are a number of ways to declare an array in Java. As you’ve seen, you can declare an array
and immediately provide its elements using the C-style squiggly bracket syntax. For example,
the following Java code declares an array of integers of length 3 and initializes the array all in
one line:
view plaincopy to clipboardprint?

1. int aNums[] = { 2, 4, 6 };

You can also declare an array of a specific size and then assign the value of each element
individually, like this:
view plaincopy to clipboardprint?

1. double aPowersOfTwo[] = new double[5];


2. aPowersOfTwo[0]=[Link](2,0);
3. aPowersOfTwo[1]=[Link](2,1);
4. aPowersOfTwo[2]=[Link](2,2);
5. aPowersOfTwo[3]=[Link](2,3);
6. aPowersOfTwo[4]=[Link](2,4);

This is equivalent to creating an array like this:


view plaincopy to clipboardprint?

1. double aPowersOfTwoExplicit[] = {1.0d, 2.0d, 4.0d, 8.0d, 16.0d};

There are several other ways to create arrays. For example, you can create the array variable and
assign it separately using the new keyword. You can also put the array brackets before the
variable name, if you desire (this is a style issue). For example, the following Java code defines
an array of String elements and then assigns them individually:
view plaincopy to clipboardprint?

1. String [] aStopLightColors;
2. aStopLightColors = new String[3];
3. aStopLightColors[0] = new String("red");
4. aStopLightColors[1] = new String("yellow");
5. aStopLightColors[2] = new String("green");

Modifying Array Content


As you have seen, you can assign array values by using the bracket syntax:

You can retrieve array values by index as well. For example, you could access the second
element in the array called aStopLightColors (defined in the previous section) as follows:

view plaincopy to clipboardprint?

1. String strCurrentLightColor = aStopLightColors[1];

Iterating Arrays
Finally, arrays are often used as an ordered list of objects. Therefore, you may find that you want
to iterate through the array in order, accessing each element methodically.

There are a number of ways to do this in Java. Because you can always check the size of an array
programmatically, you can use any of the typical for or while loop methods you may find
familiar. For example, the following Java code declares a simple integer array of three numbers
and uses a simple for-loop to iterate through the items:

view plaincopy to clipboardprint?

1. int aNums[] = { 2, 4, 6 };
2.
3. for (int i = 0; i < [Link]; i++) {
4. String strToPrint = "aNums[" + i + "]=" + aNums[i];
5. }

Java also provides a very handy for-each loop to iterate through arrays in a friendly fashion. The
for-each loop helps avoid silly programming mistakes so common in loops (off-by-one errors,
etc.). To use the for-each loop syntax, you need to define your loop variable, then put a colon,
and then specify the name of your array. For example, the following code provides the similar
loop structure as the previous for-loop shown above:
view plaincopy to clipboardprint?

1. for (int num : aNums) {


2. String strToPrint = num;
3. }

As you can see, the for-each loop is slick. However, you no longer know the index while
iterating. Thus, it can't be used in all situations.

Conclusion
In this quick lesson you have learned about arrays in Java. Arrays are a fundamental data
structure used for Java programming that store an ordered number of objects of a given type in
an organized fashion. In Java, arrays are objects themselves and store references to objects,
making assignment and use easier (but subtly different) than how arrays are employed in other
programming languages.

Learn Java for Android Development:


Reflection Basics
Shane Conder & Lauren Darcey on Oct 13th 2010 with 7 comments

Tutorial Details

 Program: Java with Android Focus


 Difficulty: Beginner
 Estimated Completion Time: 45-60 Minutes

This entry is part 5 of 13 in the series Learn Java for Android Development

Learn Java for Android Development

 Learn Java for Android Development: Introduction to Java


 Learn Java for Android Development: Java Syntax
 Learn Java for Android Development: Checking Object Type with Instanceof
 Learn Java for Android Development: Working with Arrays
 Learn Java for Android Development: Reflection Basics
 Learn Java for Android Challenge: Iteration
 Learn Java for Android Development: Inner Classes
 Learn Java for Android Development: More On Inner Classes
 Learn Java for Android Development: Javadoc Code Documentation
 Learn Java for Android Development: String Basics
 Learn Java for Android Development: Date and Time Basics
 Learn Java for Android Challenge: Strings
 Learn Java for Android Development: Java Shorthand

In this tutorial, you’ll become familiar with the concept of Java reflection: the ability of a class or
object to examine details about its own implementation programmatically.

Android applications are written in the Java, a programming language that supports reflection—
the ability of an object to examine itself. In this tutorial, you’ll learn the basics of Java reflection,
including how to inspect the methods and fields of a given class, check for the availability of
specific methods, and other practical tasks you may need to use when developing for different
versions of the Android SDK.

What You’ll Need


Technically, you don’t need any tools to complete this tutorial but you will certainly need them
to develop Android applications.

To develop Android applications (or any Java applications, for that matter), you need a
development environment to write and build applications. Eclipse is a very popular development
environment (IDE) for Java and the preferred IDE for Android development. It’s freely available
for Windows, Mac, and Linux operating systems.
For complete instructions on how to install Eclipse (including which versions are supported) and
the Android SDK, see the Android developer website.

Why Use Reflection?


Reflection gives developers the flexibility to inspect and determine API characteristics at
runtime, instead of compile time. Within the security constraints imposed by Java (e.g. use of
public, protected, private), you can then construct objects, access fields, and invoke methods
dynamically. The Java Reflection APIs are available as part of the [Link] package,
which is included within the Android SDK for developers to use.

So what does this have to do with Android development? Well, with each new version of the
Android SDK, classes, interfaces, methods, etc. are added, updated, and (less frequently)
removed. However, Android developers often want to target devices running different versions
of Android with a simple application package. To do this, Android developers may use reflection
techniques to determine, at runtime, if a specific class or method is available before trying to use
it. This allows the developer to leverage new APIs where available while still supporting the
older devices—all in the same application.

Inspecting Classes
Java classes are represented at runtime using the Class ([Link]) class. This class
provides the starting point for all reflection APIs. Within this class, you’ll find many methods for
inspecting different aspects of a class, such as its fields, constructors, methods, permissions, and
more. You can also use the Class method called forName() to load a non-primitive class (e.g. not
int, but Integer) by name dynamically at runtime, instead of at compile time:

view plaincopy to clipboardprint?

1. String sClassName = "[Link]";


2. try {
3. Class classToInvestigate = [Link](sClassName);
4.
5. // Dynamically do stuff with this class
6. // List constructors, fields, methods, etc.
7.
8. } catch (ClassNotFoundException e) {
9. // Class not found!
10. } catch (Exception e) {
11. // Unknown exception
12. }

The class (in this case, NotificationManager) need not have the corresponding import statement
in your code; you are not compiling in this class into your application. Instead, the class loader
will load the class dynamically at runtime, if possible. You can then inspect this Class object and
use the reflection techniques described in the rest of this tutorial.

Inspecting the Constructors Available Within a Class


You can inspect the constructors available within a given Class. To get just the constructors that
are publicly available, use getConstructors(). However, if you want to inspect those methods
specifically declared within the class, whether they are public or not, use
getDeclaredConstructors() instead. Both methods return an array of Constructor
([Link]) objects.

For example, the following code iterates through the declared constructors of a class:

view plaincopy to clipboardprint?

1. Constructor[] aClassConstructors = [Link]();


2. for(Constructor c : aClassConstructors){
3. // Found a constructor c
4. }

Once you have a valid Constructor object, you can inspect its parameters and even declare a new
instance of the class using that constructor with the newInstance() method.

Inspecting the Fields Available Within a Class


You can inspect the fields (or attributes) available within a given Class. To get just the methods
that are publicly available, including inherited fields, use getFields(). However, if you want to
inspect those fields specifically declared within the class (and not inherited ones), whether they
are public or not, use getDeclaredFields() instead. Both methods return an array of Field
([Link]) objects.

For example, the following code iterates through the declared fields of a class:

view plaincopy to clipboardprint?

1. Field[] aClassFields = [Link]();


2. for(Field f : aClassFields){
3. // Found a field f
4. }

You can also check for a specific public field by name using the getField() method. For example,
to check for the EXTRA_CHANGED_PACKAGE_LIST field of the Intent class (which was
added in API Level 8, or Android 2.2), you could use:
view plaincopy to clipboardprint?
1. String sClassName = "[Link]";
2. try {
3. Class classToInvestigate = [Link](sClassName);
4. String strNewFieldName = "EXTRA_CHANGED_PACKAGE_LIST";
5. Field newIn22 = [Link](strNewFieldName);
6.
7. } catch (ClassNotFoundException e) {
8. // Class not found
9. } catch (NoSuchFieldException e) {
10. // Field does not exist, likely we are on Android 2.1 or older
11. // provide alternative functionality to support older devices
12. } catch (SecurityException e) {
13. // Access denied!
14. } catch (Exception e) {
15. // Unknown exception
16. }

Once you have a valid Field object, you can get its name using the toGenericString() method. If
you have the appropriate permissions, you can also access the value of that class field using the
appropriate get() and set() methods.

Inspecting the Methods Available Within a Class


You can inspect the methods available within a given Class. To get just the methods that are
publicly available, including inherited methods, use getMethods(). However, if you want to
inspect those methods specifically declared within the class (without inherited ones), whether
they are public or not, use getDeclaredMethods() instead. Both methods return an array of
Method ([Link]) objects.

For example, the following code iterates through the declared methods of a class:

view plaincopy to clipboardprint?

1. Method[] aClassMethods = [Link]();


2. for(Method m : aClassMethods)
3. {
4. // Found a method m
5. }

Once you have a valid Method object, you can get its name using the toGenericString() method.
You can also examine the parameters used by the method and the exceptions it can throw.
Finally, if you have the appropriate permissions, you can also call the method using the invoke()
method.

Inspecting Inner Classes


You can inspect the inner classes defined within a Class using getDeclaredClasses() method.
This method will return an array of Class ([Link]) objects declared within the parent
class. These classes can then be inspected like any other.

Inspecting Member Modifiers


You can also inspect the flags and security settings—called modifiers—associated with a given
Class, Field, or Method using the getModifiers() method. Interesting modifiers include whether
the component is public, private, protected, abstract, final, or static (amongst others).

For example, the following code checks the security modifiers of a class:

view plaincopy to clipboardprint?

1. int permissions = [Link]();


2.
3. if([Link](permissions)) {
4. // Class is Public
5. }
6. if([Link](permissions)) {
7. // Class is Protected
8. }
9. if([Link](permissions)) {
10. // Class is Private
11. }

Keep in mind that you cannot dynamically access or invoke any class, method, or field using
reflection that you would not normally be able to access at compile-time. In other words, regular
class security is still applied at runtime.

Inspecting Class Metadata


You can also inspect the metadata—called annotations—associated with a given class, field or
method using the getAnnotations() method. Interesting metadata associated with a class might
include information about deprecation, warnings, and overrides, among other things.

For example, the following code checks the metadata available for the AbsoluteLayout class.
Since this class was deprecated in Android 1.5, one of the annotations returned is
@[Link]() when this code is run on Android 2.2:

view plaincopy to clipboardprint?

1. String sClassName = "[Link]";


2. try {
3. Class classToInvestigate = [Link](sClassName);
4.
5. Annotation[] aAnnotations = [Link]();
6. for(Annotation a : aAnnotations)
7. {
8. // Found an annotation, use [Link]() to print it out
9. }
10.
11. } catch (ClassNotFoundException e) {
12. // Class not found!
13. } catch (Exception e) {
14. // Handle unknown exception!
15. }

Similarly, you could simply check for the existence of a specific annotation, such as deprecation,
by its type:
view plaincopy to clipboardprint?

1. if([Link]([Link]) == true)
2. {
3. // Class is deprecated!
4. }

Reflection: Handy for Debugging


You can also use reflection to assist with debugging. For example, you might want to use the
class keyword to access the underlying class data for a given type:

view plaincopy to clipboardprint?

1. import [Link];
2. …
3. String strClassName = [Link](); // [Link]

You can also get class information from a variable instance using the getClass() method of the
Object class (which is therefore inherited by all classes in Java):
view plaincopy to clipboardprint?

1. String silly = "Silly String!";


2. Class someKindOfClass = [Link]();
3. String strSillyClassName = [Link](); // [Link]

If you want to check the class of a variable, using instanceof is more appropriate. See the
previous tutorial on instanceof for more details.
Similarly, you might want to use the getClass() method with the this keyword to check the name
of the class you’re currently in and include this information as part of your debug logging to
LogCat:

view plaincopy to clipboardprint?

1. String strCurrentClass = [Link]().getName(); // e.g. the current Activity


2. Log.v(strCurrentClass, "Debug tag is current class.");

Why Not To Use Reflection


As you’ve seen, reflection can be used to great effect, especially when you are unsure if a
specific class or method is available at compile time. Reflection does, however, have some
drawbacks, including reduced performance and the loss of the strong typing and safe coding
practices enforced at compile time. It’s best to use reflection sparingly, but do use it when
needed.

Wrapping Up
Reflection is a powerful tool that Java developers can use to explore packages and APIs
programmatically at runtime. While reflection operations come at a cost, they give the developer
the flexibility that is sometimes essential for getting the job done. Android developers frequently
use these simple reflection techniques to test for the availability of specific classes, interfaces,
methods, and fields at runtime, enabling them to support different versions.

Learn Java for Android Challenge: Iteration


Shane Conder & Lauren Darcey on Oct 19th 2010 with 9 comments

Tutorial Details

 Technology: Java + Android SDK


 Difficulty: Beginner
 Estimated Completion Time: 20-30 minutes

Download Source Files


This entry is part 6 of 13 in the series Learn Java for Android Development

Learn Java for Android Development


 Learn Java for Android Development: Introduction to Java
 Learn Java for Android Development: Java Syntax
 Learn Java for Android Development: Checking Object Type with Instanceof
 Learn Java for Android Development: Working with Arrays
 Learn Java for Android Development: Reflection Basics
 Learn Java for Android Challenge: Iteration
 Learn Java for Android Development: Inner Classes
 Learn Java for Android Development: More On Inner Classes
 Learn Java for Android Development: Javadoc Code Documentation
 Learn Java for Android Development: String Basics
 Learn Java for Android Development: Date and Time Basics
 Learn Java for Android Challenge: Strings
 Learn Java for Android Development: Java Shorthand

You’ve read about how iteration works in Java. Test your new skills with this challenge: five
progressively difficult exercises that help you solidify your knowledge of the Java programming
language and Android development. That’s right, Android too! You may need to refer to other
Android tutorials that we’ve published on Mobiletuts+, but if you can complete this challenge
successfully you will know you are progressing nicely in your Java and Android SDK
understanding.

Setup
To prepare for this challenge, you’ll want to start with a basic Android application. Simply create
an Android application within Eclipse and edit its default Activity, specifically the onCreate()
method, to test the code from each of these challenges.

If what we’ve just asked of you is already too challenging, we would recommend taking a step
back. Start with some of the Android tutorials, such as Introduction to Android Development or
Beginning Android: Getting Started with Fortune Crunch. Once you’ve mastered setting up an
Android project, return and try these exercises.

Getting Started: Working with String Array Resources


At first, we considered using a simple string array for you to use to complete these iteration
challenges:

view plaincopy to clipboardprint?

1. String aColors[] = {"Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"};

However, there’s a much better way to store fixed arrays of values in Android: as resources. To
create a string array resource, you must first create String resources for each value. Next, create a
String Array resource using those String resources as elements. Use the <string-array> tag to
combine String resources into an array resource using child <item> tags for each element. For
instance, here’s an array of colors inside an Android resource file:
view plaincopy to clipboardprint?

1. <?xml version="1.0" encoding="utf-8"?>


2. <resources>
3. <string name="red">Red</string>
4. <string name="orange">Orange</string>
5. <string name="yellow">Yellow</string>
6. <string name="green">Green</string>
7. <string name="blue">Blue</string>
8. <string name="indigo">Indigo</string>
9. <string name="violet">Violet</string>
10. <string-array name="colorsArray">
11. <item>@string/red</item>
12. <item>@string/orange</item>
13. <item>@string/yellow</item>
14. <item>@string/green</item>
15. <item>@string/blue</item>
16. <item>@string/indigo</item>
17. <item>@string/violet</item>
18. </string-array>
19. </resources>

To load this array resource in your Activity class, use the getStringArray() method of the
Resources object. For instance:

1. String aColors[] = getResources().getStringArray([Link]);

Challenge #1: Warm-Up Challenge


Now you’re ready to get started. Load the string array from the resources, as discussed above.
Then, iterate through the array’s contents using a for() loop. Print each string to the Android
LogCat debug log using the Log.v() method.

Extra points if you use the shorthand version of for() loops, discussed in Learn Java for Android
Development: Working with Arrays.

Find the answer to this challenge in the challengeOne() method of the downloadable project.

Challenge #2: Stretch Your Skills


Iterate the same array as Challenge #1, but use a different iteration mechanism. For example, use
a while() loop instead. Print each string to the Android LogCat debug log using the Log.v()
method.
Find the answer to this challenge in the challengeTwo() method of the downloadable project.

Challenge #3: Reverse!


Iterate the same array backwards. Print each string to the Android LogCat debug log using the
Log.v() method.

HINT: Challenge #2 can help.

Find the answer to this challenge in the challengeThree() method of the downloadable project.

Challenge #4: It’s All About Character


Next, go back to the for() loop you created in Challenge #1. Update it to print out the individual
characters of each String as well. This challenge will require an inner for() loop.

HINT: You can use the toCharArray() method of the String class to retrieve a character array.

The answer to this challenge is in the challengeFour() method of the downloadable project.

Challenge #5: Reflect on How Far You’ve Come


For this final challenge, you’re going to need a bit of understanding about Java reflection. Use
reflection to iterate through the declared fields within the [Link] class using a for()
loop. Print each field name to the Android LogCat debug log using the Log.v() method.

HINT: Our short tutorial on Java reflection will teach you everything you need to know to
complete this challenge.

We’ve provided two different solutions for this challenge. The first solution assumes that the
package is imported and the compiler knows about the class. The second solution does not make
this assumption. These solutions are found in the challengeFiveA() and challengeFiveB()
methods of the downloadable project.

Conclusion
Android developers use iteration techniques on a regular basis to solve coding problems.
Iteration is frequently used to iterate arrays, data structures like lists, or database content using
cursors. Feel free to post your alternative answers (or any questions) in the comments section.

Best of luck!
Learn Java for Android Development: Inner
Classes
Shane Conder & Lauren Darcey on Oct 26th 2010 with 4 comments

Tutorial Details

 Program: Java with Android Focus


 Difficulty: Beginner
 Estimated Completion Time: 45-60 Minutes

This entry is part 7 of 13 in the series Learn Java for Android Development

Learn Java for Android Development

 Learn Java for Android Development: Introduction to Java


 Learn Java for Android Development: Java Syntax
 Learn Java for Android Development: Checking Object Type with Instanceof
 Learn Java for Android Development: Working with Arrays
 Learn Java for Android Development: Reflection Basics
 Learn Java for Android Challenge: Iteration
 Learn Java for Android Development: Inner Classes
 Learn Java for Android Development: More On Inner Classes
 Learn Java for Android Development: Javadoc Code Documentation
 Learn Java for Android Development: String Basics
 Learn Java for Android Development: Date and Time Basics
 Learn Java for Android Challenge: Strings
 Learn Java for Android Development: Java Shorthand

In this tutorial, you’ll become familiar with the concept of inner classes in Java—those classes
whose scope and definition are encompassed within another class. You’ll also learn about
anonymous inner classes, which are used quite frequently when developing with the Android
SDK.

Android applications are written in the Java, an object-oriented programming language. In this
tutorial, you’ll learn about inner classes, when and why to use them and how they work. You’ll
also learn how to create new objects dynamically using anonymous inner classes.

What You’ll Need


Technically, you don’t need any tools to complete this tutorial but you will certainly need them
to develop Android applications.
To develop Android applications (or any Java applications, for that matter), you need a
development environment to write and build applications. Eclipse is a very popular development
environment (IDE) for Java and the preferred IDE for Android development. It’s freely available
for Windows, Mac, and Linux operating systems.

For complete instructions on how to install Eclipse (including which versions are supported) and
the Android SDK, see the Android developer website.

What is an Inner Class?


Most classes in Java are top-level classes. These classes, and the objects they define, are stand-
alone. You can also create nested classes in order to clearly encapsulate and define subordinate
objects that only matter in the context of the outer class. Nested classes are called inner classes.

Inner classes can have all the features of a regular class, but their scope is limited. Inner classes
have another benefit: they have full access to the class in which they are nested—this feature
makes inner classes perfect for implementing adapter functionality like iterators.

Here’s an example of a top-level class with two inner classes:

view plaincopy to clipboardprint?

1. public class User {


2.
3. // User fields, including variables of type LoginInfo and UserPreferences
4. // Misc user methods
5.
6. class LoginInfo
7. {
8. // Login info fields
9. // Login/Logout methods
10. // Can access User fields/methods
11. }
12.
13. class Preferences
14. {
15. // User preference fields
16. // Get/Set preference methods
17. // Reset preferences method
18. // Can access User fields/methods
19. }
20. }

In this example, the User class has two inner classes: LoginInfo and Preferences. While all user-
related data and functionality could be defined in the User class, using the inner classes to
compartmentalize functionality can make code easier to read and maintain. The inner classes
LoginInfo and Preferences also have access to the protected/private fields and methods available
within the User class, which they might not otherwise have due to security, if they were defined
as stand-alone classes themselves.

It’s important to remember, though, that inner classes really only exist to help the developer
organize code; the compiler treats inner classes just like any other class, except that the inner
classes have a limited scope, and are therefore tethered to the class they are defined with. Said
another way, you would not be able to use or instantiate the LoginInfo or Preferences classes
except with an instance of the User class, but the inner classes could access any fields or methods
available in the outer class User, as needed.

Using Static Nested Classes


One particularly use for nested classes is static nested classes. A static inner class defines
behavior that is not tied to a specific object instance, but applies across all instances. For
example, we could add a third nested class, this time static, to the User class to control server-
related functionality:

view plaincopy to clipboardprint?

1. public class User {


2.
3. // User fields, including variables of type LoginInfo and UserPreferences
4. // Misc user methods
5.
6. class LoginInfo {}
7.
8. public static class ServerInfo {}
9. {
10. // Server info applies to all instances of User
11. }
12. }

Because it’s public, this static nested class can be instantiated using the following new statement:
view plaincopy to clipboardprint?

1. [Link] sInfo = new [Link]();

The outer class does not have to be instantiated to perform this instantiation, thus the use of the
class name. As such, a static nested class, unlike a non-static nested class (aka inner class) does
not have access to members of the outer class–they may not even be instantiated.

The Power of Anonymous Inner Classes


Android uses anonymous inner classes to great effect. Anonymous inner classes are basically
developer shorthand, allowing the developer to create, define, and use a custom object all in one
“line.” You may have seen examples of the use of anonymous inner class in sample code and not
even realized it.
To create an anonymous inner class, you only provide the right-hand side of the definition. Begin
with the new keyword, followed by the class or interface you wish to extend or implement,
followed by the class definition. This will create the class and return it as a value which you can
then use to call a method.
When we use an anonymous inner class, the object created does not get assigned a name (thus
the term anonymous). The side effect, of course, is that the object is used used just once. For
example, it’s common to use an anonymous inner class to construct a custom version of an
object as a return value. For example, here we extend the Truck class (assuming its defined
elsewhere and has a field called mpg and two methods, start() and stop():

view plaincopy to clipboardprint?

1. Truck getTruck()
2. {
3. return new Truck()
4. {
5. int mpg = 3;
6. void start() { /* start implementation */ }
7. void stop() { /* stop implementation */ }
8. };
9. }

Now let’s look at practical examples of anonymous inner classes used in Android.

Using an Anonymous Inner Class to Define a Listener


Android developers often use anonymous inner classes to define specialized listeners, which
register callbacks for specific behavior when an event occurs. For example, to listen for clicks on
a View control, the developer must call the setOnClickListener() method, which takes a single
parameter: a [Link] object.
Developers routinely use the anonymous inner class technique to create, define and use their
custom [Link], as follows:

view plaincopy to clipboardprint?

1. Button aButton = (Button) findViewById([Link]);


2. [Link](new [Link]() {
3. public void onClick(View v) {
4. // User clicked my button, do something here!
5. }
6. });
Using an Anonymous Inner Class to Start a Thread
Let’s look at another example. It’s quite common to define a new Thread class, provide the
implementation of its run() method, and start that thread, all in one go:

view plaincopy to clipboardprint?

1. new Thread() {
2. public void run()
3. {
4. doWorkHere();
5. }
6. }.start();

Using a Named Inner Class


Using anonymous inner classes for listeners in Android is so common that it is practically second
nature to do so. Why, then, would you not want to use them? Let’s answer this through a
hypothetical example.
Let’s say you have a screen that has 100 buttons on it (we did say hypothetical, right?). Now,
let’s say each button, when pressed, does the exact same thing. In this case, we’ll just listen for
clicks and Toast the text from the View object passed in (the text shown on the Button that was
clicked):
Here’s pseudo code to do that:

view plaincopy to clipboardprint?

1. Button[] buttons = getAllOneHundredButtonsAsArray();


2. for (Button button : buttons) {
3. [Link](new [Link]() {
4. public void onClick(View v) {
5. showToast([Link]());
6. }
7. });
8. }

Short and elegant, so what’s wrong with it? At each iteration, a new OnClickListener object is
instantiated. Since each one is exactly the same, there is no good reason to create 100 of them.
Instead, you can create a single, named, inner class, instantiate it once, then pass that to the
setOnClickListener() method. For instance:
view plaincopy to clipboardprint?

1. class MyActivity extends Activity {


2.
3. public void myMethod() {
4. MyClickHandler handler = new MyClickHandler();
5. Button[] buttons = getAllOneHundredButtonsAsArray();
6. for (Button button : buttons) {
7. [Link](handler);
8. }
9. }
10.
11. class MyClickHandler implements [Link] {
12. public void onClick(View v) {
13. showToast(((Button) v).getText());
14. }
15. }
16. }

If you prefer anonymity, you can still assign an anonymous inner class to a variable and use that,
like so:
view plaincopy to clipboardprint?

1. class MyActivity extends Activity {


2.
3. public void myMethod() {
4. [Link] handler = new [Link]() {
5. public void onClick(View v) {
6. showToast(((Button) v).getText());
7. }
8. };
9.
10. Button[] buttons = getAllOneHundredButtonsAsArray();
11. for (Button button : buttons) {
12. [Link](handler);
13. }
14. }
15. }

The method is up to you, but keep in mind the potential memory and performance issues that
instantiating a bunch of objects may have.

A Note on Nuances
This tutorial is meant to be an introductory guide to inner classes in Java. There are style
considerations and nuances when using inner classes in different and creative ways. Even beyond
that, you can explore further to learn more about the internal effects and marginal performance
differences that can show up when you use nested classes in different ways. All of this, however,
is well beyond the scope of this tutorial.
A Quick Note On Terminology
Although we have tried to be consistent with the terminology on nested and inner classes, the
terminology is not always consistent from various online and offline resources. The following
are a list of terms from the current Sun/Oracle documentation, which is as good as any for being
authoritative on Java:

 Nested Class: a class defined inside another class


 Static Nested Class: a static class defined inside another class
 Inner class: a non-static nested class defined inside another class
 Local Inner Class: a class defined within a method
 Anonymous Inner Class: an unnamed class defined within a method

Confused? You can use the [Link] methods called isLocalClass() and isAnonymous()
class on instantiated classes to determine a couple of these properties. An Oracle blog entry
attempts to clarify the situation a little, too, with a nice Venn diagram.

Wrapping Up
The Java programming language supports nested classes, allowing the developer great flexibility
in defining objects. Inner classes can be used to organize class functionality or to define
specialized behaviors that would otherwise require the developer to expose class data and
functionality that really shouldn’t be exposed. Static inner classes can be used to define fields
and functionality that apply across all instances of a class. Finally, anonymous inner classes
provide a useful shorthand for developers who want to create, define and use a custom object all
at once.

Learn Java for Android Development: More


On Inner Classes
Shane Conder & Lauren Darcey on Nov 3rd 2010 with 2 comments

Tutorial Details

 Technology: Java with Android Focus


 Difficulty: Beginner
 Estimated Completion Time: 15 minutes

This entry is part 8 of 13 in the series Learn Java for Android Development

Learn Java for Android Development


 Learn Java for Android Development: Introduction to Java
 Learn Java for Android Development: Java Syntax
 Learn Java for Android Development: Checking Object Type with Instanceof
 Learn Java for Android Development: Working with Arrays
 Learn Java for Android Development: Reflection Basics
 Learn Java for Android Challenge: Iteration
 Learn Java for Android Development: Inner Classes
 Learn Java for Android Development: More On Inner Classes
 Learn Java for Android Development: Javadoc Code Documentation
 Learn Java for Android Development: String Basics
 Learn Java for Android Development: Date and Time Basics
 Learn Java for Android Challenge: Strings
 Learn Java for Android Development: Java Shorthand

This quick lesson discusses a number of tips for working with inner classes in Java. This lesson
is part of an ongoing series of tutorials for developers learning Java in order to develop Android
applications.

What are (Anonymous) Inner Classes?


In Java, classes can be nested within one another in order to organize data and functionality in an
orderly fashion. Anonymous inner classes are basically developer shorthand, allowing the
developer to create, define, and use a custom object all in one go. Anonymous inner classes are
frequently used in Android to define handlers for controls, define and launch new threads, and
create and return custom objects in methods without cluttering code with unnecessary setup.

For a thorough discussion of nested and inner classes, including anonymous inner classes, see
our tutorial called Learn Java for Android Development: Inner Classes

Accessing Outside Variables with the Final Keyword


Sometimes you want to access information available outside of the inner class. Consider the
following example. You’ve got a screen with two controls: a Button and a TextView. Each time
the user clicks on the Button control, the TextView control is updated with the current time.
Within the Activity class associated with this layout, you could implement this functionality as
follows:

view plaincopy to clipboardprint?

1. Button myButton = (Button) findViewById([Link]);


2. [Link](new [Link]() {
3. public void onClick(View v) {
4. SimpleDateFormat formatter = new SimpleDateFormat("h:mm:ss a");
5. String strWhen = [Link](new Date());
6. TextView myTextview = (TextView)
7. findViewById([Link]);
8. [Link]("Clicked at " + strWhen);
9. }
10. });

The above code will run and behave as expected. However, let’s say you really wanted to declare
the TextView control outside the inner class and use it for other purposes as well. Perhaps you’d
try to do this instead:
view plaincopy to clipboardprint?

1. TextView myTextview = (TextView) findViewById([Link]);


2. Button myButton = (Button) findViewById([Link]);
3. [Link](new [Link]() {
4. public void onClick(View v) {
5. SimpleDateFormat formatter = new SimpleDateFormat("h:mm:ss a");
6. String strWhen = [Link](new Date());
7. [Link]("Clicked at " + strWhen);
8. }
9. });

Unfortunately, this won’t compile. Instead, you’ll get the compile error “Cannot refer to a non-
final variable myTextview inside an inner class defined in a different method”. As the error
suggests, what you need to do is make the TextView variable final, so that it is accessible within
the inner class’s onClick() method:
view plaincopy to clipboardprint?

1. final TextView myTextview = (TextView) findViewById([Link]);


2. Button myButton = (Button) findViewById([Link]);
3. [Link](new [Link]() {
4. public void onClick(View v) {
5. SimpleDateFormat formatter = new SimpleDateFormat("h:mm:ss a");
6. String strWhen = [Link](new Date());
7. [Link]("Clicked at " + strWhen);
8. }
9. });

This code will indeed compile and run as expected.

Working with Final Variables in Java


By making the TextView variable final in the previous example, you’ve made it available to the
anonymous inner class (or any inner class defined within its scope, for that matter). Here are
some other things to know about final variables:
 You cannot change the value (r-value) of a final variable. For example, if you tried to
assign the myTextview variable to another control within the onClick() method of the
inner class, you would get the compile error “The final local variable myTextview cannot
be assigned, since it is defined in an enclosing type.”
 You can call a final variable’s methods, provided you have access. This is what allows us
to make the call to the TextView’s setText() method. This does not change the value of
the variable myTextview, it simply changes what is displayed to the screen—a subtle but
important difference. (The reason for this is simply that the reference to the object can’t
change, but the object itself can change through its methods.)
 A final variable’s value need not be known at compile time, whereas a static variable is
known at compile time.
 The final keyword is often paired with the static variable (a field or variable tied to all
instances of a class, instead of a single instance) to create a constant for use within your
application, as in: public static final String DEBUG_TAG, used for LogCat logging
purposes throughout your Activity.

Inner Classes and the “This” variable


In Java, you can use the special this reference to refer to the specific instance of an object. So
what happens when you have a class with an inner class, or, for that matter, an anonymous inner
class? Well, the inner class can access the special this instance of the enclosing class, and it has a
this reference of its own as well. To access the this instance for the inner class, simply use the
this syntax. To access the this instance of the enclosing class, you need to tack on the name of
the enclosing class, then a dot, then this. For example:

view plaincopy to clipboardprint?

1. [Link]

Take a look at the full implementation of the anonymous inner class, as discussed above, in the
full context of its enclosing class, here called ClassChaosActivity:
view plaincopy to clipboardprint?

1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
8. import [Link];
9. import [Link];
10. import [Link];
11. import [Link];
12.
13. public class ClassChaosActivity extends Activity {
14.
15. public static final String DEBUG_TAG = "MyLoggingTag";
16. /** Called when the activity is first created. */
17. @Override
18. public void onCreate(Bundle savedInstanceState) {
19. [Link](savedInstanceState);
20. setContentView([Link]);
21.
22. final TextView myTextview = (TextView) findViewById([Link]);
23. Button myButton = (Button) findViewById([Link]);
24. [Link](new [Link]() {
25. public void onClick(View v) {
26.
27. SimpleDateFormat formatter = new SimpleDateFormat("h:mm:ss a");
28. String strWhen = [Link](new Date());
29. [Link]("Clicked at " + strWhen);
30.
31. Log.v(DEBUG_TAG, "this Class name: " + [Link]().getName());
32. Log.v(DEBUG_TAG, "this extends interface named: " + [Link]().getInte
rfaces()[0].getName());
33. Log.v(DEBUG_TAG, "this Enclosing class name: " +[Link]().getEnclosi
ngClass().getName());
34. Log.v(DEBUG_TAG, "this Is anonymous class? " + [Link]().isAnonymo
usClass());
35.
36. Log.v(DEBUG_TAG, "[Link] Class name: " + ClassChaosAc
[Link]().getName());
37. Log.v(DEBUG_TAG, "[Link] Super Class name: " + ClassCh
[Link]().getSuperclass().getName());
38. Log.v(DEBUG_TAG, "[Link] Is anonymous class? " + Class
[Link]().isAnonymousClass());
39. }
40. });
41.
42. }
43. }

The log output for the button click proceeds as follows:


view plaincopy to clipboardprint?

1. 10-24 [Link].075: VERBOSE/MyLoggingTag(751): this Class name: [Link]


[Link]$1
2. 10-24 [Link].085: VERBOSE/MyLoggingTag(751): this extends interface named: andr
[Link]$OnClickListener
3. 10-24 [Link].085: VERBOSE/MyLoggingTag(751): this Enclosing class name: com.a
[Link]
4. 10-24 [Link].095: VERBOSE/MyLoggingTag(751): this Is anonymous class? true
5. 10-24 [Link].095: VERBOSE/MyLoggingTag(751): [Link] Class na
me: [Link]
6. 10-24 [Link].105: VERBOSE/MyLoggingTag(751): [Link] Super Cl
ass name: [Link]
7. 10-24 [Link].105: VERBOSE/MyLoggingTag(751): [Link] Is anony
mous class? false

As you can see, the this keyword on its own refers to the “closest” class—the inner class.
Although the inner class is anonymous, Java does give it a number ClassChaosActivity$1 to
keep track of it. While not useful to developers per se, this shows that the anonymous inner class
is treated like any other class internally. Meanwhile, we access the enclosing class instance using
the [Link] syntax.

Conclusion
In this quick lesson you have learned several tips to help you use inner classes and anonymous
inner classes more skillfully. You learned that inner classes can access variables declared outside
their scope, provided the variables are marked as final and therefore unchangeable. You also
learned about the special syntax related to the this keyword when it comes to accessing inner
class instance data as well as its enclosing class instance data.

Learn Java for Android Development:


Javadoc Code Documentation
Shane Conder & Lauren Darcey on Nov 16th 2010 with 4 comments

Tutorial Details

 Difficulty: Beginner
 Estimated Completion Time: 15-20 minutes
 Technology: Java with Android Focus

This entry is part 9 of 13 in the series Learn Java for Android Development

Learn Java for Android Development

 Learn Java for Android Development: Introduction to Java


 Learn Java for Android Development: Java Syntax
 Learn Java for Android Development: Checking Object Type with Instanceof
 Learn Java for Android Development: Working with Arrays
 Learn Java for Android Development: Reflection Basics
 Learn Java for Android Challenge: Iteration
 Learn Java for Android Development: Inner Classes
 Learn Java for Android Development: More On Inner Classes
 Learn Java for Android Development: Javadoc Code Documentation
 Learn Java for Android Development: String Basics
 Learn Java for Android Development: Date and Time Basics
 Learn Java for Android Challenge: Strings
 Learn Java for Android Development: Java Shorthand

This quick lesson covers Javadoc, a helpful tool for generating documentation from your Java
source files. This lesson is part of an ongoing series of tutorials for developers learning Java in
order to develop Android applications.

What is Javadoc?
Javadoc is a utility provided with the Java SDK that allows developers to generate code
documentation from Java source files. Development environments like Eclipse have built-in
support for Javadoc and can generate searchable HTML reference materials from Javadoc-style
comments. In fact, the Android SDK reference is a form of Javadoc documentation.
How Does Javadoc Work?
Javadoc documentation uses a combination of processing the source code (and inspecting types,
parameters, etc.) and reading special comment tags that the developer provides as metadata
associated with a section of code.
A Javadoc-style comment must come just before the code it is associated with. For example, a
Javadoc comment for a class should be just above the class declaration and a comment for a
method should be just above the method declaration. Each comment should begin with a short
description, followed by an option longer description. Then you can include an number of
different metadata tags, which must be supplied in a specific order. Some important tags include:

 @author – who wrote this code


 @version – when was it changed
 @param – describe method parameters
 @return – describe method return values
 @throws – describe exceptions thrown
 @see – link to other, related items (e.g. “See also…”)
 @since – describe when code was introduced (e.g. API Level)
 @deprecated – describe deprecated item and what alternative to use instead

You can also create your own custom tags for use in documentation.

Generate Javadoc-style Comments in Eclipse


While you are writing code in Eclipse, you can generate a Javadoc –style comment by selecting
the item you want to comment (a class name, method name, etc.) and pressing Alt-Shift-J (Cmd-
Shift-J on a Mac). This will create a basic Javadoc-style comment for you to fill in the details.

Simple Javadoc Class Comments


Let’s look at an example. Here’s a simple Javadoc comment that describes a class:

view plaincopy to clipboardprint?

1. /**
2. * Activity for loading layout resources
3. *
4. * This activity is used to display different layout resources for a tutorial on user interface
design.
5. *
6. * @author LED
7. * @version 2010.1105
8. * @since 1.0
9. */
10. public class LayoutActivity extends Activity {

Here’s what it will look like when you generate the Javadoc documentation:
Simple Javadoc Field Comments
Let’s look at an example. Here’s a simple Javadoc comment that describes a field within a class:

view plaincopy to clipboardprint?

1. /**
2. * Debug Tag for use logging debug output to LogCat
3. */
4. private static final String DEBUG_TAG = "MyActivityDebugTag";

Here’s what it will look like when you generate the Javadoc documentation:

Simple Javadoc Method Comments


Now let’s look at two examples of method comments. Here’s a simple Javadoc comment that
describes a method within a class:

view plaincopy to clipboardprint?

1. /**
2. * Method that adds two integers together
3. *
4. * @param a The first integer to add
5. * @param b The second integer to add
6. * @return The resulting sum of a and b
7. */
8. public int addIntegers(int a, int b)
9. {
10. return (a+b);
11. }

Now let’s look at a method that returns void, but throws an exception:
view plaincopy to clipboardprint?

1. /**
2. * This method simply throws an Exception if the incoming parameter a is not a positive
number, just for fun.
3. *
4. * @param a Whether or not to throw an exception
5. * @throws Exception
6. */
7. public void throwException(boolean shouldThrow) throws Exception
8. {
9. if(shouldThrow == true)
10. {
11. throw new Exception();
12. }
13. }

Here’s what it will look like when you generate the Javadoc documentation for these two
methods:
Generating Javadoc Documentation in Eclipse
To generate Javadoc code documentation in Eclipse, go to the Project menu and choose the
“Generate Javadoc…” option. This will launch a wizard that allows you to choose the projects to
generate documentation for.

From this wizard, you should point Eclipse at the appropriate [Link] command line tool
(you’ll find it in your JDK’s /bin directory). You can also configure some documentation
settings, such as whether to document all code, or only visible classes, members, etc. Finally,
choose a destination for your documentation files.
Even without generating the Javadoc files, Eclipse will show the Javadoc-style documentation
when you hover over your methods and such, as shown in the figure below.

Learning More about Javadoc


You can find out more from the Javadoc reference at the Oracle website. There is also a helpful
Javadoc FAQ available.

Conclusion
In this quick lesson you have learned about Javadoc, a powerful tool used by Java developers to
document source code thoroughly for reference and maintenance purposes. Eclipse, the
development environment used by many Android developers, has built-in support for Javadoc.

Learn Java for Android Development: String


Basics
Shane Conder & Lauren Darcey on Nov 22nd 2010 with 4 comments

Tutorial Details

 Program: Java with Android Focus


 Difficulty: Beginner
 Estimated Completion Time: 45-60 Minutes
This entry is part 10 of 13 in the series Learn Java for Android Development

Learn Java for Android Development

 Learn Java for Android Development: Introduction to Java


 Learn Java for Android Development: Java Syntax
 Learn Java for Android Development: Checking Object Type with Instanceof
 Learn Java for Android Development: Working with Arrays
 Learn Java for Android Development: Reflection Basics
 Learn Java for Android Challenge: Iteration
 Learn Java for Android Development: Inner Classes
 Learn Java for Android Development: More On Inner Classes
 Learn Java for Android Development: Javadoc Code Documentation
 Learn Java for Android Development: String Basics
 Learn Java for Android Development: Date and Time Basics
 Learn Java for Android Challenge: Strings
 Learn Java for Android Development: Java Shorthand

In this tutorial, you’ll become familiar with one of the most important programming data
structures (types) in Java—the String. String variables can be used to store the textual (letters,
numbers, symbols) data associated with a program.

Android applications are written in the Java, a programming language. Java has a number of
primitive data types for different kinds of numbers (integers, floats, etc.), Boolean values, and
single characters. In addition to storing textual data as arrays or characters, Java also includes a
powerful object class called String ([Link]), which encapsulates textual data neatly and
can be used to manipulate content. In this tutorial, you’ll learn how to create, use and manipulate
strings in different ways, including how to store them as Android project resources.

What You’ll Need


Technically, you don’t need any tools to complete this tutorial but you will certainly need them
to develop Android applications.

To develop Android applications (or any Java applications, for that matter), you need a
development environment to write and build applications. Eclipse is a very popular development
environment (IDE) for Java and the preferred IDE for Android development. It’s freely available
for Windows, Mac, and Linux operating systems.

For complete instructions on how to install Eclipse (including which versions are supported) and
the Android SDK, see the Android developer website.

What is a String?
At the most fundamental level, Java programs are broken into functionality and data. Much
human-readable data comes in the forms of words, characters, punctuation, numbers and so on.
Basically, anything the user can type on a keyboard. Programmers call this storage of textual
content “string data”, but the data itself can be stored using a variety of different data structures,
depending on your requirements:

 The Java String class ([Link]) is a utility class for storing string data that will
not be modified.
 The Java StringBuilder class ([Link]) is a utility class for storing string
data that will be modified; used when concurrency is not an issue.
 The Java StringBuffer class ([Link]) is a utility class for storing string
data that will be modified; used when concurrency is an issue.
 An array of char primitives or Character ([Link]) variables
 An array of byte primitives or Byte ([Link]) variables
 Various other data structures and object classes can be used to store string data

As you can see, there are numerous ways to store string data in Java. For example, the following
Java variables represent a string of vowel characters in different ways (as bytes, characters,
Unicode representations or sub-strings):

view plaincopy to clipboardprint?

1. String strVowels = "aeiou";


2. char astrVowels[] = { 'a', 'e', 'i', 'o', 'u' };
3. byte abyteVowels[] = { 'a', 'e', 'i', 'o', 'u' };
4. byte abyteVowelsU[] = { '\u0061', '\u0065','\u0069','\u006F','\u0075' };
5. String uVowels = new String("\u0061\u0065\u0069\u006F\u0075");
6. CharSequence csVowels = (CharSequence) new String("aeiou");
7. StringBuffer sbVowels = new StringBuffer("a" + "e" + "iou");
8. StringBuilder sVowelBuilder = new StringBuilder();
9. [Link]('a');
10. [Link]("eio");
11. [Link]('\u0075');

The String class is the convenience class used most often, especially by beginners. You’ll also
want to have a passing understanding of the CharSequence ([Link]) interface,
as it is often used when working with Android resources.

Working with the String Class


The String class is available as part of the [Link] package, which is included within the
Android SDK for developers to use. The complete documentation for the String class can be
found with the Android SDK documentation.
The String class represents an immutable (unchangeable) sequence of Unicode (16-bit encoding)
characters, appropriate for storing characters in any language (English, German, Japanese, and so
on).

So what does this have to do with Android development? Well, strings are used to store content
displayed on application screens, or to store the input taken in from a user. Android developers
are constantly loading, creating, and manipulating string data. So let’s look at some of the stuff
we can do with the String class.

Creating Strings
The String class has numerous constructors, for creating and instantiating string variables. String
variables can be set to empty using the null keyword. You can also set its content from byte,
character, or other String data. For example, here are some ways to create String variables for
use within your applications (some are initialized from the variables, like uVowels and
sVowelBuilder, defined earlier in this tutorial):

view plaincopy to clipboardprint?

1. String strVowels1 = "aeiou";


2. String strVowels2 = new String("aeiou");
3. String strVowels3 = new String(sVowelBuilder);
4. String strVowels4 = new String(sbVowels);
5. String strVowels5 = new String(uVowels);
6. String strVowels6 = new String(abyteVowels2);
7. String strVowels7 = new String(abyteVowelsU);
8. String strVowels8 = new String("a" + "e" + "iou");
9. String strVowels9 = new String( new char[]{'\u0061',
10. '\u0065','\u0069','\u006F','\u0075'});
11. String strVowels10 = new String(new byte[]{ '\u0061',
12. '\u0065','\u0069','\u006F','\u0075' });

Using Android String Resources


You can also load strings from Android application resources, provided you have stored them
correctly. For example, you can load the string resource for the application name into a String
variable as follows:

1. String strAppName = getResources().getString([Link].app_name);

This requires that the Android application in question contains a string resource named
app_name somewhere in the /res/values project directory hierarchy. For example, a file called
/res/values/[Link] which contains the following XML string definition:
view plaincopy to clipboardprint?
1. <?xml version="1.0" encoding="utf-8"?>
2. <resources>
3. <string name="app_name">My Android App Name!</string>
4. </resources>

Simple String Iteration


Now let’s look at some of the cool stuff you can do to String objects. First, let’s focus on the
features available within the String class itself.

It’s helpful to think of a String as a sequence of characters. As such, you sometimes want to
iterate through its contents, one character at a time. There are numerous ways to do this, but one
simple way is to use a for() loop. You can take advantage of the String’s length() method to
determine how many characters you’ve got, and the charAt() method to retrieve a specific
character by its index, much like you would an array index. For example:

view plaincopy to clipboardprint?

1. String strVowels = "AEIOU";


2. for (int i = 0; i < [Link](); i++) {
3. char curChar = [Link](i);
4. }

String Modifications: The Basics


As mentioned earlier, String variables are immutable, or unchangeable. That is not to say you
cannot manipulate the textual contents of a String variable, but each method that does so returns
a new String variable. Some common examples of String class methods that generate new String
variables include:

 The concat() method is used to concatenate, or combine, two strings into a new String
object. Note: You can also use the + operator to create a new String object from parts as
well.
 The format() method allows you to create parameterized string templates (a more
advanced topic for future discussion)
 The replace() and replaceFirst() methods are used to replace one character or substring
with another substring. The replaceAll() method supports regular expression pattern
matching.
 The split() method is helpful for breaking a larger String into numerous substrings. For
example, you could break up a comma-delimited list into an array of String objects, one
for each list item.
 The substring() method is used to extract only part of the original String object.
 The toUpperCase() and toLowerCase() methods are used to change the String’s case,
especially useful for normalizing strings.
 The trim() method is used to hack off (remove) any whitespace before or after the String
contents.

Keep in mind that each of these methods allocates a new String object instance to store the result.
The original String variable remains unchanged.

String Modifications: Converting to Upper and Lowercase


Sometimes you want to convert your string to uppercase or lowercase. One reason you might
want to change the case of a string is to normalize the string to make case-insensitive searching
or matching easier to implement.

1. String strUpperCaseVersion = [Link]();


2. String strLowerCaseVersion = [Link]();

Note that here you have created two new String variables for use. The original String variable,
strVowels, remains unchanged.

String Modifications: Splitting


Sometimes you want to quickly parse a string into substrings. You might do this to extract the
individual words from a sentence, or a delimited list of tags, etc. You can use simple regular
expressions with the split() function for this purpose. For example, the following code extracts
the individual words (colors) from a String:

view plaincopy to clipboardprint?

1. String someWords = "Red Orange Yellow Green Blue Indigo";


2. String aColors[] = [Link](" ");

If you were to print out the contents of the String array called aColors, you would see that:
view plaincopy to clipboardprint?

1. aColors[0]=Red
2. aColors[1]=Orange
3. aColors[2]=Yellow
4. aColors[3]=Green
5. aColors[4]=Blue
6. aColors[5]=Indigo

Note that here you have created a new array containing 6 new String variables for use.

Simple String Matching


You can check if two strings match using the String class’s compareTo() method. This method
will return 0 if, and only if, the two strings are identical:

view plaincopy to clipboardprint?

1. String strVowels = "AEIOU";


2. if([Link]("AEIOU") == 0)
3. {
4. // Strings match! (This code will execute)
5. } else {
6. // Strings don’t match!
7. }

Note that the compareTo() method is case-sensitive. Consider converting both sides of your
comparison to one case before comparing them, unless you are specifically looking for one case.
If you don’t care about case, you can also use the compareToIgnoreCase() method instead of the
compareTo() method:
view plaincopy to clipboardprint?

1. String strVowels = "AEIOU";


2. if([Link] ("aeiou")== 0)
3. {
4. // Strings match! (This code will execute)
5. } else {
6. // Strings don’t match!
7. }

Simple String Searching


Sometimes you want to search a string for a character or substring. There are many other ways to
perform string matching and searching, allowing you to build whatever search methods you
desire. You can also hunt for specific characters or substrings using the indexOf() and
lastIndexOf() methods, check if a string begins or ends with a substring using the startsWith()
and endsWith() methods. Finally, the matches() method supports regular expression matching.

Here we use the contains() method to determine if a specific substring exists:

view plaincopy to clipboardprint?

1. if([Link]("IOU")==true)
2. {
3. // String contains IOU sub-string!
4. }

If you don’t care about case, use the compareToIgnoreCase() method instead:
view plaincopy to clipboardprint?
1. String strVowels = "AEIOU";
2. if(strVowels. compareToIgnoreCase ("aeiou")== 0)
3. {
4. // Strings match! (This code will execute)
5. } else {
6. // Strings don’t match!
7. }

TIP: When implementing matching and searching functionality in your applications, don’t forget
to do any preprocessing string manipulation necessary to rule out upper/lower/mixed case string
issues before searching. User input normalization can be done as part of the input validation
process, keeping your code as simple and maintainable as possible.

Strings and Other Data Types


The String object is so fundamental to Java that every class, due to being derived from the root
class called Object ([Link]), has a toString() method to create a useful string
representation of their value. Classes that don't have a reasonable string representation usually
return some identifier or debug information as to the type of class. Those that do have a
reasonable string representation, such as a number string from an Integer object, return the
textual representation of the encapsulated number. When concatenated with a String, such as
with the plus (+) operator described above, the toString() method results are used by default. For
example:

view plaincopy to clipboardprint?

1. Integer iNum = new Integer(123);


2. String sText = "The number one-two-three = ";
3. String sFullText = sText + iNum;
4. String sFullText2 = sText + [Link]();

Both the strings (sFullText and sFullText2) have the same value, "The number one-two-three =
123". Many such objects can also work in reverse. That is, they can parse a String representation
and convert it to the native type the object is representing. For instace, again with the Integer
class, the parseInt() method can be used to get a new Integer object based on the string
representation.

Strings and Performance


As you’ve seen, strings can be used to great effect. String creation and manipulation does,
however, have some drawbacks. Imprudent String manipulation can have negative performance
implications for your application. It’s a basic design principle of Java to not create objects you
don’t need. You can see that string manipulation and modifications can result in a lot of String
variables floating around. Here are some tips for good string usage:
 Don’t create String variables you don’t need, especially temporary ones.
 Use the StringBuilder and StringBuffer classes to generate string contents from the
ground up.
 Review the performance suggestions available on the Android Developer website.
 Use static final String constants for String values known at compile time.

Wrapping Up
Strings are an important data type that Android developers use to store textual data. String data,
whether it be a sequence of characters, numbers, symbols, or some mix thereof, can be stored in
a variety of ways, but the String class is the primary utility class used for this purpose. The String
class, and it’s helper classes like StringBuilder, contain a robust set of methods for use with
strings, allow their contents to be searched or modified.

Learn Java for Android Development: Date


and Time Basics
Shane Conder & Lauren Darcey on Dec 6th 2010 with 1 comment

Tutorial Details

 Program: Java with Android Focus


 Difficulty: Beginner
 Estimated Completion Time: 45-60 Minutes

This entry is part 11 of 13 in the series Learn Java for Android Development

Learn Java for Android Development

 Learn Java for Android Development: Introduction to Java


 Learn Java for Android Development: Java Syntax
 Learn Java for Android Development: Checking Object Type with Instanceof
 Learn Java for Android Development: Working with Arrays
 Learn Java for Android Development: Reflection Basics
 Learn Java for Android Challenge: Iteration
 Learn Java for Android Development: Inner Classes
 Learn Java for Android Development: More On Inner Classes
 Learn Java for Android Development: Javadoc Code Documentation
 Learn Java for Android Development: String Basics
 Learn Java for Android Development: Date and Time Basics
 Learn Java for Android Challenge: Strings
 Learn Java for Android Development: Java Shorthand
In this tutorial, you’ll learn to work with dates and times in Java and within Android
applications. Date and time data can be determined, modified, and stored in a variety of ways.

Android applications are written in the Java, a programming language. Java has a number of
primitive data types for different kinds of numbers (integers, floats, etc.), Boolean values, and
single characters. Java also includes numerous classes for storing, formatting and modifying date
and time data for use within your Android applications. In this tutorial, you’ll learn how to
determine the current date and time, store date and time data and display it in a number of ways.

What You’ll Need


Technically, you don’t need any tools to complete this tutorial but you will certainly need them
to develop Android applications.

To develop Android applications (or any Java applications, for that matter), you need a
development environment to write and build applications. Eclipse is a very popular development
environment (IDE) for Java and the preferred IDE for Android development. It’s freely available
for Windows, Mac, and Linux operating systems.

For complete instructions on how to install Eclipse (including which versions are supported) and
the Android SDK, see the Android developer website.

What is a Date or Time, Really?


First things first: the date and the time are basically two parts of the same piece of data (a point
in time). When it comes to storing dates and times in a computer, it can be helpful to think back
to your first computer class and recall that all data on a computer is made up of “ones and zeros”.
Computers (and Android devices are no exception) do not really have a sense of time like people
do, but instead keep a numeric representation of the current date or time (always ticking forward,
one millisecond at a time) and then format this information in different ways to suit specific
purposes. After all, a single instant in time is interpreted differently depending upon your time
zone or location, whether or not you (or your area) recognize daylight savings, and various other
factors.

Add to this fact that dates and times are displayed differently in different cultures and locales.
For example, in the United States, we often format our dates like this: April 6th, 1981, or
04/06/1981 whereas in Europe, the day normally precedes the month, like this: 6 April, 1981, or
06/04/1981. Similarly, some countries have the concept of AM and PM with a 12-hour, whereas
others simply use a 24-hour clock.

Computers, including Android devices, calculate times and dates as a single number (a long)—
which grows as time passes. The number itself equates to the number of milliseconds elapsed
since a specific date in the past. In this case, the point in time at which the “time” started ticking
is: midnight, January 1, 1970. This mechanism is referred to as Unix time, or POSIX time.
What’s a Developer to Do?
Pop quiz! Which of the following strings correctly represents the 4th month of the (Gregorian)
calendar year: A, April, APR, Apr, 4, or 04? The answer? All of them. Already, working with
dates and times seems a bit complicated, doesn’t it? In fact, we did a quick perusal of all the Java
reference books in our office (not insubstantial) and very few cover dates and times in any
substantial way. But don’t panic. Just accept the fact that, as a developer, you will have to
expend a bit of effort towards satisfying two goals:

1. Your External Goal: To allow the user to work with the date and time formats they are most
comfortable with, or at least familiar with.
2. Your Internal Goal: To keep your application code format-independent, so it works
everywhere with little hassle.

Now let’s talk a bit about each of these goals.

The External Goal: Be Flexible & Use Standard Controls


Have you ever noticed that few travel websites let the user manually enter date or time
information? Instead, they rely upon calendar pickers and fixed day, month and year dropdowns,
or, at minimum, enforce a specific date format (usually tied to your language/country, which
they ask for in advance). From a user interface perspective, your apps should honor date and time
nuances, at least to some extent. However, you should also carefully consider the methods in
which the user can enter date and time information. By using standard date and time pickers in
your Android apps, such as DatePicker and TimePicker, you effectively limit the data users can
input to that which can be easily converted into appropriate date and time structures, without
having to parse every known format (not to mention its typos).
The Internal Goal: Keep Your Dates and Times Generic
From an internal code perspective, your apps should use a generic date/time representation that
does not rely on these nuances.

In Java, dates and times are stored in several ways, depending upon your requirements.

 The long type is a primitive data type capable of storing the number of milliseconds
elapsed since a specific point in time (Unix time).
 The Date class ([Link]) is a utility class for storing date and time in a way that can
be reasonably manipulated without having to constantly think about time in terms of
milliseconds.
 The Calendar class ([Link]) is a utility class for working with different
calendars, as well as for manipulating date and time information in a variety of ways.
 The GregorianCalendar class (a subclass of [Link]) is used primarily for date
manipulation in the Western hemisphere, were we use a 12-month calendar, with 7 days
to a week, and two eras (BC and AD).

Determining the Current Date and Time


There are a number of ways to determine the current time on an Android device.

You can determine the raw date and time data using the static method provided in the System
class ([Link]):

view plaincopy to clipboardprint?

1. long msTime = [Link]();


2. Date curDateTime = new Date(msTime);
This method relies upon the time that the device thinks it is, which may or may not be reliable.
Another way to determine the current date and time uses the default constructor for the Date
class, which creates a Date object with the current date and time:
view plaincopy to clipboardprint?

1. Date anotherCurDate = new Date();

There are yet other ways to determine the true exact time—computers frequently check known
time-keeping servers to make sure everyone is “in sync”. This process is slightly beyond the
scope of this tutorial, but suffice to say, just requesting and receiving the correct time takes some
time, which must then be accounted for before synchronization can really be achieved.

(Note: Android devices that connect to cellular services tend to have locale accurate date and
time information as this may be used in communications with the radio towers.)

Creating Date and Time Variables from Scratch


Now what if you want to create a date or time variable from a specific date, like a birthday.
Perhaps you know, just off the top of your head, the number of milliseconds since 1/1/1970
midnight that represents your birthday. In my case, that would be something like 229703700
milliseconds, or the morning of April 12th, 1977 (adjusted for California time). However, as you
can see, this is very cumbersome. Really, what you want to do is say: computer, create me a
date/time variable representing April 12th, 1977. That’s where the Calendar class comes into
play:

view plaincopy to clipboardprint?

1. GregorianCalendar bday = new GregorianCalendar(1977, [Link], 12);

You can use calendar objects to manipulate dates and extract interesting information about them.
For example, you could use the get() method to determine the day of the week that I was born
upon:
view plaincopy to clipboardprint?

1. int dayOfWeek=[Link](Calendar.DAY_OF_WEEK); // Returns 3, for Tuesday!

Note that the months of the calendar are 0-based, so January is month 0, not month 1, and
therefore April is month 3, not 4. Finally, you can extract a Date object from a Calendar date
configuration using the getTime() method.

Formatting Date and Time Data


You can use the helper class called DateFormat ([Link]) to convert raw date and
time information into different String formats (for different locales, etc.) or to parse String
information into its appropriate date and time bits for use in code.
For example, you can use the SimpleDateFormat class (a subclass of the DateFormat class) to
create a custom string containing date and time information. First, you must specify your format
string, using the appropriate codes for the different bits of information (see the
SimpleDateFormat documentation for details on individual codes). Then you apply that
information to a specific date or time. For example:

view plaincopy to clipboardprint?

1. Date anotherCurDate = new Date();


2. SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMMM d 'at' hh:mm a 'i
n the year' yyyy G");
3. String formattedDateString = [Link](anotherCurDate);

If you were to print the String called formattedDateString, you might see something like:
“Monday, December 6 at 08:34 AM in the year 2010 AD”.

Incidentally, you can also use the DateFormat and SimpleDateFormat classes to parse date and
time strings into the appropriate Date class. Hopefully, you won’t spend a lot of time parsing
user-entered dates (which, generally, is quite annoying), but having a parsing mechanism is
useful. For example, you might want to parse timestamps from an XML file, where you control
or know the format of the timestamp in advance, and can therefore generate the appropriate
format string to parse with.

Displaying Date and Time Information to the User


There are numerous ways to display date and time information to the user. The way you choose
depends upon your requirements.

Perhaps the simplest way is to simply display a specific date or time as a properly formatted
string. This method makes the most sense for fixed dates or times, such as birthdays or events.
Simply use the DateFormat utility class to create the appropriate string and display it on the
screen as you would any other text (such as within a TextView control).

To show the time passing “in real time”, you can use either the AnalogClock (see figure) or
DigitalClock controls.
Tip: Looking for a timer? Check out the Chronometer control.

Wrapping Up
Dates and times are important data types that Java developers inevitably must work with.
Internally, devices store date and time information numerically, but users interpret this
information in different ways and using different formats. Keep these nuances under control by
limiting the ways users can input dates and times using built-in picker controls and ensure your
code uses a generic representation of this information, for example using one of the many classes
available for storing date and time information.

Learn Java for Android Challenge: Strings


Shane Conder & Lauren Darcey on Dec 13th 2010 with 7 comments

Tutorial Details

 Technology: Java + Android SDK


 Difficulty: Beginner
 Estimated Completion Time: 20-30 minutes

Download Source Files


This entry is part 12 of 13 in the series Learn Java for Android Development

Learn Java for Android Development

 Learn Java for Android Development: Introduction to Java


 Learn Java for Android Development: Java Syntax
 Learn Java for Android Development: Checking Object Type with Instanceof
 Learn Java for Android Development: Working with Arrays
 Learn Java for Android Development: Reflection Basics
 Learn Java for Android Challenge: Iteration
 Learn Java for Android Development: Inner Classes
 Learn Java for Android Development: More On Inner Classes
 Learn Java for Android Development: Javadoc Code Documentation
 Learn Java for Android Development: String Basics
 Learn Java for Android Development: Date and Time Basics
 Learn Java for Android Challenge: Strings
 Learn Java for Android Development: Java Shorthand

You’ve read about how Strings work in Java. Test your new skills with this challenge: solve this
String-based puzzle to help you solidify your knowledge of the Java programming language and
Android development. That’s right, Android, too! You may need to refer to other Android
tutorials here.

Setup
To prepare for this challenge, you’ll want to start with a basic Android application. Simply create
an Android application within Eclipse and edit its default Activity, specifically the onCreate()
method, to test the code you create for this challenge. Remember, you can use the Log.v()
method to print output (including strings) to the debug log. This is a quick and convenient way to
display testing output for exercises such as this one.

If what we’ve just asked of you is already too challenging, we would recommend taking a step
back. Start with some of the Android tutorials, such as Introduction to Android Development or
Beginning Android: Getting Started with Fortune Crunch. Once you’ve mastered setting up an
Android project, return and try these progressive exercises.

A Progressive Challenge
This is a progressive challenge. If you follow each of the steps below correctly, you will solve a
puzzle. Keep in mind, there are numerous ways to approach this problem and therefore numerous
solutions.

You can print out your progress to the Android debug log called LogCat using the Log.v()
method.

Bonus: Extra points (not that you’re being graded) for those who catch the reference to this
puzzle, and where it comes from.

Step 1: Define Your String


For your first step, you’ll need to define a new text string for use in this challenge. You’ve got
lots of options here. For the many ways in which you can define strings in Java, see our String
tutorial. The simplest method, of course, would be to simply define a new variable of type String.
The contents of this string should be the following text:

Setec Astronomy

Step 2: Convert to Uppercase


For your next trick, you’ll want to convert the string to all uppercase letters.

Hint: If you’re stuck, check the methods available within the String class, as defined in the
Android SDK documentation.

Sanity Check: The contents of your new string should be the following text: SETEC
ASTRONOMY

Step 3: Rearrange The Letters


Now things will get a bit more challenging…

As you may recall, a string is simply a sequence of characters. In this step, you want to rearrange
the characters in your uppercase string and add one extra character.

Think of your current string as a 0-based array of characters. Now rearrange the characters of
your string into the following sequence, where each number represents the current character
index, dashes are used to separate each index, and the asterisk (*) is used to represent a space
character:

view plaincopy to clipboardprint?

1. 7-8-3-9-4-1-0-*-14-11-6-13-5-12-10-2

Hint: Remember that String variables cannot be changed. Seriously consider using
StringBuilder.
to build up your new string contents from the specific characters of your source string.

Sanity Check: If you print out the resulting string, it should be:
STERCES YNAM OOT.

Step 4: Reverse Those Letters


You’re almost there! The only thing left to do is to reverse the characters in your string.
Hopefully you used a StringBuilder to build up your string from individual characters; it’s got a
helpful method that can this job for you.

Print the resulting string. It should be clear if you’ve solved the puzzle.
Step 5: Tweak Your Solution (Optional Challenge)
It’s always a good idea to review your solution and improve it, perhaps making it slightly more
elegant or flexible. While this step is certainly not essential to solving the puzzle (especially as
you’ve already done so), we suggest you continue if you’ve found the previous steps reasonably
straightforward.

Assuming you haven’t already, consider how you might define a String variable to represent the
index sequence discussed in Step 3.

view plaincopy to clipboardprint?

1. String strSequence = "7-8-3-9-4-1-0-*-14-11-6-13-5-12-10-2";

Now, take the following steps:

1. Parse the string above into an array of Strings, one for each number or asterisk.

Hint: Check the String class method called split().

2. Create a loop and iterate through this array of strings and build the resulting string using a
StringBuilder. As part of this process, you will need to convert each String to the
appropriate integer, or to a space character.

Conclusion
Android developers use Strings all the time to store textual data for various purposes. Strings
often need to be manipulated in order to be used within your code. As always, there are many
ways to solve these problems, so feel free to post your alternative answers (or any questions) in
the comments section. We have supplied a couple of methods in the accompanying attachment.

Best of luck!

Learn Java for Android Development: Java


Shorthand
Shane Conder & Lauren Darcey on Feb 1st 2011 with 11 comments

Tutorial Details

 Estimated Completion Time: 20 Minutes


 Difficulty: Beginner
 Technology: Java + Android SDK

This entry is part 13 of 13 in the series Learn Java for Android Development

Learn Java for Android Development

 Learn Java for Android Development: Introduction to Java


 Learn Java for Android Development: Java Syntax
 Learn Java for Android Development: Checking Object Type with Instanceof
 Learn Java for Android Development: Working with Arrays
 Learn Java for Android Development: Reflection Basics
 Learn Java for Android Challenge: Iteration
 Learn Java for Android Development: Inner Classes
 Learn Java for Android Development: More On Inner Classes
 Learn Java for Android Development: Javadoc Code Documentation
 Learn Java for Android Development: String Basics
 Learn Java for Android Development: Date and Time Basics
 Learn Java for Android Challenge: Strings
 Learn Java for Android Development: Java Shorthand

These quick tips discuss some of the most common Java shorthand techniques you’ll come
across when you’re getting started in Android development.

You’ll find these little code tidbits—which we are calling Java shorthand—used in the Android
SDK sample code, and just about every Android development book published at this time, not to
mention online tutorials and developer forums. None of these tips are Android-specific; they are
simply Java techniques that routinely confound beginners new to Java and Android, based upon
the emails we receive from our readers.

Tip #1:Java’s Unary Operators (Increment/Decrement


Variable Shorthand)
Many developers like their code short and easy to read. Like some other programming
languages, Java includes unary operators for easily incrementing and decrementing variable
values by 1.

In other words,

view plaincopy to clipboardprint?

1. int counter = 1;
2. counter++;
3. counter--;
This code is equivalent to:
view plaincopy to clipboardprint?

1. int counter = 1;
2. counter = counter + 1;
3. counter = counter – 1;

These unary operators can appear before (prefix) or after (postfix) the variable. The location of
the operator dictates whether the increment/decrement operation happens before or after the rest
of the expression is evaluated. For example, the following code shows how unary operators work
by manipulating a variable called counter using Android logging:
view plaincopy to clipboardprint?

1. int counter = 0;
2. Log.i(DEBUG_TAG, "The counter value is ="+counter++); // prints 0
3. Log.i(DEBUG_TAG, "The counter value is ="+counter); // prints 1
4. Log.i(DEBUG_TAG, "The counter value is ="+counter--); // prints 1
5. Log.i(DEBUG_TAG, "The counter value is ="+counter); // prints 0
6. Log.i(DEBUG_TAG, "The counter value is ="+(++counter)); // prints 1
7. Log.i(DEBUG_TAG, "The counter value is ="+--counter); // prints 0

Tip #2:Skipping Temporary Variables (Unnecessary


Variables Shorthand)
Java developers generally avoid creating variables they don’t really need. This is especially true
of temporary, ortemp ,variables that are used once to store the result of a statement, only to be
abandoned.

Instead, Java developers frequently just use the statement to be evaluated as the “resulting” value
itself. This is seen often when it comes to return statements, but you’ll also see it in other places
as well. For example, the following verbose method uses a “temp” variable called sum to store
the sum of two integers and then returns this value:

view plaincopy to clipboardprint?

1. int sumVerbose(int a, int b)


2. {
3. int temp = a + b;
4. return temp;
5. }

Many Java developers would simply skip the overhead and hassle of creating the temp variable,
and just evaluate the statement as part of the return statement, like this:
view plaincopy to clipboardprint?
1. int sum(int a, int b)
2. {
3. return (a+b);
4. }

This style holds true for cases where the temp variable is only used once. If the method included
further operations on that value, it is usually prudent to use a well-named variable for code
readability. In addition, you’ll often see more “verbose” coding style in code that has a lot of
debugging features.

Tip #3: The Java “this” Keyword and Chaining Methods


You will often see Java methods chained together. Frequently, these methods are called on the
instance of the current class (thus, the this keyword). Similar to the tip discussed above, the
return values of each method are only being used to access an underlying method. Therefore, the
return value is not stored in a container value, instead the underlying method is just called. For
example:

1. InputStream is = getResources().openRawResource([Link]);

This code is logically equivalent to the following:


view plaincopy to clipboardprint?

1. Resources myAppResources = [Link]();


2. InputStream is = [Link]([Link]);

Tip #4: Java’s Ternary Operators (If-Else Shorthand)


One conditional statement you will likely see will use Java’s ternary operator support. This is a
shorthand way of designing a simple If-Else statement using a conditional statement (which may
or may not be encapsulated in parentheses), followed by a question mark (?), then a statement to
occur if the conditional is true, then a colon (:) and another statement to occur if the conditional
is false.

Here’s an example of a ternary operator in use:

view plaincopy to clipboardprint?

1. int lowNum = 1;
2. int highNum = 99;
3. int largerNum = lowNum < highNum ? highNum : lowNum;

This is the logical equivalent of the following, much longer, code snippet:
view plaincopy to clipboardprint?
1. int largerNum;
2. if(lowNum < highNum)
3. {
4. largerNum = highNum;
5. } else {
6. largerNum = lowNum;
7. }

This sort of Java shorthand is really only appropriate when your If-Else statement is simple.
You’ll sometimes see developers cram a lot of logic into one of these statements; we do not
recommend this. Only use ternary operators when they make your code easier to read, not harder.

Tip #5: Empty Statements (Infinite Loop Shorthand)


In Java, you can have empty statements simply by terminating a blank line of code with its
semicolon. This trick is often used to specify for() loop conditionals to create an infinite loop,
like this:

view plaincopy to clipboardprint?

1. for (;;) {
2. //Do something over, and over, and over again.
3. }

Each of the for() loop components is an empty statement. This evaluates to be true and therefore
the loop continues indefinitely. As with any code design, make sure any infinite loops you create
have reasonable exit cases.

Conclusion
It can be frustrating when developers new to Java encounter strange code syntax on their first
day working with Android— syntax that is not normally covered in the typical “Master
Everything in Java in 20 Minutes” tutorial. Now you know what some of these “shorthand”
tricks look like, and what they mean. Whether or not you use them yourself is up to you, but at
least they won’t confound you when you see them in sample code! Good luck and feel free to
share some of your favorite shorthand Java code you come across in the comment section as
well!

Common questions

Powered by AI

Understanding Java syntax is fundamental to Android application development as it is the primary language used for creating Android apps. Familiarity with Java syntax enables developers to efficiently utilize Android's robust libraries and APIs, crucial for effective app development. For those familiar with other programming languages, learning Java syntax allows translation of existing programming concepts into Android development, enhancing their skill set and enabling them to create versatile applications with pre-established programming principles .

Java inner classes provide a way to logically group classes that are only used in one place, enhancing encapsulation. They can access members of the enclosing class, making them suitable for implementing adapter functionality such as iterators, which often need to traverse and interact with many members of another class. In Android development, inner classes, including anonymous inner classes, are frequently used to implement event listeners and callbacks, enabling a tighter coupling and easier access to the variables and methods of the containing class .

Iteration techniques in Java are fundamental for processing collections of data, which is a common requirement in Android development. Common scenarios include iterating over arrays and lists, which are frequently used to manage views, contacts, messages, or any data structure involving multiple items. Iteration is also applied when accessing elements in databases via cursors. By automating repetitive tasks, such as updating UI elements with data or processing user input, iteration simplifies code and enhances application performance and functionality .

Android developers utilize anonymous inner classes to handle events more efficiently by allowing them to define behavior directly inline without the need for a separate named class. This approach simplifies code related to event handling, such as listening to user interface events like button clicks. Using anonymous inner classes reduces boilerplate code and improves readability by keeping the event-handling logic close to where the events are triggered. This encapsulation is particularly useful in streamlining listener implementations within an activity or fragment .

For-loops and while-loops in Java both facilitate iteration, but they have distinct uses. A for-loop is ideal when the number of iterations is known ahead of time, as it condenses the loop initialization, condition, and iteration expression within one line, enhancing readability. In contrast, while-loops are suitable for scenarios where the loop should continue until a particular condition changes, offering more control over loop execution when the number of iterations isn't predetermined. In Android development, choosing between them depends on the specific use case and readability demands, ensuring that the most intuitive structure is applied for maintaining and future-proofing code .

Substrings in Java are often replaced to modify parts of the text within a string for various purposes, such as data cleaning, formatting, and preparing text for output or storage. The use of regular expressions in methods like replaceAll() enhances this process by allowing more complex pattern matching and transformations. Regular expressions provide powerful tools to identify specific substrings based on patterns, which can then be replaced, making string manipulation efficient and adaptable to complex requirements without manually coding all conditions .

The Java String class provides several methods that can be leveraged to transform and normalize user input for consistent processing in Android applications. Methods like toUpperCase() and toLowerCase() ensure uniform casing, facilitating case-insensitive searches and comparisons. The trim() method removes unwanted whitespace, aiding in sanitizing input data. Additionally, the split() method can divide input into manageable components based on delimiters, making it easier to parse and process forms or queries. Together, these transformations help maintain data consistency and reliability in application logic .

Packages are crucial in Java for organizing classes and interfaces because they help avoid naming conflicts and allow for better modularization of code. In complex projects like Android development, where the scale of application code can be quite large, packages enable developers to group related classes and interfaces together logically. This organization improves code maintainability and readability by providing a clear structure and hierarchy, making debugging and updating more manageable .

Understanding Java's immutable strings is crucial for Android developers because it significantly influences how memory resources are managed. Since strings in Java cannot be altered once created, each modification operation results in new object creation, which can lead to increased memory consumption. Developers need to be cautious with operations like concatenation in performance-critical applications to avoid unnecessary memory overhead. Efficient use of string builders or buffers for concatenation operations is recommended to optimize performance and resource usage, which is especially important in resource-constrained environments like mobile devices .

Java's reflection plays a significant role in Android development by enabling runtime inspection and manipulation of classes, methods, and fields. This capability allows developers to create objects, invoke methods, and access fields dynamically, which is essential for frameworks that require loose coupling between components or support for plugin architectures. Reflection is particularly useful in Android for tasks like dependency injection, where object creation and configuration are handled dynamically, promoting flexibility and decoupling in application design .

You might also like