Advertisement
Android SDK

Learn Java for Android Development: Java Shorthand

by

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,

int counter = 1;
counter++;
counter--;

This code is equivalent to:

int counter = 1;
counter = counter + 1;
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:

int counter = 0;
Log.i(DEBUG_TAG, "The counter value is ="+counter++);       // prints 0
Log.i(DEBUG_TAG, "The counter value is ="+counter);         // prints 1
Log.i(DEBUG_TAG, "The counter value is ="+counter--);       // prints 1
Log.i(DEBUG_TAG, "The counter value is ="+counter);         // prints 0
Log.i(DEBUG_TAG, "The counter value is ="+(++counter));     // prints 1
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:

int sumVerbose(int a, int b)
{
    int temp = a + b;
    return temp;
}

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:

int sum(int a, int b)
{
    return (a+b);
}

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:

InputStream is = getResources().openRawResource(R.drawable.icon);

This code is logically equivalent to the following:

Resources myAppResources = this.getResources();
InputStream is = myAppResources.openRawResource(R.drawable.icon);

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:

int lowNum = 1;
int highNum = 99;
int largerNum = lowNum < highNum ? highNum : lowNum; 

This is the logical equivalent of the following, much longer, code snippet:

int largerNum;
if(lowNum < highNum)
{
    largerNum = highNum;
} else {
    largerNum = lowNum;
}

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:

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

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!

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 Posts
  • Code
    PHP
    Object-Oriented Programming in WordPress: Control Structures IWordpress 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.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
    Android SDK
    Android SDK: Detecting GesturesAndroid preview@2x
    The Android SDK supports a variety of gestures you can detect, allowing you to tailor the ways in which users interact with your applications. In this tutorial, we will look at the framework that allows developers to add gesture detection to a simple application, working through the process of supporting the fling gesture and outlining how to support other gestures. Once you've completed the development for a basic fling function, you'll be able to add additional gestures to the application yourself.Read More…
  • Code
    Android SDK
    Android SDK: Java Application ProgrammingAndroid preview@2x
    Our goal in this series is to learn about Android SDK development. So far we explored the development tools, looked at the structure of an Android app project, started to create a user interface, and responded to user interaction. In this tutorial, we will look at the basic structures and concepts in Java that you need to know in order to start developing apps for Android.Read More…
  • Code
    Cheat Sheets
    The WordPress Coding Standards: The Ternary Operator and Yoda ConditionsThe wordpress coding standards
    At this point in the series, we've covered a lot of ground. Up to now, we've discussed the following topics: Naming Conventions and Function Arguments The Use of Single Quotes and Double Quotes Indentation, Space Usage, and Trailing Spaces Brace Style, Regular Expressions, and PHP Tags Lots of stuff, right? In this particular article, I thought we'd take it a bit easier before jumping into the final topic. As such, we're going to cover two really simple topics (that are often either ignored or overcomplicated). Specifically, we're going to talk about the ternary operator and we're going to talk about Yoda conditions.Read More…