Java Basics for Android Development – Part 1

Android Robot drinking a mug of Java

There are a number of ways to create apps for Android devices, but the recommended method for most developers is to write native apps using Java and the Android SDK. Java for Android apps is both similar and quite different from other types of Java applications.

If you have experience with Java (or a similar language) then you’ll probably feel pretty comfortable diving right into the code and learning how to use the Android SDK to make your app run. But if you’re new to programming or object-oriented languages then you’ll probably want to get familiar with the syntax of the Java language and how to accomplish basic programming tasks before learning how to use the Android SDK.

Java the Programming Language

Programming languages, like regular languages, are different ways to communicate to a computer how you want it to act. Programming languages allow us to instruct a computer step-by-step how to manipulate data, collect input from users, and display things on a screen, among other things.

Way down on a microscopic level, the processor of a computer sends electrical signals back and forth that control how it operates. High level programming languages like Java mean that we can write these instructions in an abstract manner using words and symbols, and the computer will take care of translating these instructions that we can understand all the way down to electrical impulses that the processor can understand.

Not to get ahead of ourselves, but Java is a statically-typed, object-oriented language. Let’s break this down:

  • “Statically-typed” – Programming at its core is really about working with data. Pieces of data are stored as variables, which are basically containers that hold data. Statically-typed languages like Java require us to declare what type of data each variable (or container) will hold. So for example, if a variable is supposed to hold a number, we need to say so, and we won’t be allowed to put something else like a letter in it. Statically-typed also means that all the variables will be checked before the program even runs, and we’ll be presented with an error if we forget to declare a type of data or declare the wrong one.
  • “Object-oriented” – An object-oriented language is one that is built around the concept of objects. In the physical world, take a look around the room and think of each thing as an object. For example, on my desk right now I have a mug. As an object, it’s name is “mug” and it has properties about it like its color and how much liquid it will hold. Object-oriented languages allow us to define objects like mugs and access their properties in our code. We can also send messages to objects, so for my mug I might want to know “Is it empty?” We can then create and manipulate all sorts of objects to do different things in our app. For example, we can use the Camera object to take a photo. The Camera object represents the physical camera on an Android phone, but in a way that we can interact with in code.
Half-full mug on table

The isEmpty() method for this Mug object returns false!

Java is Not Related to JavaScript

One of my favorite sayings about this topic is “Java is to JavaScript as Car is to Carpet.” There is absolutely no relationship between the two languages. However, knowing JavaScript can help you understand Java, because some of the basic components and ideas are similar. The two languages are written differently and work very differently, but both allow us to work with programming features like variables, methods, operators, and even objects. And the logic behind the language is the same, so knowing how to use variables, methods (or functions), and loops will make learning Java much easier; at that point you just need to learn the syntax of Java, which is how you explicitly need to write certain things like variable declarations and method calls.

Components of the Java Programming Language

Let’s take a look at how the language of Java is expressed in the code we write. The language itself is a collection of keywords and symbols that we put together to express how we want our code to run. Each line of code has certain rules (or grammar) about how it needs to be constructed and what is or isn’t allowed.

Remember, programming languages are abstractions, meaning that they abstract the true underpinnings of how a computer operates into things we can more easily understand. Behind the scenes it really is all ones and zeroes, but we don’t need to concern ourselves with that. We can think in these abstract terms to express our ideas and commands, and these abstractions apply across all different types of programming.

Basic Data Types

If programming really is about working with data, then we’d better familiarize ourselves with the basic data types used in Java. These are some of the keywords that indicate the type of data we’ll use and store in variables.

  • int – An integer value, i.e. a whole number (no decimals) that includes zero and negative numbers.
  • float – A floating point value that includes as many decimal places as it can hold. Because the decimal place can change, or float, it’s important to know that these values may technically be imprecise. When precise decimals are needed, like for currency, we should use the BigDecimal data type.
  • boolean – A 1-bit true or false value that can only be in one of those states. The Java keywords for the values are “true” and “false”, which represent 1 and 0, respectively.
  • char – A single character, such as the letter “A” or the symbol “#”. Note that lowercase and uppercase characters are different, so “a” and “A” are two different characters.
  • String – String data is a bunch of characters strung together to make text, like a banner strung up at a party.

The first four data types in the list above, int, float, boolean, and char, are primitive data types, which means that they are relatively simple and straightforward. Other primitive data types include byte, short, and long. For more information about Java’s primitive data types, visit the documentation from Oracle.

The “S” in String is capital because String is a more complex data type. Strings are actually objects, and the naming convention in Java is that object names should start with a capital letter. An object is different than a primitive data type because it has more complex properties and methods available to it, whereas the primitive data types are limited and straightforward. For example, the String object has a method called length() that tells us how many characters are in the String, but the int data type does not have any methods like that.

Variables

A variable is basically a container used to hold data. The data itself can be anything from a simple number to coordinates for a location on a map to a URL for a video on the web. As we just learned, Java is a statically-typed language, which means that we need to explicitly declare what type of data a variable is supposed to hold. Let’s take a look at an example.

String title = "Java Basics for Android";

