Make sure to subscribe to our newsletter and be the first to know the news.
Make sure to subscribe to our newsletter and be the first to know the news.
Have you ever tried to print an object using System.out.println() ?
Most probably you must have tried printing a String or an Integer value which prints its value.
For example, let say for the following code
String s="Tom";System.out.println(s);
It will print "Tom".
or
int i=10;System.out.println(i);
will print 10.
But what will it print in following scenario.
Let say there is a class Circle with a int variable of radius.
class Circle
{
int radius;
Circle(int radius)
{
this.radius=radius;
}
}
Circle c= new Circle(10);
System.out.println(c);
What should I expect to get printed now? Radius of the Circle or any other thing.
When you run this code, it will print the following.
Why this? What is that number after @ sign and why that name of class.
When any object is printed under System.out.println(), it prints its response of toString().
class Circle
{
int radius;
Circle(int radius)
{
this.radius=radius;
}
public String toString()
{
String x="Radius="+radius;
return x;
}
}
Now when you print the object of class Circle, output will be different.
Circle c=new Circle(24);
System.out.pritnln(c);
Output: Radius=24