Showing posts with label JAVA Basics Part 4. Show all posts
Showing posts with label JAVA Basics Part 4. Show all posts

Thursday, July 5, 2012

JAVA Basics 17: Interfaces

There is one thing in Java source code that is neither a class nor a member of a class. That's an interface. An interface defines methods that a class implements. In other words it declares what certain classes do. However an interface itself does nothing. All the action at least, happens inside classes. A class may implement one or more interfaces. This means that the class subscribes to the promises made by those interfaces. Since an interface promises certain methods, a class implementing that interface will need to provide the methods specified by the interface. The methods of an interface are abstract -- they have no bodies. Generally, a class implementing an interface will not only match the method specifications of the interface, it will also provide bodies -- implementations -- for its methods.
For example, a ScoreCounter class might meet the contract specified by the Counting interface:

interface Counting
{
abstract void increment();
abstract int getValue();
}

So might a Stopwatch, although it might have a totally different internal representation. Both would have increment() and getValue() methods, but the bodies of these methods might look quite different. For example, a ScoreCounter for a basketball game might implement increment() so that it counts by 2 points each time, while a Stopwatch might call its own increment() method even if no one else does.

A class that implements a particular interface must declare this explicitly:

class ScoreCounter implements Counting {
....
}

If a class implements an interface, an instance of that class can also be treated as though its type were that interface. For example, it can be labeled with a name whose declared type is that interface. For example, an instance of class ScoreCounter can be labeled with a name of type Counting. It will also answer true when asked whether it's an instanceof that interface type: if myScoreCounter is a ScoreCounter, then myScoreCounter instanceof Counting is true. Similarly, you can pass or return a ScoreCounter whenever a Counting is required by a method signature.

The generality of interfaces and the inclusion of multiple implementations within a single (interface) type is an extremely powerful feature. For example, you can use a name of type Counting to label either an instance of ScoreCOunter or an instance of Stopwatch (and use its increment() and getValue() methods) without even knowing which one you've got.

JAVA Basics 16: Classes and Objects

Following the principles of Object Oriented Programming (OOP), everything in Java is either a class, a part of a class, or describes how a class behaves. Objects are the physical instantiations of classes. They are living entities within a program that have independent lifecycles and that are created according to the class that describes them. Just as many buildings can be built from one blueprint, many objects can be instantiated from one class. Many objects of different classes can be created, used, and destroyed in the course of executing a program. Programming languages provide a number of simple data types like int, float and String. However very often the data you want to work with may not be simple ints, floats or Strings. Classes let programmers define their own more complicated data types.

All the action in Java programs takes place inside class blocks, in this case the HelloWorld class. In Java almost everything of interest is either a class itself or belongs to a class. Methods are defined inside the classes they belong to. Even basic data primitives like integers often need to be incorporated into classes before you can do many useful things with them. The class is the fundamental unit of Java programs. For instance consider the following Java program:

class HelloWorld {

  public static void main (String args[]) {

    System.out.println("Hello World");

  }

}

class GoodbyeWorld {

  public static void main (String args[]) {

    System.out.println("Goodbye Cruel World!");

  }

}


Save this code in a single file called hellogoodbye.java in your javahtml directory, and compile it with the command javac hellogoodbye.java. Then list the contents of the directory. You will see that the compiler has produced two separate class files, HelloWorld.class and GoodbyeWorld.class. javac hellogoodbye.java
The second class is a completely independent program. Type java GoodbyeWorld and then type java HelloWorld. These programs run and execute independently of each other although they exist in the same source code file. 
Class Syntax
Use the following syntax to declare a class in Java:

//Contents of SomeClassName.java
[ public ] [ ( abstract | final ) ] class SomeClassName [ extends SomeParentClass ] [ implements SomeInterfaces ]
{
        // variables and methods are declared within the curly braces
}

* A class can have public or default (no modifier) visibility.
* It can be either abstract, final or concrete (no modifier).
* It must have the class keyword, and class must be followed by a legal identifier.
* It may optionally extend one parent class. By default, it will extend java.lang.Object.
* It may optionally implement any number of comma-separated interfaces.
* The class's variables and methods are declared within a set of curly braces '{}'.
* Each .java source file may contain only one public class. A source file may contain any number of default visible classes.
* Finally, the source file name must match the public class name and it must have a .java suffix.

