Wednesday 27 October 2010

Generics and Subtyping

Let’s test our understanding of generics. Is the following code snippet legal?

List<String> ls = new ArrayList<String>(); //1
List<Object> lo = ls; //2


Line 1 is certainly legal. The trickier part of the question is line 2. This boils down
to the question: is a List of String a List of Object. Most people’s instinct is to answer:
“sure!”.
Well, take a look at the next few lines:

lo.add(new Object()); // 3
String s = ls.get(0); // 4: attempts to assign an Object to a String!


Here we’ve aliased ls and lo. Accessing ls, a list of String, through the alias lo, we
can insert arbitrary objects into it. As a result ls does not hold just Strings anymore,
and when we try and get something out of it, we get a rude surprise.
The Java compiler will prevent this from happening of course. Line 2 will cause a
compile time error.
In general, if Foo is a subtype (subclass or subinterface) of Bar, and G is some
generic type declaration, it is not the case that G<Foo> is a subtype of G<Bar>.
This is probably the hardest thing you need to learn about generics, because it goes
against our deeply held intuitions.
So we had list of String not subtype of list of Objects.


The problem with that intuition is that it assumes that collections don’t change.
Our instinct takes these things to be immutable.
For example, if the department of motor vehicles supplies a list of drivers to the census
bureau, this seems reasonable. We think that a List<Driver> is a List<Person>,
assuming that Driver is a subtype of Person. In fact, what is being passed is a copy
of the registry of drivers. Otherwise, the census bureau could add new people who are
not drivers into the list, corrupting the DMV’s records.
In order to cope with this sort of situation, it’s useful to consider more flexible
generic types. The rules we’ve seen so far are quite restrictive.

Generic classes in java vs templates in C++

Here is a small excerpt from the definitions of the interfaces List and Iterator in package :
java.util:
public interface List<E> {
void add(E x);
Iterator<E> iterator();
}
public interface Iterator<E> {
E next();
boolean hasNext();
}

This should all be familiar, except for the stuff in angle brackets. Those are the
declarations of the formal type parameters of the interfaces List and Iterator.
Type parameters can be used throughout the generic declaration, pretty much where
you would use ordinary types (though there are some important restrictions.

In the introduction, we saw invocations of the generic type declaration List, such
as List<Integer>. In the invocation (usually called a parameterized type), all occurrences of the formal type parameter (E in this case) are replaced by the actual type argument (in this case, Integer).

You might imagine that List<Integer> stands for a version of List where E has been uniformly replaced by Integer:
public interface IntegerList {
void add(Integer x);
Iterator<Integer> iterator();
}

This intuition can be helpful, but it’s also misleading.
It is helpful, because the parameterized type List<Integer> does indeed have methods that look just like this expansion.
It is misleading, because the declaration of a generic is never actually expanded in this way. There aren’t multiple copies of the code: not in source, not in binary, not on disk and not in memory. If you are a C++ programmer, you’ll understand that this is very different than a C++ template.

A generic type declaration is compiled once and for all, and turned into a single class file, just like an ordinary class or interface declaration. Type parameters are analogous to the ordinary parameters used in methods or constructors. Much like a method has formal value parameters that describe the kinds of values it operates on, a generic declaration has formal type parameters. When a method is invoked, actual arguments are substituted for the formal parameters, and the method body is evaluated.
When a generic declaration is invoked, the actual type arguments are substituted for the formal type parameters.

The Motivation for Generics : dealing with casting of objects

Consider the following code:
List myIntList = new LinkedList(); // line no. 1
myIntList.add(new Integer(0)); // line no. 2
Integer x = (Integer) myIntList.iterator().next(); //line no. 3

The cast on line 3 is slightly annoying. Typically, the programmer knows what kind of data has been placed into a particular list. However, the cast is essential. The compiler can only guarantee that an Object will be returned by the iterator.
To ensure the assignment to a variable of type Integer is type safe, the cast is required.
Of course, the cast not only introduces clutter, it also introduces the possibility of a run time error, since the programmer might be mistaken.


Removing the cast
What if programmers could actually express their intent, and mark a list as being restricted to contain a particular data type?
This is the core idea behind generics.
Here is a version of the program fragment given above using generics:

List<Integer> myIntList = new LinkedList<Integer>(); // 1’
//OR
List<Integer> myIntList = new LinkedList(); // 1’

myIntList.add(new Integer(0)); //2’
Integer x = myIntList.iterator().next(); // 3’

Now, you might think that all we’ve accomplished is to move the clutter around.

Instead of a cast to Integer on line 3, we have Integer as a type parameter on line 1’. However, there is a very big difference here. The compiler can now check the type correctness of the program at compile-time. When we say that myIntList is declared with type List<Integer>, this tells us something about the variable myIntList, which holds true wherever and whenever it is used, and the compiler will guarantee it. In contrast, the cast tells us something the programmer thinks is true at a single point in the code.

The net effect, especially in large programs, is improved readability and robustness.

A big big note on Generics
Generics provides a sort of a syntactic sugar that might spare you some casting operation. But behind the scenes, after compilation the byte code is same. See Type Erasure with Generics to see how.

Enum and their super-class

All java enum E implicitly extends java.lang.Enum. Since java doesn't allow multiple inheritance, enum types can't have superclass. They can't even extend from java.lang.Enum, nor java.lang.Object. It also means enum A can't inherit or extend enum B.

For example, the following is an invalid enum declaration:
public enum MyType extends Object {
ONE, TWO
}
Compiler error:
MyType.java:3: '{' expected
public enum MyType extends Object {
MyType.java:6: expected
2 errors
 
The correct form should be:
public enum MyType {
ONE, TWO
}

Enum that implements interfaces

Enum can implement any interfaces. All enum types implicitly implements java.io.Serializable, and java.lang.Comparable.
public enum Color implements Runnable {
WHITE, BLACK, RED, YELLOW, BLUE;

public void run() {
System.out.println("name()=" + name() +
", toString()=" + toString());
}
}
A sample test program to invoke this run() method:
for(Color c : Color.values()) {
c.run();
}
Or,
for(Runnable r : Color.values()) {
r.run();
}

Enum with additional fields and custom constructor

Enum constructors must be either private or package default, and protected or public access modifier is not allowed. When custom constructor is declared, all elements declaration must match that constructor.
public enum Color { //Color is of type enum
 WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);
private int code;

private Color(int c) {
code = c;
}

public int getCode() {
return code;
}

Switch statement on enums

public enum Shape { RECTANGLE, CIRCLE, LINE }

The switch statement was enhanced to allow a convenient use of enums. Note that the case values don't have to be qualified with the enum class name, which can be determined from the switch control value.
switch (drawing) {
case RECTANGLE: g.drawRect(x, y, width, height);
break;
case CIRCLE : g.drawOval(x, y, width, height);
break;
case LINE : g.drawLine(x, y, x + width, y + height);
break;
}

Tuesday 26 October 2010

Bitwise Operators Summary

  • Integers (int and long) can be considered as collections of 32 or 64 bits.
  • Bitwise operators perform logical operations on each bit position, where 1 is regarded as true and zero false.
  • Bitwise and (a & b) - Result is 1 in every bit position where both operands have a 1.
  • Bitwise or (a | b) - Result is 1 only in positions where one or both operands have a 1.
  • Bitwise xor (a ^ b)- Result is 1 in positions where the two corresponding bits are different.
  • Bitwise not (~a) - Unary operator. Result is each bit of operand inverted.
  • Shift left (a << n) - Shifts bits n positions left. Zeros added on right.
  • Shift right (a >> n) - Shifts bits n positions right. High-order bit inserted on left.
  • Shift right (a >>> n) - Shifts bits n positions right. Zeros inserted at left.
  • Operator Precedence

    Precedence determines order of evaluation

    Mathematical tradition, which programming languages generally try to match, dictates that some operations are done before others (for example, multiplication and division are done before addition and subtraction).

    a+b*c is the same as a+(b*c), not (a+b)*c.

    Ever operator has a precedence (a number) associated with it. The precedence determines which operations will be performed first. Multiplication has higher precedence than addition, as illustrated in the previous example..

    Equal precedence operations generally performed left-to-right

    In addition to the precedence of each operator, the compiler also knows whether equal-precedence operators should be performed left-to-right (almost all) or right-to-left (basically only assignment).

    Parentheses can be used to control the order of evaluation

    If you have any doubt about the order of evaluation, or have a potentially confusing expression, use parentheses. Remember that one of your goals should be to make your programs as readable as possible. Use parentheses when it makes an expression easier to read, not must when they are absolutely required. Few programmers know the precedence of all operators, so it's common for extra parentheses to be used.

    Unary (one operand) versus binary (two operand) operators

    Unary operators have only one operand, for example, in

       a = -b;

    The "-" operator is the unary (one operand) operator which changes the sign of its operand.

       a = b - c

    The "-" operator is a binary (two operand) operator which subtracts c from b.

    Most unary operators are performed before binary operators (exceptions "." (qualification), "[]" (subscription), and "()" (method call).

    Example - Parentheses


    When you can work out the precedence, it's often useful to use parentheses to figure out the order of evaluation. For example, let's say you're evaluating the following expression.

     1 + 2 - 3 * 4 / 5

    Addition and subtraction are equal in precedence and lower than multiplication and division, which are equal. Form the parenthesized form and work out the values in steps.


    1. 1 + 2 - 3 * 4 / 5
    2. = (1 + 2) - ((3 * 4) / 5)
    3. = 3 - (12/5)
    4. = 3 - 2 The result of the integer division, 12/5, is 2 .
    5. = 1

    Precedence table


    This table gives the precedence of all operators. You may not be familiar with all operators, but take the advice on the right side and only learn a few precedences.

    Operator Precedence

    . [] (args) post ++ --
    ! ~ unary + - pre ++ --
    (type) new
    * / %
    + -
    << >> >>>
    < <= > >= instanceof
    == !=
    &
    ^
    |
    &&
    ||
    ?:
    = += -= etc

    Remember only

    1. unary operators
    2. * / %
    3. + -
    4. comparisons
    5. && ||
    6. = assignments
    Use () for all others

    Alternative notation - Dataflow diagram


    Let's look at the expression x = a+b-c*d/e, which can be parenthesized as x = ((a+b) - ((c*d)/e)). Instead of parentheses, we can draw a diagram.

    dataflow-tree
    This dataflow diagram shows another way to think about expression evaluation.

    Boxes represent values in memory, ovals represent operations, and arrows show the direction of data flow. The assignment operator ("=") is treated as an operator with low precedence by the compiler, but from a dataflow point of view it only moves data so it's represented as an arrow, not an operation.

    Dataflow diagrams show which operations must necessarily be performed before others, but doesn't show which are actually performed first. Java performs most operations left-to-right, so the addition would, in principle, be performed before the multiplication. I believe reordering of operations that can have no side effects is allowed, however.

    Alternative notation - Postfix - RPN


    Postfix. Altho it's not directly relevant to learning Java, there are other systems for writing expressions that don't need parentheses or precedence. Normal mathematical notation is called infix notation because the operators occur in between the operands. A common alternative is called postfix notation where the operator is written after its two operands.

    Example. For example, a+b would be written as ab+ , and x = a+b-c*d/e would be written as xab+cd*e/-=.

    RPN. This is often called Reverse Polish Notation in honor of the Polish mathematician Jan Lukasiewicz.

    Postfix notation is used in the following, among others.


    • Hewlett-Packard makes RPN calculators.
    • The Postscript printer control language is postfix.
    • The Forth programming language is RPN.
    • Java source code is translated into postfix notation!

    Saturday 23 October 2010

    Design Hints for Inheritance

    We want to end this chapter with some hints that we have found useful when using inheritance.
    1. Place common operations and fields in the superclass.
      This is why we put the name field into the Person class rather than replicating it in the Employee and Student classes.
    2. Don't use protected fields.
      Some programmers think it is a good idea to define most instance fields as protected, "just in case," so that subclasses can access these fields if they need to. However, the protected mechanism doesn't give much protection, for two reasons. First, the set of subclasses is unbounded—anyone can form a subclass of your classes and then write code that directly accesses protected instance fields, thereby breaking encapsulation. And second, in the Java programming language, all classes in the same package have access to protected fields, whether or not they are subclasses.
      However, protected methods can be useful to indicate methods that are not ready for general use and should be redefined in subclasses. The clone method is a good example.
    3. Use inheritance to model the "is–a" relationship.
      Inheritance is a handy code-saver, and sometimes people overuse it. For example, suppose we need a Contractor class. Contractors have names and hire dates, but they do not have salaries. Instead, they are paid by the hour, and they do not stay around long enough to get a raise. There is the temptation to form a subclass Contractor from Employee and add an hourlyWage field.
      class Contractor extends Employee
      { . . .
      private double hourlyWage;
      }

      This is not a good idea, however, because now each contractor object has both a salary and hourly wage field. It will cause you no end of grief when you implement methods for printing paychecks or tax forms. You will end up writing more code than you would have by not inheriting in the first place.
      The contractor/employee relationship fails the "is–a" test. A contractor is not a special case of an employee.
    4. Don't use inheritance unless all inherited methods make sense.
      Suppose we want to write a Holiday class. Surely every holiday is a day, and days can be expressed as instances of the GregorianCalendar class, so we can use inheritance.
      class Holiday extends GregorianCalendar { . . . }

      Unfortunately, the set of holidays is not closed under the inherited operations. One of the public methods of GregorianCalendar is add. And add can turn holidays into nonholidays:
      Holiday christmas;
      christmas.add(Calendar.DAY_OF_MONTH, 12);

      Therefore, inheritance is not appropriate in this example.
    5. Don't change the expected behavior when you override a method.
      The substitution principle applies not just to syntax but, more important, to behavior. When you override a method, you should not unreasonably change its behavior. The compiler can't help you—it cannot check whether your redefinitions make sense. For example, you can "fix" the issue of the add method in the Holiday class by redefining add, perhaps to do nothing, or to throw an exception, or to move on to the next holiday.
      However, such a fix violates the substitution principle. The sequence of statements
      int d1 = x.get(Calendar.DAY_OF_MONTH);
      x.add(Calendar.DAY_OF_MONTH, 1);
      int d2 = x.get(Calendar.DAY_OF_MONTH);
      System.out.println(d2 - d1);

      should have the expected behavior, no matter whether x is of type GregorianCalendar or Holiday.
      Of course, therein lies the rub. Reasonable and unreasonable people can argue at length what the expected behavior is. For example, some authors argue that the substitution principle requires Manager.equals to ignore the bonus field because Employee.equals ignores it. These discussions are always pointless if they occur in a vacuum. Ultimately, what matters is that you do not circumvent the intent of the original design when you override methods in subclasses.
    6. Use polymorphism, not type information.
      Whenever you find code of the form

      if (x is of type 1)
         action1(x);
      else if (x is of type 2)
         action2(x);
      think polymorphism.
      Do action1 and action2 represent a common concept? If so, make the concept a method of a common superclass or interface of both types. Then, you can simply call
      x.action();

      and have the dynamic dispatch mechanism inherent in polymorphism launch the correct action.
      Code using polymorphic methods or interface implementations is much easier to maintain and extend than code that uses multiple type tests.
    7. Don't overuse reflection.
      The reflection mechanism lets you write programs with amazing generality, by detecting fields and methods at run time. This capability can be extremely useful for systems programming, but it is usually not appropriate in applications. Reflection is fragile—the compiler cannot help you find programming errors. Any errors are found at run time and result in exceptions.

    Thursday 21 October 2010

    Swap in java

    Setting Program Attributes in java

    Java programs run within an environment that contains system attributes: a host machine, a user, a current directory, and an operating system. A Java program also can set up its own configurable attributes, called program attributes. Program attributes allow the user to configure various startup options, preferred window size, and so on for the program. Sometimes the term preferences is used instead of program attributes.
    System attributes are maintained by the System class and are covered later in System Properties. Java programs can set their own set of program attributes through three mechanisms: properties, command-line arguments, and applet parameters.

    Setting Up and Using Properties

    A property defines attributes on a persistent basis. That is, you use properties when attribute values need to persist between invocations of a program. This section shows you how to do this in your programs.

    Command-Line Arguments

    A command-line argument defines attributes for Java applications on a nonpersistent basis. You use command-line arguments to set one or more attributes for a single invocation of an application. This section shows how to accept and process command-line arguments in a Java program.

    Applet Parameters

    An applet parameter is similar to a command-line argument, except that it is used with applets, not applications. Use applet parameters to set one or more attributes for a single invocation of an applet.

    Using Properties to Manage Program Attributes

    An attribute has two parts: a name and a value. For example, "os.name" is the name for one of the Java platform's system attributes; its value contains the name of the current operating system, such as "Solaris".
    The Properties class in the java.util package manages a set of key/value pairs. A key/value pair is like a dictionary entry: The key is the word, and the value is the definition. This is a perfect match for managing the names and values of attributes. Each Properties key contains the name of a system attribute, and its corresponding Properties value is the current value of that attribute.
    The System class uses a Properties object for managing system properties. Any Java program can use a Properties object to manage its program attributes. The Properties class itself provides methods for the following:
    • Loading key/value pairs into a Properties object from a stream
    • Retrieving a value from its key
    • Listing the keys and their values
    • Enumerating over the keys
    • Saving the properties to a stream
    Properties extends the HashtableProperties class and inherits methods from it for doing the following:
    • Testing to see if a particular key or value is in the Properties object
    • Getting the current number of key/value pairs
    • Removing a key and its value
    • Adding a key/value pair to the Properties list
    • Enumerating over the values or the keys
    • Retrieving a value by its key
    • Finding out if the Properties object is empty

    The Life Cycle of a Program's Properties

    There are 3 phases in program's properties life cycle :
    • Starting up - where properties are loaded
    • Running - where properties are get and set
    • Exiting - saving the properties
    Now dealing with these phases one by one.


    Starting Up
    The actions given in the first three boxes occur when the program is starting up. First, the program loads the default properties from a well-known location into a Properties object. Normally, the default properties are stored in a file on disk along with the .class and other resource files for the program. Next, the program creates another Properties object and loads the properties that were saved from the last time the program was run. Many applications store properties on a per-user basis, so the properties loaded in this step are usually in a specific file in a particular directory maintained by this application in the user's home directory. Finally, the program uses the default and remembered properties to initialize itself. The key here is consistency. The application must always load and save properties to the same location so that it can find them the next time it's executed.

    Running


    During the execution of the program, the user may change some settings, perhaps in a Preferences window, and the Properties object is updated to reflect these changes. For them to have a permanent effect, they must be saved.

    Exiting
    Upon exiting, the program saves the properties to its well-known location, to be loaded again when the program is next started up.

    Setting Up Your Properties Object

    The following Java code performs the first two steps described in the previous section: loading the default properties and loading the remembered properties:
    . . .
    // create and load default properties
    Properties defaultProps = new Properties();
    FileInputStream in = new FileInputStream("defaultProperties");
    defaultProps.load(in);
    in.close();

    // create program properties with default
    Properties applicationProps = new Properties(defaultProps);

    // now load properties from last invocation
    in = new FileInputStream("appProperties");
    applicationProps.load(in);
    in.close();
    . . .
    First, the application sets up a default Properties object. This object contains the set of properties to use if values are not explicitly set elsewhere. Then the load method reads the default values from a file on disk named defaultProperties. Next, the application uses a different constructor to create a second Properties object, applicationProps, whose default values are contained in defaultProps. The defaults come into play when a property is being retrieved. If the property can't be found in applicationProps, then its default list is searched.

    Finally, the code loads a set of properties into applicationProps from a file named appProperties. The properties in this file are those that were saved from the program the last time it was invoked (the next section shows you how this was done).

    Saving Properties

    The following example writes out the application properties from the previous example using Properties's save method. The default properties don't need to be saved each time because they never change.
    FileOutputStream out = new FileOutputStream("appProperties");
    applicationProps.save(out, "---No Comment---");
    out.close();
    The save method needs a stream to write to, as well as a string that it uses as a comment at the top of the output.

    Getting Property Information

    Once you've set up your Properties object, you can query it for information about various keys/values that it contains. An application gets information from a Properties object after start up so that it can initialize itself based on choices made by the user. The Properties class has several methods for getting property information:
    • contains(Object value)
      containsKey(Object key)

      Returns true if the value or the key is in the Properties object. Properties inherits these methods from Hashtable. Thus they accept Object arguments. 
    • You should pass in Strings to get property.
      getProperty(String key)
      getProperty(String key, String default)

      Returns the value for the specified property. The second version allows you to provide a default value. If the key is not found, the default is returned.
    •  list(PrintStream s)
      list(PrintWriter w)

      Writes all of the properties to the specified stream or writer. This is useful for debugging.
    • elements()
      keys()
      propertyNames()

      Returns an Enumeration containing the keys or values (as indicated by the method name) contained in the Properties object.
    • size()
      Returns the current number of key/value pairs.
    • Setting Properties
      A user's interaction with a program during its execution may impact property settings. These changes should be reflected in the Properties object so that they are saved when the program exits (and calls the save method). You can use the following methods to change the properties in a Properties object:
      put(Object key, Object value)

      Puts the key/value pair in the Properties object.
    • remove(Object key)
      Removes the key/value pair associated with key.
      Both put and remove come from Hashtable and thus take Objects. You should pass in Strings.

    Tuesday 19 October 2010

    Stack in java using link list

    The three methods that stands out for a stack are pop(), push() and peek().
    push() - push elements into a stack. We will use the insertAtFirst() method of LinkedList. Throws StackOverflowException when the stack is full.
    pop() - remove and returns the top element from a stack. We will use the removeAtFirst() method of LinkedList. Throws StackEmptyException when the stack is empty.
    peek() - return the top element from the stack without removing it. We will use the getFirst() method of LinkedList. Throws StackEmptyException when the stack is empty.

    The java code for this looks very simpler. We will make use of the existing SinglyLinkedList class that we have used before.

    package dsa.stack;

    import dsa.linkedlist.SinglyLinkedList;

    public class Stack<E> extends SinglyLinkedList<E>{

    public static final int MAX_STACK_SIZE = 100;

    public E pop() throws StackEmptyException{
    if(this.size()==0){
    throw new StackEmptyException();
    }
    return this.removeAtFirst();
    }

    public E peek() throws StackEmptyException{
    if(this.size()==0){
    throw new StackEmptyException();
    }
    return this.getFirst().data;
    }

    public void push(E data) throws StackOverflowException{
    if(this.size()>MAX_STACK_SIZE){
    throw new StackOverflowException();
    }
    this.insertAtFirst(data);
    }

    public static void main(String args[]){
    Stack<Integer> stack = new Stack<Integer>();
    try{
    System.out.println("Pushing 1, 2, 3, 4, 5");
    stack.push(1);
    stack.push(2);
    stack.push(3);
    stack.push(4);
    stack.push(5);
    System.out.println("Pop once : "+stack.pop());
    System.out.println("Peek once : "+stack.peek());
    System.out.println("Pop once : "+stack.pop());
    System.out.println("Pop once : "+stack.pop());
    System.out.println("Pop once : "+stack.pop());
    System.out.println("Pop once : "+stack.pop());
    System.out.println("Pop once : "+stack.pop());
    }catch(StackEmptyException e){
    System.out.println(e.getMessage());
    }catch(StackOverflowException e){
    System.out.println(e.getMessage());
    }
    }
    }
    /*
    SAMPLE OUTPUT:
    Pushing 1, 2, 3, 4, 5
    Pop once : 5
    Peek once : 4
    Pop once : 4
    Pop once : 3
    Pop once : 2
    Pop once : 1
    Stack is empty!
    */

    package dsa.stack;

    public class StackEmptyException extends Exception{
    public StackEmptyException(){
    super("Stack is empty!");
    }
    }
    package dsa.stack;

    public class StackOverflowException extends Exception{
    public StackOverflowException(){
    super("Stack Overflown");
    }
    }

    Parsing Strings with split

    parsing
    dividing a string into tokens based on the given delimiters
    token
    one piece of information, a "word"
    delimiter
    one (or more) characters used to separate tokens
    When we have a situation where strings contain multiple pieces of information (for example, when reading in data from a file on a line-by-line basis), then we will need to parse (i.e., divide up) the string to extract the individual pieces.

    When there is just one character used as a delimiter

    Example 1

    We want to divide up a phrase into words where spaces are used to separate words. For example
    the music made   it   hard      to        concentrate
    In this case, we have just one delimiter (space) and consecutive delimiters (i.e., several spaces in a row) should be treated as one delimiter. To parse this string in Java, we do
    String phrase = "the music made   it   hard      to        concentrate";
    String delims = "[ ]+";
    String[] tokens = phrase.split(delims);
    Note that
    • the general form for specifying the delimiters that we will use is "[delim_characters]+" . (This form is a kind of regular expression. You don't need to know about regular expressions - just use the template shown here.) The plus sign (+) is used to indicate that consecutive delimiters should be treated as one.
    • the split method returns an array containing the tokens (as strings).  To see what the tokens are, just use a for loop:
      for (int i = 0; i < tokens.length; i++)
      System.out.println(tokens[i]);
      You should find that there are seven tokens: the, music, made, it, hard, to, concentrate

    Example 2

    Suppose each string contains an employee's last name, first name, employee ID#, and the number of hours worked for each day of the week, separated by commas. So
    Smith,Katie,3014,,8.25,6.5,,,10.75,8.5
    represents an employee named Katie Smith, whose ID was 3014, and who worked 8.25 hours on Monday, 6.5 hours on Tuesday, 10.75 hours on Friday, and 8.5 hours on Saturday. In this case, we have just one delimiter (comma) and consecutive delimiters (i.e., more than one comma in a row) should not be treated as one.  To parse this string, we do
    String employee = "Smith,Katie,3014,,8.25,6.5,,,10.75,8.5";
    String delims = "[,]";
    String[] tokens = employee.split(delims);
    After this code executes, the tokens array will contain ten strings (note the empty strings): "Smith", "Katie", "3014", "", "8.25", "6.5", "", "", "10.75", "8.5"
    There is one small wrinkle to be aware of (regardless of how consecutive delimiters are handled): if the string starts with one (or more) delimiters, then the first token will be the empty string ("").

    When there are several characters being used as delimiters

    Example 3

    Suppose we have a string containing several English sentences that uses only commas, periods, question marks, and exclamation points as punctuation.  We wish to extract the individual words in the string (excluding the punctuation).  In this situation we have several delimiters (the punctuation marks as well as spaces) and we want to treat consecutive delimiters as one
    String str = "This is a sentence.  This is a question, right?  Yes!  It is.";
    String delims = "[ .,?!]+";
    String[] tokens = str.split(delims);
    All we had to do was list all the delimiter characters inside the square brackets ( [ ] ).

    Example 4

    Suppose we are representing arithmetic expressions using strings and wish to parse out the operands (that is, use the arithmetic operators as delimiters).  The arithmetic operators that we will allow are addition (+), subtraction (-), multiplication (*), division (/), and exponentiation (^) and we will not allow parentheses (to make it a little simpler).  This situation is not as straight-forward as it might seem.  There are several characters that have a special meaning when they appear inside [ ].  The characters are ^  -  [  and two &s in a row(&&). In order to use one of these characters, we need to put \\ in front of the character:
    String expr = "2*x^3 - 4/5*y + z^2";
    String delims = "[+\\-*/\\^ ]+"; // so the delimiters are: + - * / ^ space
    String[] tokens = expr.split(delims);

    General template for using split

    String s = string_to_parse;
    String delims = "[delimiters]+"; // use + to treat consecutive delims as one;
    // omit to treat consecutive delims separately
    String[] tokens = s.split(delims);

    java.util.StringTokenizer

    The java.util.StringTokenizer class is used to break strings into tokens (words, numbers, operators, or whatever).
    Has been replaced by regular expression tools. A more powerful solution is to use regular expressions, and the easiest way to do that is use the java.util.Scaner class, the String split(..) method, or the Pattern and Matcher classes.
    A StringTokenizer constructor takes a string to break into tokens and returns a StringTokenizer object for that string. Each time its nextToken() method is called, it returns the next token in that string. If you don't specify the delimiters (separator characters), blanks are the default.

    Constructors

    StringTokenizer st = new StringTokenizer(s);
    Creates a StringTokenizer for the String s that uses whitespace (blanks, tabs, newlines, returns, form feeds) as delimiters.
    StringTokenizer st = new StringTokenizer(s, d);
    Creates a StringTokenizer for the String s using delimiters from the String d.
    StringTokenizer st = new StringTokenizer(s, d, f);
    Creates a StringTokenizer for the String s using delimiters from the String d. If the boolean f is true, each delimiter character will also be returned as a token.

    Common Methods

    Assume that st is a StringTokenizer.
    • st.hasMoreTokens() -- Returns true if there are more tokens.
    • st.nextToken() -- Returns the next token as a String.
    • st.countTokens() -- Returns the int number of tokens. This can be used to allocate an array before starting, altho it can be inefficient for long strings because it has to scan the string once just to get this number. Using a Vector and converting it to an array at the end may be a better choice. 

    Example: Find the longest word in a String

    This code finds the longest word (characters separated by delimiter characters) in the String s, using blanks, commas, and tabs as delimiters.
    // Assume s contains a string of words
    String longestWord = "";
    StringTokenizer st = new StringTokenizer(s, " ,\t");
    while (st.hasMoreTokens()) {
    String w = st.nextToken();
    if (w.length() > longestWord.length()) {
    longestWord = w;
    }
    }

    Method overriding in java

    Method hiding in java
    public abstract class BaseClass {

     
    public void insert(Object object) {
     
    // Do something
     
    }
    }
     
    public class SampleClass extends BaseClass {

     
    public void insert(Object object, Long param){
     
    // Do Something
     
    }
    }
    SampleClass sampleClass = new SampleClass();
    sampleClass
    .insert(Object object);
    sampleClass
    .insert(Object object, Long param);
    SampleClass sampleClass = new SampleClass();
    sampleClass
    .insert(Object object, Long param);
     
    here is no way of hiding the method. You can do this:

    @Override
    public void insert(Object ob) {
     
    throw new UnsupportedOperationException("not supported");
    }

    but that's it.
    The base class creates a contract. All subclasses are bound by that contract. Think about it this way:
    BaseObject b = new SomeObjectWithoutInsert();
    b
    .insert(...);
    How is that code meant to know that it doesn't have an insert(Object) method? It can't.
    Your problem sounds like a design problem. Either the classes in question shouldn't be inheriting from the base class in question or that base class shouldn't have that method. Perhaps you can take insert() out of that class, move it to a subclass and have classes that need insert(Object) extend it and those that need insert(Object, Object) extend a different subclass of the base object.

    here is no way of hiding the method. You can do this:
    @Override
    public void insert(Object ob) {
     
    throw new UnsupportedOperationException("not supported");
    }
    but that's it.
    The base class creates a contract. All subclasses are bound by that contract. Think about it this way:
    BaseObject b = new SomeObjectWithoutInsert();
    b
    .insert(...);
    How is that code meant to know that it doesn't have an insert(Object) method? It can't.
    Your problem sounds like a design problem. Either the classes in question shouldn't be inheriting from the base class in question or that base class shouldn't have that method. Perhaps you can take insert() out of that class, move it to a subclass and have classes that need insert(Object) extend it and those that need insert(Object, Object) extend a different subclass of the base object.



    Static Methods
    Can I override a static method? Many people have heard that you can't override a static method. This is true - you can't. However it is possible to write code like this:
    class Foo {
        public static void method() {
            System.out.println("in Foo");
        }
    }

    class Bar extends Foo {
        public static void method() {
            System.out.println("in Bar");
        }
    }
    This compiles and runs just fine. Isn't it an example of a static method overriding another static method? The answer is no - it's an example of a static method hiding another static method. If you try to override a static method, the compiler doesn't actually stop you - it just doesn't do what you think it does.
    So what's the difference?
    Briefly, when you override a method, you still get the benefits of run-time polymorphism, and when you hide, you don't. So what does that mean? Take a look at this code:
    class Foo {
        public static void classMethod() {
            System.out.println("classMethod() in Foo");
        }

        public void instanceMethod() {
            System.out.println("instanceMethod() in Foo");
        }
    }

    class Bar extends Foo {
        public static void classMethod() {
            System.out.println("classMethod() in Bar");
        }

        public void instanceMethod() {
            System.out.println("instanceMethod() in Bar");
        }
    }

    class Test {
        public static void main(String[] args) {
            Foo f = new Bar();
            f.instanceMethod();
            f.classMethod();
        }
    }
    If you run this, the output is
    instanceMethod() in Bar
    classMethod() in Foo
    Why do we get instanceMethod from Bar, but classMethod() from Foo? Aren't we using the same instance f to access both of these? Yes we are - but since one is overriding and the other is hiding, we see different behavior. Since instanceMethod() is an instance method, in which Bar overrides the method from Foo, at run time the JVM uses the actual class of the instance f to determine which method to run. Although f was declared as a Foo, the actual instance we created was a new Bar(). So at runtime, the JVM finds that f is a Bar instance, and so it calls instanceMethod() in Bar rather than the one in Foo. That's how Java normally works for instance methods.
    With classMethod() though. since it's a class method, the compiler and JVM don't expect to need an actual instance to invoke the method. And even if you provide one (which we did: the instance referred to by f) the JVM will never look at it. The compiler will only look at the declared type of the reference, and use that declared type to determine, at compile time, which method to call. Since f is declared as type Foo, the compiler looks at f.classMethod() and decides it means Foo.classMethod. It doesn't matter that the instance reffered to by f is actually a Bar - for static methods, the compiler only uses the declared type of the reference. That's what we mean when we say a static method does not have run-time polymorphism.
    Because instance methods and class methods have this important difference in behavior, we use different terms - "overriding" for instance methods and "hiding" for class methods - to distinguish between the two cases. And when we say you can't override a static method, what that means is that even if you write code that looks like it's overriding a static method (like the first Foo and Bar at the top of this page) - it won't behave like an overridden method.
    So what about accessing a static method using an instance?
    It's possible in Java to write something like:
    f.classMethod();
    where f is an instance of some class, and classMethod() is a class method (i.e. a static method) of that class. This is legal, but it's a bad idea because it creates confusion. The actual instance f is not really important here. Only the declared type of f matters. That is, what class is f declared to be? Since classMethod() is static, the class of f (as determined by the compiler at compile time) is all we need.
    Rather than writing:
    f.classMethod();
    It would be better coding style to write either:
    Foo.classMethod();
    or
    Bar.classMethod(); 
    That way, it is crystal clear which class method you would like to call. It is also clear that the method you are calling is indeed a class method. o;'oi;'i Barring that, you could always come up with this monstrosity:
    f.getClass().getMethod("classMethod", new Class[]).invoke(null, new Object[]);
    But all this could be avoided by simply not trying to override your static (class) methods. :-)
    Why does the compiler sometimes talk about overriding static methods?
    Sometimes you will see error messages from the compiler that talk about overriding static methods. Apparently, whoever writes these particular messages has not read the Java Language Specification and does not know the difference between overriding and hiding. So they use incorrect and misleading terminology. Just ignore it. The Java Language Specification is very clear about the difference between overriding and hiding, even if the compiler messages are not. Just pretend that the compiler said "hide" rather than "override"..
     


     
    Java exceptions and function overriding.
       

    Method overriding in java

    Method overriding in java

    Monday 18 October 2010

    Immutable objects

    An immutable object is an object which state is guaranteed to stay identical over its entire lifetime. While it is perfectly possible to implement immutability without final, its use makes that purpose explicit, to the human (the software developer) and the machine (the compiler).
    Immutable objects carry some very desirable characteristics:
    • they are simple to understand and easy to use
    • they are inherently thread-safe: they require no synchronization
    • they make great building blocks for other objects
    Clearly final is going to help us define immutable objects. First in labelling our object as immutable, which makes it simple to use and understand by other programmers. Second in guaranteeing that the object's state never changes, which enable the thread-safe property: thread concurrency issues are relevant when one thread can change data while another thread is reading the same data. Because an immutable object never changes its data, synchronizing access to it is not needed. Create an immutable class by meeting all of the following conditions:
    1. Declare all fields private final.
    2. Set all fields in the constructor.
    3. Don't provide any methods that modify the state of the object; provide only getter methods (no setters).
    4. Declare the class final, so that no methods may be overridden.
    5. Ensure exclusive access to any mutable components, e.g. by returning copies.

    Sunday 17 October 2010

    Arrays tip : Ignoring the zeroth row

    This trick can be used in any language but is shown in java right now.
    Sometimes you want to use natural input values as an index, the real values that that data has instead of starting with zero. Let's take the case of data that starts with the value 1, like the day of the month. The standard approach is to subtract one from every day value that's used as an index. This is annoying and error prone. Another way to do handle this case is to declare the array with an extra element, eg, 32 if dealing with the days in the month, then ignoring the zeroth element. If you're dealing with a two dimensional array, for example the accidents array from the previous page, you can even deallocate the first row so there won't be any possibility of referencing the zeroth day. For example,
    static final int DAYS  = 32;
    static final int HOURS = 24;
    . . .
    int[][] accidents = new int[DAYS][HOURS];
    accidents[0] = null;
    Because two-dimensional arrays are stored by row, you can do this. You can use the trick of allocating more columns to use the natural data, but you can't deallocate a column.
    Enhanced by Zemanta

    Tuesday 12 October 2010

    Arrays in C#

    public static void Main()
        {
            int[]    arr = {5110331004};
            
            Array.Sort(arr);
            foreach (int v in arr)
            Console.WriteLine("Element: {0}", v);


    //Making random array
    DateTime now = DateTime.Now;
                 Random rand = new Random ((intnow.Millisecond);

                 int [] Arr = new int [12];
                 for (int x = 0; x < Arr.Length; ++x)
                 {
                     Arr [x= rand.Next () 101;
                 }


    //initialising 2 D array
    int[,sqrs = 
          1}
          2}
          3}
          416 }
          525 }
          636 }
          749 }
          864 }
          981 }
          10100 
        }


    //jagged array
        int[][] jagged = new int[3][];  
        jagged[0new int[4];  
        jagged[1new int[3];  
        jagged[2new int[5];  
      
        int i; 
     
        // store values in first array 
        for(i=0; i < 4; i++)   
          jagged[0][i= i;  
     
        }

    Sunday 10 October 2010

    Java Vs C# : Arrays

    Java has two ways in which one can declare an array, one which is backwards compatible with the notation used in C & C++ and another which is generally accepted as being clearer to read, C# uses only the latter array declaration syntax.

    Saturday 9 October 2010

    Java Vs C#

    Arrays Can Be Jagged
    In languages like C and C++, each subarray of a multidimensional array must have
    the same dimensions. In Java and C# arrays do not have to be uniform because jagged
    arrays can be created as one-dimensional arrays of arrays. In a jagged array the
    contents of the array are arrays which may hold instances of a type or references to
    other arrays. For this reason the rows and columns in a jagged array need not have
    uniform length as can be seen from the following code snippet:
    int [][]myArray = new int[2][];
    myArray[0] = new int[3];
    myArray[1] = new int[9];

    No Global Methods

    Interfaces, Yes. Multiple Inheritance, No


    String
    C# has a System.String class which is analogous to the java.lang.String class. Both
    classes are immutable meaning that the values of the strings cannot be changed once
    the strings have been created. In both instances methods that appear to modify the
    actual content of a string actually create a new string to return, leaving the original
    string unchanged. Thus the following C# and Java code does not modify the string in
    either case
    C# Code
    String csString = "Apple Jack";
    csString.ToLower(); /* Does not modify string, instead returns
    lower case copy of string */
    Java Code
    String jString = "Grapes";
    jString.toLowerCase(); /* Does not modify string, instead returns
    lower case copy of string */
    To create a string-like object that allows modification in C# it is advisable to use the
    System.Text.StringBuilder class whereas in Java one would use the
    java.lang.StringBuffer class.
    NOTE: In C#, the string class can either be written as string or String.

    Unextensable classes
    Both Java and C# provide mechanisms to specify that a class should be the last one in
    an inheritance hierarchy and cannot be used as a base class. In Java this is done by
    preceding the class declaration with the final keyword while in C# this is done by
    preceding the class declaration with the sealed keyword. Below are examples of
    classes that cannot be extended in either language
    eg.
    C#
    sealed class X{}

    Java
    final class X{}


    Exceptions in C# and Java share a lot of similarities. Both languages support the use
    of the try block for indicating guarded regions, the catch block for handling thrown
    exceptions and the finally block for releasing resources before leaving the method.
    Both languages have an inheritance hierarchy where all exceptions are derived from a
    single Exception class. Exceptions can be caught and rethrown after some error
    handling occurs in both languages. Finally, both languages provide a mechanism for
    wrapping exceptions in one another for cases where a different exception is rethrown
    from the one that was caught. An example of using the exception wrapping capability
    is a three tier application where a SQLException is thrown during database access but
    is caught, examined, then an application specific exception is thrown. In this scenario
    the application specific exception can be initialized with the original SQLException
    so handlers of the application specific exception can access the original exception
    thrown if needed. Below are two equivalent code samples that show the similarities
    between exceptions in both languages.
    NOTE: Although exceptions in both languages support methods for getting a stack
    trace, only Java exceptions have methods that allow one to alter the stack trace.