Friday, April 4, 2008

STRING IN JAVA

Constructors

String class provides various types of constructors to create String objects. Some of them are,

String()

Creates a new String object whose content is empty i.e. “”.

String(String s)

Creates a new String object whose content is same as the String object passed as an argument.

Note: Constructor creates a new string means it does not intern the String. Interned String object reference can be obtained by using intern() method of the String class

String also provides constructors that take byte and char array as argument and returns String object.


String equality

String class overrides the equals() method of the Object class. It compares the content of the two string object and returns the boolean value accordingly.


For example,


String str1=”Hello”;

String str2=”Hello”;

String str3=new String(”Hello”) //Using constructor.

If(str1 == str2)

System.out.println(“Equal 1”);

Else

System.out.println(“Not Equal 1”);

If(str1 == str3)

System.out.println(“Equal 2”);

Else

System.out.println(“I am constructed using constructor, hence

not interned”);

If( str1.equals(str3) )

System.out.println(“Equal 3”);

Else

System.out.println(“Not Equal 3”);

The output would be,

Equal 1

Not Equal 2

Equal 3

Note that == compares the references not the actual contents of the String object; Where as equals method compares actual contents of two String objects.

String class also provides another method equalsIgnoreCase() which ignores the case of contents while comparing.

Apart from these methods String class also provides compareTo methods.

int compareTo(String str2)

This method compares two Strings and returns an int value. It returns value 0, if this string is equal to the string argument a value less than 0, if this string is less than the string argument

a value greater than 0, if this string is greater than the string argument

int compareTo(Object object)

This method behaves exactly like the first method if the argument object is actually a String object; otherwise, it throws a ClassCastException.


0 comments: