1

I got an example to override the toString() method.

import java.util.Scanner; 

public class Demo{ 

    String name = "";
    String age = "";

    Demo(String name, String age){
            this.name = name;
            this.age = age;
        }


    public static void main(String[] args) {  
        Scanner scanner = new Scanner(System.in);  

        System.out.print("Enter the name:");  
        String name = scanner.next();  
        System.out.print("Enter the age:");  
        String age = scanner.next();  

        Demo test = new Demo(name, age);  
        System.out.println(test);  

    }  

    public String toString() {  
        return ("Name=>" + name + " and " + "Age=>" + age);  
    }  
}  

My doubt is, how is it printing test as Name=>abc and Age=>12 even when toString() method is not being called neither from constructor nor from main?

bhantol
  • 9,368
  • 7
  • 44
  • 81
Leo
  • 5,017
  • 6
  • 32
  • 55
  • 1
    add `@Override` annotation - I don't know if this will help, but it is good to have it ;) – rzysia Dec 18 '14 at 11:20

4 Answers4

9

You're calling System.out.println(test), which is a call to PrintStream.println(Object). That will call toString() on the reference you pass in, via String.valueOf:

Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

Your toString() method is actually being called by the println method. By the way when you override a method I suggest you use the @Override notation above it, that way the compiler will check that you are actually overriding an existing method and it also keeps it clear for yourself and others when you read back through it. e.g.

@Override
public void methodToBeOverriden () {}
Sam Redway
  • 7,605
  • 2
  • 27
  • 41
1

You have called System.out.println(test); and the effect of it is like you are calling

System.out.println(test.toString());

Eugene
  • 10,627
  • 5
  • 49
  • 67
0

When you call System.out.println(test) it calls the toString() method, using the object you passed in. As you have overridden this method, it is calling your toString() method hence the expected output - Name=>abc and Age=>12

James Fox
  • 691
  • 7
  • 24