Search Java Programs
Thursday, January 7, 2010
Classes and Methods
| ||
Classes Introduction A class is declared by the use of class keyword. The general form of a class is given above. The class with the main method initiates execution of a program. There can be classes created without main method. These classes will act as a user defined data types or the type definition. | ||
A Simple class Here is a class called as Box that defines three variables : length, width and height. Currently class box does not contains any methods. In this case we have created a new data type called Box. | ||
Constructors Constructor name is class name. A constructors must have the same name as the class its in. Default constructor. | ||
Parameterised Constructors Constructors and methods differ in three aspects of the signature: modifiers, return type, and name. Like methods, constructors can have any of the access modifiers: public, protected, private, or none. Unlike methods, constructors can take only access modifiers. Therefore, constructors cannot be abstract, final, native, static, or synchronized. | ||
Garbage Collection The name "garbage collection" implies that objects no longer needed by the program are "garbage" and can be thrown away. A more accurate and up-to-date metaphor might be "memory recycling." When an object is no longer referenced by the program, the heap space it occupies can be recycled so that the space is made available for subsequent new objects. The garbage collector must somehow determine which objects are no longer referenced by the program and make available the heap space occupied by such unreferenced objects. In the process of freeing unreferenced objects, the garbage collector must run any finalizers of objects being freed. | ||
The finalise() method Before an object is garbage collected, the runtime system calls its finalize() method. The intent is for finalize() to release system resources such as open files or open sockets before getting collected. Your class can provide for its finalization simply by defining and implementing a method in your class named finalize(). Your finalize() method must be declared as follows: | ||
Overloading Methods Overloading is used in the standard Java classes. The System.out.println method accepts multiple parameter lists. This sample code snippet is valid: | ||
Recursion It is the central Simply put, recursion is when a function calls itself. That is, in the course of the function definition there is a call to that very same function. At first this may seem like a never ending loop, or like a dog chasing its tail. It can never catch it. So too it seems our method will never finish. This might be true is some cases, but in practise we can check to see if a certain condition is true and in that case exit (return from) our methodclass Factorial { int fact(int n) { int result; if ( n ==1) return 1; result = fact (n-1) * n; return result; } } public class Recursion { public static void main (String args[]) { Factorial f =new Factorial(); System.out.println(“Factorial of 3 is “ + f.fact(3)); System.out.println(“Factorial of 3 is “ + f.fact(4)); System.out.println(“Factorial of 3 is “ + f.fact(5)); } } The output from this program is shown here: Factorial of 3 is 6 Factorial of 4 is 24 Factorial of 5 is 120 | ||
The final Keyword A variable can be declared as final. Doing so prevents its contents from being modified. This means we have to initialize the variable when it is declared. Keyword final in java is similar to "const" in c / c++. The value of final variables will remain same through out the application.For example: final int FILE_NEW = 1; final int FILE_OPEN = 2; final int FILE_SAVE = 3; final int FILE_SAVEAS = 4; final int FILE_QUIT = 5; | ||
Arrays Revisited Arrays are aslo implemented as objects. Hence there is a special array attribute to tell the size of the array, that is teh number of elements that an array can hold is found in its length instance variable. All arrays have this variabe, and it will always hold the size of the array. Here is a program that demonstrates this property.public class Length { int l; public static void main(String args[]){ int n1[] = new int[10]; int n2[] = {3, 5, 7, 1, 8, 99, 44, -10); int n3[] = { 4, 3, 2, 1); System.out.println(“Length of n1 is “ + n1.length); System.out.println(“Length of n2 is “ + n1.length); System.out.println(“Length of n3 is “ + n1.length); } The output from this program is shown here: Length of n1 is 10 Length of n2 is 8 Length of n3 is 4 |
Classes and Methods
Methods are subroutines or functions used to perform a task with or modify an object. Since classes are the base of all java structures all functions must be included in a class. There are three levels of visibility for methods, public, private, and protected. Public methods are accessible from anywhere in the program, private methods are only accessible from within the class, and protected methods are available inside the class and any subclasses in the same package. If no access is specified class and package have access but not subclasses. A method must declare the type of return value or void for no return value.
Classes may also contain class wide variables with the same public, private, protected attributes. It is usually considered best practice to set the class variables as private and use public getter and setter routines to access the variable. This is called encapsulation.Include GetterSetterEx.java
class GetterSetterEx {
private int i = 0;
private String s = "string";
public int getI() {
return(this.i);
}
public void setI(int i) {
this.i = i;
}
public String getS() {
return(s);
}
public boolean isSLongerThanI() {
if (s.length() > i) {
return(true);
} else {
return(false);
}
}
public GetterSetterEx(int i, String s) {
this.i = i;
this.s = s;
}
}
This class simply demonstrates how to create private class variables and getter/setter methods for each. The variables are declared as private and can only be accessed from this class. When using this class in conjunction with any other class you must use the get and set methods for each variable. In addition to the getters and setters we added another simple method to determine if the string is longer than the value of the integer.
Also notice the final method in the class, and how it has the same name as the class. This is called the constructor and is called whenever the class is initialized. This method expects 2 values to be passed at initialization. The constructor method should always be declared public with no return type or void declaration. Multiple constructors can exist with different parameter types that handle initialization differently.
Importing Packages
Java uses the import command to include external packages to extend the functionality of your application. The Java Runtime Environment (JRE) includes a large set of libraries to build your application with ranging from network socket connections to graphical user interface (GUI) building packages. Before a package or class, such as the one we previously created can be used, they must be imported. The import statement comes at the beginning of the .java file and should be outside the class declaration.
Conditionals and Loops
Conditionals perform the core logic switching of your application. Java uses the standard and, or operator syntax for comparison, and (&&) ... or (||) Operators along with equals (==) and not equals (!=). Unlike some languages you cannot compare strings with == or != except to check nullness. To check if 2 strings are equal check stringOne.equals("String to match").
if ... else
The if ... else statement is the base of the conditional.Create a new file IfElseEx1.java
class IfElseEx1 {The if ... else example checks if the first argument passed is contained in the second argument passed.
public static void main(String[] args) {
if (args[1].contains(args[0])) {
System.out.println(args[0] + " is contained in " + args[1]);
} else {
System.out.println(args[0] + " is not contained in " + args[1]);
}
}
}
Create a new file IfElseEx2.java
class IfElseEx2 {
public static void main(String[] args) {
String s = "this is a string";
if (s == null) {
System.out.println("String is null");
} else if (s.equals("will this match?")) {
System.out.println("I guess it did");
} else if (s.equals("this is a string")) {
System.out.println("this is a string matched");
} else {
System.out.println("no match");
}
}
}
This example demonstrates how to find if two strings match. Strings also have a method equalsIgnoreCase that is a non case sensitive match. Also demonstrated is the if else syntax that allows an if statement to have multiple conditions to attempt to match.
switch ... case
The switch statement is a conditional similar to if, but if used to check one variable for a series of conditions. The switch checks the variable against each case. A case is terminated by a break statement. If a break statement is missing the code will fall through and execute the next case until a break statement is reached. The default case is executed if no other case checks matchCreate the file SwitchCaseEx.java
class SwitchCaseEx {
public static void main(String[] args) {
switch(args.length) {
case 1:
System.out.println("One command line argument");
break;
case 2:
System.out.println("Two command line arguments");
break;
case 3:
System.out.println("Three command line arguments");
break;
case 4:
System.out.println("Four command line arguments");
break;
case 5:
System.out.println("Five command line arguments");
break;
default:
System.out.println("0 or more than 5 command line arguments");
break;
}
}
}
This isn't the most creative way to show a switch statement but it clearly displays the syntax. In instances where a switch can replace an if/else block it probably should as this is much cleaner, easier to read code. Switch statements in Java can only be applied to integer style types (byte, short, int), char, and enumerated types (not covered in this tutorial). If there are no command line arguments passed or more than 5 command line arguments the default case is called, otherwise the proper case statement is executed.
Loops
Loops are used to conditionally repeat blocks of code. Java implements the common while, for, and foreach loops along with a do ... while loop.
While
Repeat the block of code while the condition is true.Create the file WhileEx.java
class WhileEx {
public static void main(String[] args) {
int i = 0;
int j;
while (i <= 5) {
j = i * 5;
System.out.println(i + " * 5 = " + j);
i++;
}
}
}
This loop will iterate 6 times. When executing a while statement like this it is important to remember to increment the conditional variable.
do ... while
A while loop with the iterate conditional at the end of the loop block. Do while loops will always iterate once since the check is after the code block.Create the file DoWhileEx.java
class DoWhileEx {
public static void main(String[] args) {
int i = 0;
int j;
do {
j = i * 5;
System.out.println(i + " * 5 = " + j);
i++;
} while (i <= 5);
}
}
This code performs exactly as with the While loop example. The only difference is that the conditional is checked after the code block is executed.
For
For loops are used to iterate through a loop a number of times. The iteration conditional in a for loop has 3 parts, the counter initialization, the conditional to check, the increment syntax. The increment syntax is executed each time through the loop.Create the file ForEx.java
class ForEx {
public static void main(String[] args) {
int j;
for (int i=0; i < 10; i++) {
j = i * i;
System.out.println(i + " squared is: " + j);
}
}
}
This simple for loop squares the counter variable. Notice that even though the increment is listed at the top of the code it isn't executed until after the first iteration.
Foreach
Foreach loops are used to iterate through a list of values. In Java a foreach loop uses the for statement with different syntax to declare how to iterate.Create the file ForeachEx.java
class ForeachEx {
public static void main(String[] args) {
String[] sArray = {"This", "is", "an", "array", "of", "strings" };
for (String s : sArray) {
System.out.println(s);
}
}
}
Loop through the array of strings displaying each to the screen.
Arrays, Strings and Other Common Types
Arrays
All primitive types can be turned into arrays. Arrays are simply indexed lists of the type in which they are initialized. Arrays are initialized by adding [] to the type when declaring the variable.Create a file ArrayEx.java
class ArrayEx {
public static void main(String[] args) {
int[] iArr;
char cArr[] = {'F', 'a', 'k','e', 'S', 't', 'r', 'i', 'n', 'g'};
iArr = new int[4];
iArr[0] = 1;
iArr[1] = 10;
iArr[2] = 20;
iArr[3] = iArr[1] * iArr[2];
System.out.println(iArr.length);
System.out.println(cArr.length + " - " + cArr.toString());
}
}
First initialize an integer array and a character array. The character array is not a real string as the example will show. You need to use the String type explained next for that. Notice that the first index of the array is 0. So the integer array iArr has 4 indexes numbered 0-3.
Strings
Strings in Java are implemented through java.lang.String. java.lang.String provides a good interface for the storing and manipulation of string data.Create the file StringEx.java
class StringEx {Initialize a new String s with the value "new string" without the quotes. Print the string. Then print the length of the string. The split method accepts a string as an input and uses that to break the string into an array of strings. We then take the length of that array. In the example we split on a space and use that to calculate the number of words in the string.
public static void main(String[] args) {
String s = "new string";
System.out.println(s);
System.out.println("Length: " + s.length());
System.out.println("Number of words: " + s.split(" ").length);
}
}
Java variables
Create a new file CommandLineEx.java
class CommandLineEx {
public static void main(String[] args) {
System.out.println(args[0]);
}
}
This code functions exactly like HelloWorld.java except the printed string comes from the first argument passed to the program. All other options passed on the command line are ignored. See the for loop example for a more complete example of parsing command line variables.
Basic Variable Types
Java variables are typed and must be declared before use. Java has 8 primitive data types. A byte is an 8 bit signed integer with an allowable value between -128 and 127. A short is a 16 bit signed integer with an allowable value between -32738 and 32767. An int is a 32 bit signed integer with an allowable value between -2,147,483,648 and 2,147,483,647. A long is a 64 bit signed integer with an allowable value between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807.Create file BasicDataIntEx.java
class BasicDataIntEx {
public static void main(String[] args) {
byte b = 5;
byte b2;
short s = 48;
short s2;
int i = 100;
int i2;
long l = 1000;
long l2;
i2 = i / b;
l2 = l * s;
System.out.println(i2);
}
}
First initialize 2 variables each of byte, short, int long types, and perform some math operations on the values and print. Math operations cannot be stored into byte or short types, but they can be used in mathmatical operations stored into int or long types.
Adjust BasicDataIntEx.java so the math operations and output are:
i++;
l--;
i+=10;
l-=100;
System.out.println(i2);
System.out.println(l2);
System.out.println(i);
System.out.println(l);
When an integer style variable is followed by ++ the variable is incremented, and -- it is decremented. If these statements happened to be part of an equation a = b++; a would contain the value of b before the incrementing. Also a = --b; a would be one less than the value of b, but b would remain unchanged. The code i += 10 is shorthand for i = i + 10; and the code l-=100 is similar shorthand for l = l - 100.
The rest of the Java primitive data types are, float which is a 32 bit single precision IEEE 754 floating point number. Double, a 64 bit single precision IEEE 754 floating point number. The char, a single 16 bit unicode character. And boolean which is the standard true/false boolean type.Create the file FloatDoubleEx.java
class FloatDoubleEx {You might notice this is simply the formula to find the circumference of a circle. Floating point numbers should be denoted with a trailing f. Now change the variable types to double. Also change the trailing f to a d to denote double.
public static void main(String[] args) {
float pi = 3.14f;
float r = 4f;
float c;
c=pi*(r*r);
System.out.println(c);
}
}
Create a file CharBooleanEx.java
class CharBooleanEx.java {We don't do much with these at this point but show you how to declare them.
public static void main(String[] args) {
char a = "b";
boolean b = true;
}
}
Introduction To Java
What is Java?
Java is an open source object oriented programming language developed by Sun Microsystems. The Java language is commonly used to build a variety of client applications and web systems. Java has been growing in popularity and usage in the field since it's release, and the Java platform was designed to be cross platform compatible with the under the hood work done by the Java Runtime.
Basic Syntax
With Java everything is an object. Each object is represented by a class and is stored in a .java source file. Java programs are a collection of classes that work together.Create a new file HelloWorld.java
class HelloWorld {Before we can execute this, we must compile it. With Java you use the javac command to compile a java class. This will be the only place in this tutorial where we cover compiling as it's the same process for the entire tutorial.
public static void main(String[] args) {
System.out.println("Hello World");
}
}
$ javac HelloWorld.javaThe class should have the same name of the .java file. Functions in Java are commonly called methods. The method main is used as the function to call when the program is executed. Methods will be covered in detail later. Values passed to the program from the command line will be stored in the String array args. The System.out.println method is called and passed Hello World. System.out.println pushes to the display (STDOUT) the passed argument followed by a newline. All code blocks in Java are delimited with { }.
$ java HelloWorld
Hello World
Working With Android Contacts
Learn to work with the Android contacts database. Basic knowledge of accessing SQLite in Android along with using Cursors is expected. See the Android SQLite and Cursor Article for more information. Google changed the contacts database moving from 1.x to 2.0 versions of Android. This tutorial will be broken into 3 sections. First covering accessing contacts in Android 2.0. The second page will deal with accessing the contacts in Android 1.6 and before. Third we'll glue it all together with a class that abstracts specific classes for each version and a set of classes to manage the data from the contact records.
Create a new project called TestContacts in Eclipse setup for Android 2.0.
Android Contact API For 2.0
Granting Access
Before an application can query the contact records access must be granted through the AndroidManifest.xml file stored in the root of the project. Add the following uses-permission belows the uses-sdk statement.
<uses-permission android:name="android.permission.READ_CONTACTS" />
Querying The Android Contact Database
Retrieving Contact Details
Basic contact information stored in Contacts table with detailed information stored in individual tables for normalization. In Android 2.0 to query the base contact records the URI to query is stored in ContactsContract.Contacts.CONTENT_URI.package higherpass.TestContacts;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
public class TestContacts extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//Query phone here. Covered next
}
}
}
}
}
This application starts off as any other Android application. First create a ContentResolver isntance in cr. Then use the ContentResolver instance to query the database and return a Cursor with the contacts list. The query is perofrmed against the URI stored in ContactsContract.Contacts.CONTENT_URI. Next check if the cursor contains records and if so loop through them. The record ID field is stored in the id variable. This will be used as a where parameter later. Also the display name field is stored in the string name. For more details about working with cursors see Android Cursors Tutorial.
Phone Numbers
Phone numbers are stored in their own table and need to be queried separately. To query the phone number table use the URI stored in the SDK variable ContactsContract.CommonDataKinds.Phone.CONTENT_URI. Use a WHERE conditional to get the phone numbers for the specified contact.if (Integer.parseInt(cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
// Do something with phones
}
pCur.close();
}
Perform a second query against the Android contacts SQLite database. The phone numbers are queried against the URI stored in ContactsContract.CommonDataKinds.Phone.CONTENT_URI. The contact ID is stored in the phone table as ContactsContract.CommonDataKinds.Phone.CONTACT_ID and the WHERE clause is used to limit the data returned.
Email Addresses
Querying email addresses is similar to phone numbers. A query must be performed to get email addresses from the database. Query the URI stored in ContactsContract.CommonDataKinds.Email.CONTENT_URI to query the email address table.Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
}
emailCur.close();
As with the phone query the field names for the email table are also stored under ContactsContract.CommonDataKinds. The email query is performed on the URI in ContactsContract.CommonDataKinds.Email.CONTENT_URI and the WHERE clause has to match the ContactsContract.CommonDataKinds.Email.CONTACT_ID field. Since multiple email addresses can be stored loop through the records returned in the Cursor.
Notes
Custom notes can be attached to each contact record. As before these are stored in a separate table and are related based on the contact ID.String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] noteWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, noteWhere, noteWhereParams, null);
if (noteCur.moveToFirst()) {
String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
}
noteCur.close();
Notes are stored in the Android Contacts generic data table. When accessing specific data the WHERE clause will need 2 conditionals. First the standard contact ID, second a MIMETYPE for the data that is being requested. The Android SDK comes with a series of auto-generated variables that take care of this. Use the ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE variable to limit the query to note records. The data table URI is stored at ContactsContract.Data.CONTENT_URI. Finally the note field name is stored in ContactsContract.CommonDataKinds.Note.NOTE.
Postal Addresses
Android can store multiple postal addresses per contact. Addresses are also stored in the data table like notes and queried via the URI stored in ContactsContract.Data.CONTENT_URI. Similar to the notes query a MIMETYPE must be added to the WHERE conditional. Also in Android 2.0 the Address record was split into multiple fields containing different parts of the address (PO-Box, stree, city, region, postal code). In earlier versions of the Android SDK this was a free-form string storage.String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] addrWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, where, whereParameters, null);
while(addrCur.moveToNext()) {
String poBox = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
String street = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
String city = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
String state = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
String postalCode = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
String country = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
String type = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
}
addrCur.close();
This code is similar to the previous example. Notice the field names for the address pieces are stored in ContactsContract.CommonDataKinds.StructuredPostal.
Instant Messenger (IM)
The instant messenger query performs just as the notes and address queries. Important field names for IM related data are stored in ContactsContract.CommonDataKinds.Im.String imWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] imWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE};
Cursor imCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, imWhere, imWhereParams, null);
if (imCur.moveToFirst()) {
String imName = imCur.getString(
imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
String imType;
imType = imCur.getString(
imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE));
}
imCur.close();
Organizations
The last part of the contact record to be covered is the Organizations data. The Android contact record can contain information about Employment, professional, and social memberships as well as roles and titles. These records are queried from the URI stored in ContactsContract.Data.CONTENT_URI. Important field names for the organization data are stored in ContactsContract.CommonDataKinds.Organization.String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor orgCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
if (orgCur.moveToFirst()) {
String orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
String title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
}
orgCur.close();