Here is an example of a Horse class. Horse is a subclass of Mammal, and it implements the Hoofed interface.

public class Horse extends Mammal implements Hoofed
{
         //Horse's variables and methods go here
}
Lets take one more example of Why use Classes and Objects. For instance let's suppose your program needs to keep a database of web sites. For each site you have a name, a URL, and a description. 
class website {

  String name;
  String url;
  String description;

}
These variables (name, url and description) are called the members of the class. They tell you what a class is and what its properties are. They are the nouns of the class. members. A class defines what an object is, but it is not itself an object. An object is a specificinstance of a class. Thus when we create a new object we say we are instantiating the object. Each class exists only once in a program, but there can be many thousands of objects that are instances of that class.
To instantiate an object in Java we use the new operator. Here's how we'd create a new web site:
    website x = new website();
Once we've got a website we want to know something about it. To get at the member variables of the website we can use the . operator. Website has three member variables, name, url and description, so x has three member variables as well, x.name, x.url and x.description. We can use these just like we'd use any other String variables. For instance:

    website x = new website();   
    x.name = "freehavaguide.com";
    x.url = "http://www.freejavaguide.com";
    x.description = "A Java Programming Website";
    
    System.out.println(x.name + " at " + x.url + " is " + x.description);

1
JAVA Tutorial - Class Declaration
A simple Java class declaration with constructor declaration:
class simple {
// Constructor
  simple(){
  p = 1;
  q = 2;
  r = 3;
}
int p,q,r;
}
In class declaration, you can declare methods of the class:
class simple {
// Constructor
  simple(){
   p = 1;
   q = 2;
   r = 3;
  }
  int p,q,r;
  public int addNumbers(int var1, int var2, int var3)
  {
    return var1 + var2 + var3;
  }
  public void displayMessage()
  {
   System.out.println("Display Message");
  }
}

To invoke the class, you can create the new instance of the class:
// To create a new instance class

Simple sim = new Simple();

// To access the methods of the class
sim.addNumbers(5,1,2)
// To show the result of the addNumbers

System.out.println("The result is " + Integer.toString(addNumbers(5,1,2)));

The complete listing of class declaration:
class simple {
// Constructor
 simple(){
  p = 1;
  q = 2;
  r = 3;
 }
 int p,q,r;
 public int addNumbers(int var1, int var2, int var3)
 {
  return var1 + var2 + var3;
 }
 public void displayMessage()
 {
  System.out.println("Display Message");
 }
}

class example1{
 public static void main(String args[])
 {
  // To create a new instance class
  Simple sim = new Simple();
  // To show the result of the addNumbers
  System.out.println("The result is " + Integer.toString(addNumbers(5,1,2)));
  // To display message
  sim.displayMessage();
 }
}

JAVA basics 15: Arrays

Arrays are generally effective means of storing groups of variables. An array is a group of variables that share the same name and are ordered sequentially from zero to one less than the number of variables in the array. The number of variables that can be stored in an array is called the array's dimension. Each variable in the array is called an element of the array.

Creating Arrays

There are three steps to creating an array, declaring it, allocating it and initializing it.

Declaring Arrays

Like other variables in Java, an array must have a specific type like byte, int, String or double. Only variables of the appropriate type can be stored in an array. You cannot have an array that will store both ints and Strings, for instance.

Like all other variables in Java an array must be declared. When you declare an array variable you suffix the type with [] to indicate that this variable is an array. Here are some examples:
int[] k;
float[] yt;
String[] names;
In other words you declare an array like you'd declare any other variable except you append brackets to the end of the variable type.
Allocating Arrays
Declaring an array merely says what it is. It does not create the array. To actually create the array (or any other object) use the new operator. When we create an array we need to tell the compiler how many elements will be stored in it. Here's how we'd create the variables declared above: new
k = new int[3];
yt = new float[7];
names = new String[50];
The numbers in the brackets specify the dimension of the array; i.e. how many slots it has to hold values. With the dimensions above k can hold three ints, yt can hold seven floats and names can hold fifty Strings. 
Initializing Arrays
Individual elements of the array are referenced by the array name and by an integer which represents their position in the array. The numbers we use to identify them are called subscripts or indexes into the array. Subscripts are consecutive integers beginning with 0. Thus the array k above has elements k[0], k[1], and k[2]. Since we started counting at zero there is no k[3], and trying to access it will generate an ArrayIndexOutOfBoundsException. subscripts indexes k k[0] k[1] k[2] k[3] ArrayIndexOutOfBoundsException
You can use array elements wherever you'd use a similarly typed variable that wasn't part of an array.
Here's how we'd store values in the arrays we've been working with:
k[0] = 2;
k[1] = 5;
k[2] = -2;
yt[6] = 7.5f;
names[4] = "Fred";
This step is called initializing the array or, more precisely, initializing the elements of the array. Sometimes the phrase "initializing the array" would be reserved for when we initialize all the elements of the array.
For even medium sized arrays, it's unwieldy to specify each element individually. It is often helpful to use for loops to initialize the array. For instance here is a loop that fills an array with the squares of the numbers from 0 to 100.
float[] squares = new float[101];

for (int i=0; i <= 500; i++) {
  squares[i] = i*2;
}
Shortcuts
We can declare and allocate an array at the same time like this:
int[] k = new int[3];
float[] yt = new float[7];
String[] names = new String[50];
We can even declare, allocate, and initialize an array at the same time providing a list of the initial values inside brackets like so:
int[] k = {1, 2, 3};
float[] yt = {0.0f, 1.2f, 3.4f, -9.87f, 65.4f, 0.0f, 567.9f};
Declaring, Allocating and Initializing Two Dimensional Arrays
Two dimensional arrays are declared, allocated and initialized much like one dimensional arrays. However we have to specify two dimensions rather than one, and we typically use two nested for loops to fill the array. for
The array examples above are filled with the sum of their row and column indices. Here's some code that would create and fill such an array:
class FillArray {

  public static void main (String args[]) {
  
    int[][] M;
    M = new int[4][5];
  
    for (int row=0; row < 4; row++) {
      for (int col=0; col < 5; col++) {
        M[row][col] = row+col;
      }
    }
    
  }
  
}
In two-dimensional arrays ArrayIndexOutOfBounds errors occur whenever you exceed the maximum column index or row index. Unlike two-dimensional C arrays, two-dimensional Java arrays are not just one-dimensional arrays indexed in a funny way. You don't have to stop with two dimensional arrays. Java lets you have arrays of three, four or more dimensions. However chances are pretty good that if you need more than three dimensions in an array, you're probably using the wrong data structure. Even three dimensional arrays are exceptionally rare outside of scientific and engineering applications.
The syntax for three dimensional arrays is a direct extension of that for two-dimensional arrays. Here's a program that declares, allocates and initializes a three-dimensional array:
class Fill3DArray {

  public static void main (String args[]) {
  
    int[][][] M;
    M = new int[4][5][3];
  
    for (int row=0; row < 4; row++) {
      for (int col=0; col < 5; col++) {
        for (int ver=0; ver < 3; ver++) {
          M[row][col][ver] = row+col+ver;
        }
      }
    }
    
  }
  
}
Example 1 : declaring and initializing 1-dimensional arrays

An array groups elements of the same type. It makes it easy to manipulate the information contained in them.

class Arrays1{ 

public static void main(String args[]){

// this declares an array named x with the type "array of int" and of 
// size 10, meaning 10 elements, x[0], x[1] , ... , x[9] ; the first term
// is x[0] and the last term x[9] NOT x[10].
int x[] = new int[10];

// print out the values of x[i] and they are all equal to 0.
for(int i=0; i<=9; i++)
System.out.println("x["+i+"] = "+x[i]);

// assign values to x[i] 
for(int i=0; i<=9; i++)
x[i] = i; // for example

// print the assigned values of x[i] : 1,2,......,9
for(int i=0; i<=9; i++)
System.out.println("x["+i+"] = "+x[i]);

// this declares an array named st the type "array of String"
// and initializes it
String st[]={"first","second","third"};

// print out st[i]
for(int i=0; i<=2; i++)
System.out.println("st["+i+"] = "+st[i]);

}
}


