[!INDEX]
- comparison
==vsequals- Points to Remember
- syntax for object, boolean mt ( equals for reference )
- syntax for class, boolean mt ( equals for object )
1. comparison == vs equals
public class M05 {
public static void main(String[] args) {
String s1 = new String("rajat");// in heap and SCP
String s2 = new String("rajat");// in heap area only
System.out.println(s1==s2);// false
System.out.println(s1.equals(s2));// true
// s1 refer to first rajat in heap
// s2 refer to second rajat
// == checkes the address, reference comparision
String s3="manoj"; // in SCP area
String s4="manoj"; // try to make but already present then
System.out.println(s3==s4);// true, coz both same location
System.out.println(s3.equals(s4));// true
// equalsto is the object class m/T, string overrides it
}
}
2. Points to Remember
[!NOTE]
==- reference/address comparison.
- means both objects point to the same memory location or not. 2.
equals- content comparison (in String class).
- means check object value.
equals (of object class )- compare the reference/address of two objects
- i.e if two objects point to the same memory location or not. 4.
equals (of string class )- equals method is override by string
- equal is the object class method ( total 11 method )
3. syntax for object, boolean mt ( equals for reference )
class Object {
public boolean equals (Objects obj) {
return (this==obj);
}
}
// the above is used for reference comparision
4. syntax for class, boolean mt ( equals for object )
class String extends Object {
public boolean equals (Objects obj)
{ // statements
}
}