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!

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, 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.

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. Android Studio is the official Integrated Development Environment (IDE) for Android app development.

It includes an Android Emulator (for simulating devices), an intelligent code editor, and other helpful features for Android development. It’s also freely available for Windows, Mac, and Linux operating systems.

Now let’s look at some helpful Java syntax.

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:

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

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 its own, but here’s an example of what Javadoc comments look like:

In the above comment, @param describes the function’s parameters, and @return describes the function’s return value (that is, the value that sampleMethod is going to return after processing the parameters).

A variable is simply a piece of data. Java variables generally fall into two categories:

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. At other times, variables might represent constants—these variables should use the final keyword to show that 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.

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

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

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

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 that the code is more readable.

Let’s look at some of the primitive data types available in the Java programming language:

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 a semicolon. For example, the following Java statement defines a variable called iVal, with an initial value of 1:

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

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. Let’s see this in code.

The following Java code instantiates an integer variable called iVal, then creates an Integer object using a constructor that takes an integer, and then uses a handle method available in the Integer class to extract a float variable equivalent.

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 on 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.

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, default, 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. Finally, use default if the method or variable should only be accessible from within the package and not outside of it (this is the case by default).

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

Now on to default. If you fail to state any access modifier for a class, method, or variable, then the default modifier will be automatically applied to it, meaning it’ll also be accessible to classes within the same package. For example:

Here, the PrintSomething class uses the default access modifier. As a result, it is visible to all the classes that are part of the myPackage package. But if we attempt to use PrintSomething in a class outside of myPackage, we’ll get a compilation error.

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:

And when you need to combine multiple conditional statements into a single larger conditional test, you can use and (&&) and or (||). For example:

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:

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

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

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 no 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.

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:

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

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:

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

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:

So in the class we have the constructor which sets the name, the method getName which gets the stored name, and the method setName which sets a new name.

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

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

You’ve just completed a crash course in 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 Java syntax.

source