Let's dive into the topic
Strings
- A string is a class
- It is from a package called Java.lang
- String is immutable
- The object is implicitly Created
Let's see some examples:
//creating objects for string
String s = new String();
System.out.println(s);
output:
//empty
In the above example, the output will be empty. But if we print an object of another class, some hashcode will be printed. For a String
, Why is it not printing anything? Let's see about that.
Let's see some internal work.
Whenever an object is printed, Java internally calls the toString
method which returns a string format.
//toString code
public class Object{
public String toString(){
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
}
This is the internal code for the toString
method. We can also override this method. The Object
class is the parent class of every class. We can override the Object
class methods unless they have the final
or static
keyword.
Let's get to the point.
In the String
class, the toString
method is written as:
// This object (already a string!) is returned.
public String toString() {
return this;
}
It just returns the string itself. Now, since the string is empty, it prints the empty string.
Overriding the toString
method
public class Test {
@Override
public String toString(){
return "Espresso";
}
public static void main(String[] args) {
Test a = new Test();
System.out.println(a);
}
}
output:
Espresso
We have overridden the toString
method to print espresso
every time we call toString
.
equals()
It checks whether the two objects are the same. But if we think logically, two objects can't be the same.
Here's an analogy: Imagine there are two phones from the same brand and model. Their properties may be the same, but that doesn't mean they are the same. They are two different physical objects. Likewise, we can't compare the two objects because the two objects are different and it is stored in separate memory locations. But we can compare their properties, and also we override the equals()
method.
However, for the String
class, the equals()
method is overridden to compare the character sequences of the strings, rather than the object reference. This means that two different String
objects with the same character sequence will be considered equal when compared using the equals()
method.
So, this is it.
I hope it is useful.
Thank You!!!
Top comments (0)