Android : Basics of Java for Android Development part 1

Java programming language is used to develop Android applications. We will learn Java programming language only with android development context. Complete Java tutorial is out this text’s scope, in this tutorial, you’ll get a brief introduction of the Java fundamentals, OOP concepts and few more. This text assumes you understand programming basic. This text is not going to teach you “how to program in Java”, but will provide you constructs and principles that are commonly used in Java.Android applications are developed using the Java language. Android relies heavily on Java fundamentals. The android SDK includes many standard Java libraries as well as special Android libraries that will help developers to create Android Apps.

Java syntax

We will start with the Java syntax. Syntax of any programming language covers Variables, Data types, statements, Loops, comments etc.

Statements

A statement is the smallest standalone element of the language which expresses some action to be carried out. Any program is formed by a sequence of one or more statements. In Java, each and every statement in Java programming language ends with a semi colon. For example,

int a = 10;

We will learn more about the meaning of the statement in next section.

Variables

A variable is just a place to hold data. Variables are used for all kinds of stuff. Variables are the data that may change again and again over time. The variables which do not change over the course of time are called constant variables. A Variable is only valid within its scope. Variable scope is defined by the curly braces {} or access modifiers. When Variables are defined in a class it is called its attribute field. Lets have an example:

int i = 10;

in the above example, int defines the data type of the variable as integer. That is, this variable can hold an integer value. i is the name of the variable also known as its identifier. Like any other programming language equals is used as assignment operator and 10 is its current value. Like other languages java also supports other arithmetic like +, -, *, /, % and Logical operators like ==, ||, !=, <, >, <=, >=. Lets have an other example here:

int a = 10;
int b = 20;
int sum = a + b;

In the above example, we have three variables a, b and sum. First two lines are same as the last example, but in the third line the variable sum is assigned(using assignment operator =) the result of the operation a + b(using the arithmetic operator +). Thus the value of the sum will be 30(10+20).
Finally, we have the unary operators, which only require single variable to perform its action ++ the increment operator and — the decrement operator:

int i = 10;
int j = 10;
i++;
j--;

In the above example, we have two variables i and j both having value 10. In the Line 4, variable i is incremented with one and will now have value 11 and in the line 5, variable j decrements by one and will have value 9. The increment and the decrement operators can be prefix or postfix, that is the increment can be executed before or after any conditionals are determined in that statement. Generally, we stick to postfix notation as it makes the code more readable.

Data Types

Data types tells the variable holding capabilities that is, what type of the data it can hold in it. Like in above example int i = 10;, int is the data type of the variable. Data types are of two types: Primitive data types and Java Objects.
Let’s look at the primitive data types:

  • byte
    8 bit signed integer between -128 and 127. Often used for arrays.
  • short
    16 bit signed integer between -32,768 and 32,767. Again, often used for arrays.
  • int
    32 bit signed integer between -2,147,483,648 and 2,147,483,647. This is used as number variable.
  • long
    64 bit signed integer between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807. Used when int isn’t big enough.
  • float
    single precision 32 bit floating point number.
  • double
    double precision 64 bit floating point number. Use this data type for decimal values.
  • boolean
    has only two possible values: true and false. Use this data type for conditional statements.
  • char
    single 16 bit Unicode character.

Like many other programming language, a zero-based array can be defined for the specific data type. For example, the following defines an array of integers:

int [] array = new int[4];
array[0] = 0;
array[1] = 1;
array[2] = 2;
array[3] = 3;

In above example, an array of integers of size 4 is created. In Java, arrays are zero based that it the array index starts from zero. In above case the array size is 4, so the indexes for the array will be 0,1,2 and 3.

The second type of Data types is Java Objects. Java provides a number of common data structures. All the objects in Java are derived from the Object class. The most common object you’ll use in Android application is the String. The String class is used to encapsulate characters arrays, so that it can be used and altered as text rather single character at a time. There are two more Java classes that can be used in place of String for string modifications, they are StringBuffer and StringBuilder.

String str = new String("hello World");

