Advertisement
Android SDK

Learn Java for Android Development: Java Syntax

by

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:

/*    MULTILINE
COMMENT  */

You can also provide comments after code on a single using //. For example:

int x = 7;        // First variable called x equals seven
int y = 8;    // Second variable called y equals eight
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:

/** This method does something interesting
 *
 * @param someValue processed and returned
 * @param option changes the type of processing done to someValue
 * @return The result of someValue being processed
 */
public int sampleMethod(int someValue, boolean option) {
    //…
}

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:

int i = 5;

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

int result = (a + b) / c;

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

iPositive++;    // increment by one; equivalent to iPositive = iPositive + 1;
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
    • A byte variable is an 8-bit signed integer between -128 and 127. Often used for arrays.
  • short
    • A short variable is a 16-bit signed integer between -32,768 and 32,767. Again, often used for arrays.
  • int
    • 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
    • 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
    • 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 data type for decimal values.
  • boolean
    • A boolean variable has only two possible values: true and false. Use this data type for conditional statements.
  • char
    • 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:

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):

int[] aiPowersOfTwo;
aiPowersOfTwo = new int[4];
aiPowersOfTwo [0] = 1;    //  2^0=1
aiPowersOfTwo [1] = 2;    //  2^1=2
aiPowersOfTwo [2] = 4;    //  2^2=4
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.

int iVal = 1;
Integer integ1= new Integer(iVal);
float f = integ1.floatValue();

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.

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

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

For more complex data structures like lists, queues, stacks, dates, and times, appropriate classes are in the java.util 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 android.app 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
    public class SillySensor
    {
        private int sensorData;

        public SillySensor()
        {
            sensorData=0;
        }

        private void calibrate(int iSeed)
        {
            // Do some calibration here
        }

        protected void seedCalibration(int iSeed)
        {
            calibrate(iSeed);
        }

        public int getSensorData()
        {
            // Check sensor here

            return sensorData;
        }

    }

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:

boolean condition = true;
if(condition==true)
{
    // Execute this code only if  condition variable is true
}

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

boolean condition = true;
if(condition==true)
{
    // Execute this code only if condition variable value is true
} else {
    // Execute this code only if condition variable value is false
}

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

if(iVar==0) {
    // variable is zero
} else if (iVar > 0) {
    // variable is a positive number
} else {
    // variable is a negative number
}

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.

        char singleChar = 'z';
        switch(singleChar) {
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
            // singleChar is a vowel! Execute this code!
            break;
        default:
             // singleChar is a consonant! Execute this code instead!
             break;
        }

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:

int numItemsToProcess = 3;
while(numItemsToProcess > 0)
{
    // process an item
    numItemsToProcess--;
}

If you want to evaluate the conditional loop expression AFTER the first iteration, you can use a do-while loop instead:

do
{
    // check for items to process, update numItemsToProcess as required
    // process item, updated numItemsToProcess
} 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:

for(int i = 1; i <=100; i++)
{
    // print i
}

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:

public class Cat {
    private String mCatName;

    Cat(String name) {
        mCatName=name;
    }

    public String getName() {
        return mCatName;
    };

    public void setName(String strName) {
        mCatName = strName;
    };
}

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

    void messWithCat(Cat kitty) {
        kitty = new Cat("Han");
    }

    void changeKitty(Cat kitty) {
        kitty.setName("Wookie");
    }

    Cat haveKitten()
    {
        Cat kitten = new Cat("Luke");
        return kitten;
    }

Finally, let’s call these methods and see how they act upon Cat object instances:

Cat cat1 = new Cat("Jabba");
Cat cat2 = new Cat("Leia");

cat1.getName();    // Returns Jabba
cat2.getName();    // Returns Leia
messWithCat(cat1);
changeKitty(cat2);
Cat cat3 = haveKitten();
cat1.getName();    // Returns Jabba – Note that object remains unchanged!
cat2.getName();    // Returns Wookie
cat3.getName();    // 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!

About the Authors

Mobile developers Lauren Darcey and Shane Conder have coauthored several books on Android development: an in-depth programming book entitled Android Wireless Application Development and Sams TeachYourself Android Application Development in 24 Hours. When not writing, they spend their time developing mobile software at their company and providing consulting services. They can be reached at via email to androidwirelessdev+mt@gmail.com, via their blog at androidbook.blogspot.com, and on Twitter @androidwireless.

Need More Help Writing Android Apps? Check out our Latest Books and Resources!

Buy Android Wireless Application Development, 2nd Edition  Buy Sam's Teach Yourself Android Application Development in 24 Hours  Mamlambo code at Code Canyon


Related Tutorials:


Related Posts
  • Code
    PHP
    Object-Oriented Programming in WordPress: Functions and AttributesWordpress oop
    As we continue our discussion of object-oriented programming within the context of WordPress, it's time for us to begin talking about actual features of object-oriented programming. Though we've already covered classes, we needed to explore some foundational programming constructs before coming back around to some of the core object-oriented concepts. In this article, we're going to begin talking about functions and attributes: two foundational aspects of object-oriented programming.Read More…
  • Code
    PHP
    Object-Oriented Programming in WordPress: Control Structures IIWordpress oop
    WordPress is a powerful CMS that provides a flexible foundation on which to build both sites and applications. If you want to extend WordPress functionality, then you do so via plugins. Although there are a number of different ways to do that, this series has us taking a look at object-oriented programming specifically from the perspective of a beginner and in the context of WordPress. In this post, we're looking at a second set of control structures that allow us to control the flow of code throughout an application.Read More…
  • Code
    Android SDK
    Create a Music Player on Android: User Controls0d63m preview image@2x
    We are building a simple music player app for Android in this series. So far, we have presented a list of the songs on the device and allowed the user to make selections from it, starting playback using the MediaPlayer class in a Service class. In this final part of the series, we will let the user control playback, including skipping to the next and previous tracks, fast-forwarding, rewinding, playing, pausing, and seeking to particular points in the track. We will also display a notification during playback so that the user can jump back to the music player after using other apps.Read More…
  • Code
    Mobile Development
    C++ Succinctly: C++ Language Usages and IdiomsPreview image@2x
    We’ve already covered the RAII idiom earlier in this series. Some language usages and programming idioms in C++ might seem foreign or pointless at first glance, but they do have a purpose. In this article, we will explore a few of these odd usages and idioms to understand where they came from and why they are used.Read More…
  • Code
    Mobile Development
    C++ Succinctly: Pointers, References, and Const-CorrectnessPreview image@2x
    Even though the concept of a pointer is simple, many people struggle with this topic. A pointer is nothing more than a variable that holds a memory address. After reading this article, pointers and references should no longer have secrets for you.Read More…
  • Code
    iOS SDK
    Objective-C Succinctly: Data Types0e5ds8 preview image@2x
    Objective-C has two categories of data types. First, remember that Objective-C is a superset of C, so you have access to all of the native C data types like char, int, float, etc. Objective-C also defines a few of its own low-level types, including a Boolean type. Let's call all of these "primitive data types."Read More…