The line above is a statement that declares a variable named “title” that holds String, or text, data. It also assigns the text “Java Basics for Android” to the variable. Let’s examine each numbered part:

  1. The first word in a variable declaration is the data type, which tells us what kind of data the variable will hold.
  2. The second word is the name of the variable, which can be anything you want following a few basic rules. Variable names must not contain any spaces or special characters; they can only have letters, numbers, and underscores. They must not start with a number, though.
  3. The equals sign (=) is an operator, meaning it performs a specific operation for us. This is the assignment operator, meaning that we use it to assign values to variables. In this example it is assigning the text value on the right (#4) to the variable “title” on the left (#2).
  4. The text in green is the String value we are working with. In Java, Strings are surrounded with double quotes to differentiate them from regular text used in the code.
  5. Finally, the last character in this line is the semicolon, which is used to finish this statement. Semicolons in Java are like periods in sentences: we use them to indicate when we’re done saying something. Every statement in Java must end with a semicolon (note that a statement may be displayed on multiple lines for better readability).

Some other examples of variable declarations using some of the basic data types we covered are as follows:

int playerNumber = 24;
float distance = 11.72011f;
boolean isEmpty = true;
char firstLetterOfName = 'B';

Note the “f” at the end of the float value that indicates the number is a floating-point value. Also note that char values are surrounded with single quotes to differentiate them from String values, which use double quotes.

Methods

A method is a section of code that we can call from elsewhere in our code, and the method will perform some action or return some kind of result that we can use. Methods are used to organize our code into reusable (and understandable) chunks that save us a lot of time and energy.

Let’s use a simplified example of the length() method mentioned above for the String data type to see how a method is defined and called and how it helps us.

01  public int length() {
02    int numberOfCharacters = 0;
03    ... code to calculate the number of characters ...
04    return numberOfCharacters;
05  }

Line 1 declares the method named length. The first word declares the visibility of the method and is often either public or private (though a few other options are available). “Public” means that it’s publicly available to call from anywhere in our app. “Private” methods are only available within the class they are defined in (more on classes in little bit).

The second word in the method is the data type that will be returned. In this case the method will return a number, or int. If the method will run some code but not return any kind of data, then the keyword void is used instead of a data type.

Next up is the name of the method. Method names follow roughly the same rules as variable names: letters, numbers, and underscores, but they cannot start with a number.

Directly after the name we see two parenthesis with nothing in between them. The parenthesis are required, but when empty like this it means we do not pass any data or variables when we call the method. If one or more variables (with data types) were included between the parenthesis, then we would need to pass in appropriate values or variables inside the parenthesis when we call this method.

Line 1 ends with an opening curly brace, and a matching closing curly brace is on line 5. In Java, blocks of code, like the code that make up a method, are often surrounded by curly braces to designate all the code that should be run. In this case it means that all the lines of code between the curly braces will be run each time we call the length() method.

The last thing I want to mention from this example is the code on line 4. The return keyword designates that the variable (or data) on the line after the return keyword is what will be returned to whoever called this function. In this example we’ve calculated the total number of characters that make up the text of the String and stored the value in an int variable named numberOfCharacters. This variable is returned, meaning that the actual number stored in the variable will be the return value of the length() method.

Calling a Method

To use a method, we need to call it from our code and, if it returns a value, store the return value somewhere.  Here’s an example of calling the length() method:

String sampleText = "Java is fun";
int textLength = sampleText.length();

First we have a String value that has 11 characters (because white space is included). We call the method on the next line using dot notation, which uses a period after a Class or variable name to call the method from. We can’t just call it like int textLength = length(); because in this incorrect example, there is no point of reference for where the length() method is defined or what text it should be checking. By chaining it to the sampleText String variable, we are saying to use the length() method defined by the String class, and to use it on the text data held in the sampleText variable.

In this case the length() method calculates a value of 11 and returns it to this code where it was called from. We do something with the return value by storing it in a new int variable named textLength.

Major Benefit of Using Methods

Imagine that we have five different String variables that we need to know the lengths of. If we didn’t have a length() method to use, we’d have to write the code to calculate the length five different times. But be creating a reusable method, now we only need one line of code each time we want to determine the length of a String value. Programming is all about efficiency, so use methods whenever possible to organize your code and save yourself work.

Stay Tuned

Thanks for reading, and stay tuned for part 2 in which we’ll cover more Java basics like Objects and Classes, loops, and conditionals (if statements)! To see some of this in action, check out the first stage of Build a Simple Android App.

Free Workshops

Watch one of our expert, full-length teaching videos. Choose from either HTML, CSS or Wordpress.

Start learning

Ben Jakuben

I'm a dad to a few, husband to one, son to two, brother to one, and friend to many. I spent nine years in software development before finding my dream job with Treehouse. Lately I've been focused on mobile development (primarily Android) as well as how to be a better father/husband/son/friend. Firmly committed to the belief that the world is evolving to a better place. Find me on Twitter @benjakuben.

Comments

19 comments on “Java Basics for Android Development – Part 1

  1. This is a comprehensive and an ideal reference for all Android beginners. Thanks a lot Ben.

  2. Hi Ben,

    I was just wondering what’s the difference between a function and a method. Are the concepts of functions not used in JAVA (is JAVA based around Methods only)?

    • Basically, they are almost interchangeable. A function is a little more generic in that it doesn’t have to depend on a class. That’s the main difference: a method is associated with a specific object. There are some great answers in this StackOverflow question: http://stackoverflow.com/questions/155609/what-is-the-difference-between-a-method-and-a-function

      So Java doesn’t really have “functions” by that definition. Other languages allow you to have functions that aren’t specific to a certain object, but in Java such functions (methods) will always be tied somehow to an object definition. You can usually use them interchangeably, but the norm in Java and other object-oriented languages is to say “method”.

  3. Excellent tutorial Ben. I am beginner to android. Also don’t know the basics like c and other languages. Directly i saw your blog and way of teaching was perfect. waiting for your next tutorial.

    • Thanks for reading and being a student! I took a little hiatus from Android for iOS, but more of both is on the way!

  4. I needed something like this from so looong….. Android learning from Java Basics! Great Post!!!