This is how you create a Java Object, first we tell the Class or Object Type, then Object identifier. The new operator will tell the runtime to create a new object or assign memory space for the variable to hold its Data. Next is the constructor of the String class. For the list of common Java data types, check the Android Documentation for java.lang package.;

Finally, Android applications rely on a number of helpful classes that defines the commonly used applications components like Activity, Application, Dialog and Service. These can also be found in android documentation for android.app package;

Comments

Before moving any further lets talk about commenting your code. Comments in the source code make it more readable and understandable to other developers, thus help developers in debugging and maintenance. Most programming languages allow for comments and Java is no different. There are two types of comments in Java: single line and multi-line comments. As the name suggests single line comments are of one single line using //, everything that follows // int that line, are commented out and will not be compiled.

int a = 5; // First variable
int b = 5; // Second variable
int sum = a + b; // The sum variable will store the sum of a and b

The second type, Multi-line comments encapsulates any number of lines of the text by beginning comments with /* and ending the comments with */. For example:

/* this is a...
multi line...
comment...*/

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 quite large, but here’s an example of how it will look like:

/** This method return sum of two variables
*
* @param first value
* @param second value
* @return The sum of the two value
*/
public int sum(int a, int b) {
    //...
}

Conditional Statements

Java includes conditional statements, which checks if certain conditions are met. Typically, a conditional statement involves two sides. If the condition is true, then true side will execute otherwise false side will execute.
Java has all the typical conditional operators, such as:

  • ==equal to, as in (a==b)
  • !=not equal to, as in (a!=b)
  • > greater than, as in (a>b)
  • <less than, as in (a<b)
  • >=greater than or equal to, as in (a>=b)
  • <=less than or equal to, as in (a<=b)

And when you need to combine multiple conditional statements, you can use AND(&&) operator or OR(||) operator:

  • ((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

Now that we know how to create conditionals, lets learn conditional statements. The simplest form of a conditional statement is the if() statement:

int a = 10;
int b = 5;

if(a &gt; b) {
    // Execute some code...
}

If you want to provide alternative code to run if condition fails, then we use else clause with if() statement

int a = 5;
int b = 15;

if(a &gt; b) {
    // Execute some code...
} else {
    // Execute some code...
}

If we want to handler more than one case, we can cascade if and else statements and form an if else ladder.

int a = 5;
int b = 15;

if(a == b) {
    // Execute some code...
} else if(a &gt; b){
    // Execute some code...
} else {
    // Execute some code...
}

Switch case statements

When there are a number of different code path possible from a single variable value, we can use switch statement. With a switch statement, we check single variable and provide numerous options to execute for specific cases. There can be a default option, which will execute if none of the cases applies. 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. Example :

int check = 10;

switch(check) {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        // check is less or equals to 5!
        break;
    default:
        // check is greater than 5!
        break;
}

Loops

If you have some piece of code that needs to be executed repeatedly then there are four types of loops are available in Java language.
To Loop or iterate continuously provided that a statement is true, we use while() loop:

int iterator = 0;

while(iterator < 10) {
    // process over iterator
    iterator++;
}

If you want to execute the code inside loop at least one time and then checks if the condition is still true or false to continue looping, you can use do-while loop.

int iterator = 0;

do {
    // some code to execute and update iterator value accordingly
} while (iterator > 0);

If you want to iterate over a specific number of iterations, you can use for() loop. A for() loop has three parameters: the initial value, the terminating value, and the incrementing value. For example if you want to execute a loop 100 times to print numbers from 1 to 100 then you can use following code:

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

Finally, if you want to iterate over arrays like objects which implements iteratable interface can be looped using for each loop.  which literates over the array from zero index to last index without getting index out of bounds exception.

int[] array = {0,1,2,3,4};

for (int item : array) {
    // do something with item
}

you can also use a break statement to get out of loops when necessary. you can also use a continue statement to skip the rest of the current iteration of the loop and move on to the next iteration but before moving to the next iteration the conditional statement of the loop will be checked.

Next : Basics of Java for Android Development part 2

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: