Saturday, March 30, 2013

Java array


In java, arrays are treated as objects.

While using arrays, we create objects for arrays, whose class is non-existent (which we have not done so far.)

Whenever JVM encounters [], it understand that it has to create an object. Thus, array objects can be created without using the ‘new’ operator.

One of the peculiar characteristics of the array is that, without using the name of the class, we use ‘new’ operator to create an array object.

In any programming language, we cannot create an object without mentioning the  size of the array.
Once the size is defined , it is fixed .we cannot alter it during run time.

Ex:
Int arr[] = new  int[5];
arr is reference to an array of integer type.

System.out.println(arr[0]);

The above statement prints ‘0’ because uninitialized locations(values) would be initialized with their default values.

arr[1] = 10; // initialize the location with index 1 to 10.

Length: It is an non-static variable defined inside array object and the values of that variables is nothing but the size of the array.

System.out.println(arr.length); // prints the size of the array arr.

Note :  With respect to arrays, length is not a function . As mentioned above, it is a non-static variable that belong to array object.


Creating array object without using ‘new’ operator

Class Ademo1
{
Public static void main (String args[])
{
Int i[] = {10,9,8,7};
Char ch[] = {‘a’,’b’,’c’,’9’,’4’};
System.out.println(ch[i]); // ch[1] = b
System.out.println(i[1]); // ch[1] = 9
}
}

Note:  As soon as JVM encounters {}, it creates an object with the values present in {} and assigns the address of the object to a variable.

In the way, we can create array objects of all primitive data types.

In a similar way, we can define arrays of the objects of classes.





 


Friday, March 29, 2013

String class and StringBuffer class

A String is a group of characters.

String classes are used to represents these group of characters.

We can even create an object of a string class without using ‘new’ operator. Instead of the ‘new’ operator we use double quotes(“”).

As soon as JVM encounters “ “, it understands  that it is has to create a object of the String class with the contents present in “ “ and for each and every individual character inside ” “ it assigns a unique index value starting from Zero.

Ex: String s=”abcde”;

Address of the object is assigned to the variable s.

This object has a very near relation with arrays.

Once a String object is created, the data inside the object cannot be modified. This is the reason. Why, we say that , String are mutuable.

Different ways of creating String objects are shown below.

String s1 = new String ();
String s2 = new String (“abc”);
String s3 =  “ MSDASS”;

Consider the following two statements.
A a1 = new A();
String s1 = “abcde”;

Both the above statements create the object of their respective classes.

Now, when we say

System.out.println(a1);  --  Its prints the address of the object,

whereas for  System.out.println(s1); -- it prints abcde (i.e the contents of the object).Why?

The explanation is related to static polymorphism.The prinln() method,called in the above two cases is not the same.

One println() method is defined to accept object of object class and its functionality is to print the address of the onject.

The second println() method is defined to accept object of String class and its functionality is to print the contents of the object pointed by the address.

Question:

 What is the difference b/w creating the string object using new operator and creating the string object using double quotes?

Ans : Using new operator, we can create many objects of the same String class.

Ex:
 String s1 = new String (“xyz”);
String s2  = new String (“xyz”) ;

Here, through the contents are same, two different objects are created and the address are assigned to different variables.

But when we create objects of string class using double quotes, we can almost create only one object.

If we try to create more objects, the same address of the already created object will be assigned to the variables pointing to the newly created objects.

Ex:
String s1 = “MSD”;
String s2 = “MSD”;

The above example explained difference is illustrated in the following program.

