Search code examples
javastringtostringobject-to-string

Convertion of user-defined object to string by toString not showing correct output


I have created a class CurrentDate which shows the system date in a particular format(e.g. 29-JUN-12). The class looks like :

package getset;

import java.util.*;
import getset.Getset;
public class CurrentDate{
    public static void main(String[] args){
        Calendar cal = new GregorianCalendar();
        int month = cal.get(Calendar.MONTH);
        int year = cal.get(Calendar.YEAR);
        int day = cal.get(Calendar.DAY_OF_MONTH);

        String toyear=String.valueOf(year);
        String newyear=toyear.substring(2,4);
        String newmonth=monthvalidation(month);
        System.out.println("Current date : " + day + "-" + (newmonth) + "-" + newyear);
    }

    private static String monthvalidation(int initmonth) {
        // TODO Auto-generated method stub
        //int initmonth=i;
        String finalmonth="";
        if(initmonth==1)
        {
            finalmonth="JAN";
        }
        if(initmonth==2)
        {
            finalmonth="FEB";
        }
        if(initmonth==3)
        {
            finalmonth="MAR";
        }
        if(initmonth==4)
        {
            finalmonth="APR";
        }
        if(initmonth==5)
        {
            finalmonth="MAY";
        }
        if(initmonth==6)
        {
            finalmonth="JUN";
        }
        if(initmonth==7)
        {
            finalmonth="JUL";
        }
        if(initmonth==8)
        {
            finalmonth="AUG";
        }
        if(initmonth==9)
        {
            finalmonth="SEP";
        }
        if(initmonth==10)
        {
            finalmonth="OCT";
        }
        if(initmonth==11)
        {
            finalmonth="NOV";
        }
        if(initmonth==12)
        {
            finalmonth="DEC";
        }    
        return finalmonth;
    }
}

Now when I try to convert it using toString() it does not show what is expected. I tried:

CurrentDate date=new CurrentDate();
String sysdate=date.toString();
System.out.println(""+sysdate);

It shows something like: getset.CurrentDate@18a178a which is not human readable expected format. What can I do to correct this?


Solution

  • You need to override the toString method.

    In your CurrentDate class, add somethnig like

    @Override
    public String toString() {
        String toyear=String.valueOf(year);
        String newyear=toyear.substring(2,4);
        String newmonth=monthvalidation(month);
        return day + "-" + newmonth + "-" + newyear;
    }