In: Computer Science
Comparing Objects Vs Comparing Primitive data Types
Topic:
Discuss how do we compare Strings for equality? Provide coding examples. How String comparison is different than the primitive data type comparison? Please cite any resources you used.
Comparing Objects Vs Comparing Primitive data Types :
In java we can compare object by using equals() method . equals() method is available in object class. It will use for check the equality of two object. If two object will be store in same memory location then both object is equal.
Syntax:
Public boolean equals(Object ob);
In this syntax - public is a access modifier and boolean is a return type it means it return either true or false. And equals is a method name. And it takes object as a parameter and return true if object is equal otherwise return false.
Note: Object class is a parent class of all class so it can hold the reference of all class.
Primitive data types: in java we have to declare all variables to before use because java is statically types programming language. We can compare primitive variable by using == operators.
An example of == operator:
Int a=10;
Int b=a;
If(a==b)
{
System.out.println(“True”);// it return true
}
Else
{
System.out.println(“False”);
}
Output- True
How to compare String - we can compare two string by using equals() method as well as using == operator . we have to override equals() method in our program. equals() method compare content of any string and == operator compare address of the string.
Program for String comparison:
public class StringComparision {
public static void main(String[] args) {
String s1="abc";
String s2="xyz";
String s3="abc";
System.out.println(s1==s2);// it return false because
address of both string is different
System.out.println(s1.equals(s3));//it return true because content
of both string is same
}
}
Output:- false
true
Note: in string if we make object using new keyword then two object is created on in SCP(String constant pool) and second is in heap.
How String comparison is different than the primitive data type comparison:
If we compare primitive variable then it can be done simple by using == operators but if we want to compare Strings then we have to override equals() method in our program. So we can say string comparison is difficult then primitive variable comparison.