Monday, 7 May 2012

Java String equals Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
String class equals method example

String class equals method example:- This method demonstrates the working of equals() method. 
it returns boolean values true and false after examining the two objects taken under checking process

Syntax:-equals(Object anObject) 


Here is the code:-

  /**
  * @(#) EqualsString.java
  * EqualsStringString class demonstrates the working of equals() method of String class of lang package
  */  




public class EqualsString {
  public static void main(String args[]) {

    Integer in = new Integer(12234);
    String str = new String("12234");
    
    // since both objects posses same value but the type of value is
    // different. Here there are two types of objects compared one is
    // Integer type and the other one is String type so the method returns
    // false as values types didnot match
    
    System.out.println( "value types don't matches: " + in.equals(str));
             

    // method returns true if and only if none of the Strings compared
    // posses null value and also must that there value matches each other
    // in sequence, cases and all aspects of equality including value types
    String str1 = new String("  hare krishna hare rama! rama rama hare hare");
    String str2 = str1.substring(0);
    String str3 = " ", str4 = " ";
    String str5 = "heram", str6 = "Heram";
    //Method returns true here as both Strings str1 and str2 posses same values
    System.out.println(" 'true' is returned:  " + str1.equals(str2));
    //Both the String mentioned above don't have any value but still Strings are equal as both are null type objects compared"             
    System.out.println("Method returns true here:  " + str3.equals(str4));
    //Method here returns false because values of Strings did not match when their respective letters case are concerned        
    System.out.println(" 'false' is returned:  " + str5.equals(str6));
            
  }
}
Output of the program:-
--------------------------------
value types don't matches: false

'true' is returned:  true

Method returns true here:  true

'false' is returned:  false

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...