Monday, 18 October 2010

String comparisons using ==, equals () or compartTo()

Using ==
To compare Strings for equality, don't use ==. The == operator checks to see if two objects are exactly the same object. Two strings may be different objects, but have the same value (have exactly the same characters in them).
Using equals()
Use the .equals() method to compare strings for equality. Similarly, use the .compareTo() method to test for unequal comparisons. For example,
String s1 = "True";
String s2 = "True";
s1 == s2 == true //compiler uses one instance for string literals , so works fine as 2 strings are
same taken from string pool.
String s3 = new String("False");
String s4 = new String("False");
s3 == s4 == false //two forced instances
String s5 = "True";
String s6 = "Tr" + "ue";
s5 == s6 == true //compiler evaluates and uses same instance
String s7 = "False";
String sx = "F";
String s8 = sx + "alse";
s7 == s8 == false //compiler won't evaluate where a second reference is involved
These values are all "equal". But == will return true or false based on _how_ the values were set.
Stick to .equals(), and enjoy the remaining features of autoboxing.
compareTo() and comparison operators
if (s > t)    // ILLEGAL
if (s.compareTo(t) > 0) // CORRECT>
I guess I don't find it inconsistent, or at least not as inconsistent as the alternative would be. In each case the result is true or false based on whether the reference is pointing to the same object instance or not. When dealing with objects, == does not compare values. Doing so _would_ be inconsistent.

Autoboxing in java


Autoboxing, introduced in Java 5, is the automatic conversion the Java compiler makes between the primitive (basic) types and their corresponding object wrapper classes (eg, int and Integer, double and Double, etc). The underlying code that is generated is the same, but autoboxing provides a sugar coating that avoids the tedious and hard-to-read casting typically required by Java Collections, which can not be used with primitive types.

In the previous section on wrapper classess for primitive type values, we discussed how to create an instance of a wrapper from a primitive and conversely, how to obtain the primitive value held by the wrapper. This involves a a certain amount of clumsy code.
For example, creating a Float object from a float primitive is straightforward:
  float primitive_float = 3.0f;
  Float wrapper_float = new Float (primitive_float);
Going the other direction, however, requires explicitly calling the floatValue() method on the Float object:
  float primitive_float = wrapper_float.floatValue ();
If you are dealing with a lot of instances of wrappers and conversions, you will thus need to deal with a lot of method invocations.
In J2SE 5.0, however, the code to create the wrapper object allows for this much simpler form:
  Float wrapper_float = primitive_float;
Here, the "wrapping" is done automatically! There is no need to explicitly call the Float constructor. This "wrapping" is called "autoboxing" in the sense that the primitive value is automatically "boxed up" into the wrapper object. Autoboxing is available for all the primitive/wrapper types.
Going the other way, from object type to primitive, is just as simple:
  Integer wrapper_integer = 5; // primitive 5 autoboxed into an Integer
  int primitive_int = wrapper_integer; // automatic unboxing Integer into int


Now we can have this.
int i;
Integer j;
i = 1;
j = 2;
i = j;
j = i;
Earlier we had to do this.
int i;
Integer j;
i = 1;
j = new Integer(2);
i = j.intValue();
j = new Integer(i);
This is quite clumsy.

Also see - Some issues with Autoboxing

Common string function in java

String com = str1.concat(str2);

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.