Example 2 : Find the sum of the numbers 2.5, 4.5, 8.9, 5.0 and 8.9

class Arrays2{ 

public static void main(String args[]){

// this declares an array named fl with the type "array of int" and
// initialize its elements

float fl[] = {2.5f, 4.5f, 8.9f, 5.0f, 8.9f};

// find the sum by adding all elements of the array fl
float sum = 0.0f;
for(int i=0; i<= 4; i++)
sum = sum + fl[i];

// displays the sum
System.out.println("sum = "+sum);
}
}


Check that the sum displayed is 29.8.

Example 3 : declaring and initializing 2-dimensional arrays

class Arrays3{ 

public static void main(String args[]){

// this declares a 2-dimensional array named x[i][j] of size 4 (4 elements)
// its elements are x[0][0], x[0][1], x[1][0] and x[1][1].
// the first index i indicates the row and the second index indicates the
// column if you think of this array as a matrix.


int x[][] = new int[2][2];

// print out the values of x[i][j] and they are all equal to 0.0.
for(int i=0; i<=1; i++)
for(int j=0; j<=1; j++)
System.out.println("x["+i+","+j+"] = "+x[i][j]);

// assign values to x[i] 
for(int i=0; i<=1; i++)
for(int j=0; j<=1; j++)
x[i][j] = i+j; // for example

// print the assigned values to x[i][j] 
for(int i=0; i<=1; i++)
for(int j=0; j<=1; j++)
System.out.println("x["+i+","+j+"] = "+x[i][j]);

// this declares a 2-dimensional array of type String
// and initializes it
String st[][]={{"row 0 column 0","row 0 column 1"}, // first row 
{"row 1 column 0","row 1 column 1"}}; // second row 

// print out st[i]
for(int i=0; i<=1; i++)
for(int j=0; j<=1; j++)
System.out.println("st["+i+","+j+"] = "+st[i][j]);

}
}

JAVA Basic 14: Methods (Includes Recursive Methods)

A method is a group of instructions that is given a name and can be called up at any point in a program simply by quoting that name. Each calculation part of a program is called a method. Methods are logically the same as C's functions, Pascal's procedures and functions, and Fortran's functions and subroutines.

When I wrote System.out.println("Hello World!"); in the first program we were using the System.out.println() method. TheSystem.out.println() method actually requires quite a lot of code, but it is all stored for us in the System libraries. Thus rather than including that code every time we need to print, we just call the System.out.println() method.

You can write and call your own methods too. Methods begin with a declaration. This can include three to five parts. First is an optional access specifier which can be public, private or protected. A public method can be called from pretty much anywhere. Aprivate method can only be used within the class where it is defined. A protected method can be used anywhere within the package in which it is defined. Methods that aren't specifically declared public or private are protected by default. access specifier. We then decide whether the method is or is not static. Static methods have only one instance per class rather than one instance per object. All objects of the same class share a single copy of a static method. By default methods are not static. We finally specify the return type
Next is the name of the method.
Source Code
class FactorialTest {    //calculates the factorial of that number.

  public static void main(String args[]) {

    int n;
    int i;
    long result;

    for (i=1; i <=10; i++)  {
      result = factorial(i);
      System.out.println(result);
    }

  } // main ends here
  
  
  static long factorial (int n) {

  int i;
  long result=1;
  
  for (i=1; i <= n; i++) {
   result *= i;
  }
  
  return result;

} // factorial ends here


}

Recursive Methods

Recursion is used when a problem can be reduced into one or several problems of the same nature, but a smaller size. This process is usually repeated until a boundary situation is reached, where the problem can be directly solved. Java supports recursive methods, i.e. even if you're already inside methodA() you can call methodA(). 
Example  (A Recursive Counterpart of the Above Factorial Method)
n! is defined as n times n-1 times n-2 times n-3 ... times 2 times 1 where n is a positive integer. 0! is defined as 1. As you see n! = n time (n-1)!. This lends itself to recursive calculation, as in the following method:
public static long factorial (int n) {

  if (n < 0) {
    return -1;
  } 
  else if (n == 0) {
    return 1;
  }
  else {
    return n*factorial(n-1);
  }

}