Class Sdemo1
{
Public Static void main(String args[])
{
String s1 = “abc”;
String s2 = new String (“xyz”);
String s3 = new String (“xyz”);
If(s2 == s3){
System.out.println(s2 and s3 are equal);
else{
System.out.println(s2 and s3 are not equal); //this statement is executed
}
String s4 = “abc”;
If(s1==s4){
System.out.println(s1 and s4 are equal); //this statement is executed
}else{
System.out.println(s1 and s4 are not equal);
}
}
}

String Concatenation:

Appending a string to another string is known as string concatenation.

The ‘+’ symbol acts as the concatenation operator.

Note: + operator works as an arithmetic operator if and only if the two operator operands supplied to the + operator are arithmetic.

+ operator works as a concatenation operator if atleast one operand supplied to the + operator is a String  object.

Concatenation operator always outputs a new String class object with the contents of LHS and RHS of the + operator.

Ex:
String s1 = “abc” + “xyz”;

System.out.println(s1); //it prints abcxyz

String s2 = “MSD”;

S2= s2 + “SSA”;

System.out.println(s2); //it prints  MSDSSA


Question:

We said that Strings are immutable(i.e: contents of the object of string class cannot be changed), but  how are the above statements possible?

Ans: Actually, the content of the object pointed by s2 is not changed. Infact, a new object is created and the same new content is appended to the existing content and this is stored is in the object and the address of the object is assigned to variable.


StringBuffer Class:

We said that Strings are immutable. But we have another class by name StringBuffer class, the contents of where objects are mutable.

i.e: we can alter the contents of the object which is created upon the stringbuffer class.

Ex:
StringBuffer sb1 = new StringBuffer (“abc”);

Some of the methods available in the StringBuffer class are

append();
remove();
replace(); etc.

By using these methods, we can alter the contents of the object od StringBuffer class.

StringBuffer sb2= new String (“xyz”);

String s3 = new String (“abc”);

Both the above statement s are not the valid statement s .The reason  is , we are typing  to assign 
 object of one class to reference of another class which is against the rules that an object of a class  should be assigned to the reference variable of the type same class.











Wednesday, March 27, 2013

Object Cloning


Objects in Java are referred using reference types, and there is no direct way to copy the contents of an object into a new object.

The assignment of one reference to another merely creates another reference to the same object. Therefore, a special clone() method exists for all reference types in order to provide a standard mechanism for an object to make a copy of itself. Here are the details you need to know about cloning Java objects.

Why create a local copy?



The most probable reason for creating a local copy of an object is because you plan to modify the object, and you don't want to modify the method caller's object. If you decide that you need a local copy, you can perform the operation by using the clone() method of the Object class. The clone() method is defined as protected, but you must redefine it as public in all subclasses that you might want to clone.

For example, the standard library class ArrayList overrides clone(), so you can call clone() for ArrayList, like this:

Code: Java
import java.util.*;
  class MyInt 
  {
      private int i;
  
  
      public MyInt(int ii) { i = ii; }
  
  
      public void increment() { i++; }
  
  
      public String toString() 
      {
          return Integer.toString(i);
      }
   }
  
  
  public class Test 
  {
      public static void main(String[] args) 
      {
          ArrayList al = new ArrayList(); 
          for(int i = 0; i < 10; i++ )
              al.add(new MyInt(i));
          
          ArrayList al1 = (ArrayList)al.clone();
          // Increment all al1's elements:
          for(Iterator e = al1.iterator(); e.hasNext(); )
                  ((MyInt)e.next()).increment();
    }
   }
The clone() method produces an Object, which must be recast to the proper type. This example shows how ArrayList's clone() method does not automatically try to clone each of the objects that the ArrayList contains -- the old ArrayList and the cloned ArrayList are aliased to the same objects. This is often called a shallow copy, since it's only copying the "surface" portion of an object. The actual object consists of this "surface," plus all the objects that the references are pointing to and all the objects those objects are pointing to, etc. This is often referred to as the "Web of objects." When you copy the entire mess, it is called a deep copy.

The Cloneable interface and deep copies



By default, classes in Java do not support cloning; the default implementation of the clone() method throws a CloneNotSupportedException. You should override implementation of the clone() method. Remember that you must make it public and, inside the method, your first action must be super.clone(). Classes that want to allow cloning must implement the marker interface Cloneable. Since the default implementation of Object.clone only performs a shallow copy, classes must also override clone to provide a custom implementation when a deep copy is desired. Basically, if you want to make objects of your class publicly cloneable, you need code like this:
Code: Java
class Test implements Cloneable
  {
   ...
      public Object clone()
      {
          try
      {
              return super.clone();
          }
      catch( CloneNotSupportedException e )
      {
              return null;
          }
      } 
  ...
  }
If you are happy with a protected clone, which just blindly copied the raw bits of the object, you don't need to redefine your own version. However, you will usually want a public one. (Note: You can't create a private or default scope clone; you can only increase the visibility when you override.)

