Java

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;
}
}
Now let say you make an object of class Circle and print it.
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.

 

Circle@15db9742

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().

 

toString() method

java.lang.Object- Alpha class or super class for all the class that exist in Java have a method with following signature.
 
public String toString()
 
By default java.lang.Object is designed to return the following
 

NameofClass@Hexcode(hashCode) 

 
Hence the output,
 
Circle@15db9742
 
Then why is it printing it differently for String and Integer?
 
Simple!! They have overridden the toString() method.
 

 

Let say I want the output of Circle object when printed as "Radius=radiusValue", I will have to override the toString() method.
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

 

 

 

 

Related Posts

language_img
Java

Implicit Objects

Aug 10, 2016

Table Of Contents

;