Site icon Treehouse Blog

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:

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.

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.

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.


Learn in-demand programming skills and become a certified Android Developer with the Treehouse Techdegree Program. Learn more and enroll today.
Exit mobile version