Possible problems and a solution



Since the clone() method is protected, subclasses have to explicitly agree to be cloneable by overriding this protected method with a public method. All of the Collections classes do this. The subclass also has to implement Cloneable for the default cloning mechanism in Object.clone() to work.

If you have an object that you know has a public clone() method, but you don't know the type of the object at compile time, you have problems. For instance, say x is declared as an Object. You can't just call x.clone() because Object.clone() is protected. If Cloneable defined a public clone() method, you could use ((Cloneable) x).clone(), but it doesn't. You either have to enumerate all the classes that you think x could be, or you have to resort to reflection.

Another problem arises when you try deep copying of a complex object. You're assuming that the clone() method of all member object variables also does deep copy; this is too risky of an assumption. You must control the code in all classes, or you must know that all classes involved in deep copy operation do such a copy in the right way.

One solution to these problems is to clone using serialization. Serialization is usually used to send objects off somewhere (such as into a file or over the network) so that somebody else can reconstruct them later. You can abuse serialization to immediately reconstruct the object yourself. If the object is serializable at all, the reconstruction should be a faithful copy. In normal uses of serialisation, the original object is nowhere near a faithful copy; it could be on the other side of the world at the far end of a network connection. You can be sure that changing the copy will have no effect on the original.

Tuesday, March 19, 2013

Java - The Data Structures


The data structures provided by the Java utility package are very powerful and perform a wide range of functions. These data structures consist of the following interface and classes:
·         Enumeration
·         BitSet
·         Vector
·         Stack
·         Dictionary
·         Hashtable
·         Properties
All these classes are now legacy and Java-2 has introduced a new framework called Collections Framework which is discussed in next tutorial:

The Enumeration:

The Enumeration interface isn't itself a data structure, but it is very important within the context of other data structures. The Enumeration interface defines a means to retrieve successive elements from a data structure.
For example, Enumeration defines a method called nextElement that is used to get the next element in a data structure that contains multiple elements.
To have more detail about this interface, check TheEnumeration.

The BitSet

The BitSet class implements a group of bits, or flags, that can be set and cleared individually.
This class is very useful in cases where you need to keep up with a set of boolean values; you just assign a bit to each value and set or clear it as appropriate.
To have more detail about this class, check TheBitSet.

The Vector

The Vector class is similar to a traditional Java array, except that it can grow as necessary to accommodate new elements.
Like an array, elements of a Vector object can be accessed via an index into the vector.
The nice thing about using the Vector class is that you don't have to worry about setting it to a specific size upon creation; it shrinks and grows automatically when necessary.
To have more detail about this class, check TheVector.

The Stack

The Stack class implements a last-in-first-out (LIFO) stack of elements.
You can think of a stack literally as a vertical stack of objects; when you add a new element, it gets stacked on top of the others.
When you pull an element off the stack, it comes off the top. In other words, the last element you added to the stack is the first one to come back off.
To have more detail about this class, check TheStack.

The Dictionary

The Dictionary class is an abstract class that defines a data structure for mapping keys to values.
This is useful in cases where you want to be able to access data via a particular key rather than an integer index.
Since the Dictionary class is abstract, it provides only the framework for a key-mapped data structure rather than a specific implementation.
To have more detail about this class, check TheDictionary.

The Hashtable

The Hashtable class provides a means of organizing data based on some user-defined key structure.
For example, in an address list hash table you could store and sort data based on a key such as ZIP code rather than on a person's name.
The specific meaning of keys in regard to hash tables is totally dependent on the usage of the hash table and the data it contains.
To have more detail about this class, check TheHashtable.

The Properties

Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String.
The Properties class is used by many other Java classes. For example, it is the type of object returned by System.getProperties( ) when obtaining environmental values.
To have more detail about this class, check TheProperties.