Tuesday 28 August 2012

Java Example Program



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.


No comments:

Post a Comment