Search code examples
javaencapsulation

return the value in toString


How do i return this value into may main function? sorry i just started learning encapsulation in java.

public String toString() {
  System.out.format("%02d/", day);
  System.out.format("%02d/", month);
  System.out.format("%02d/", year);
  
  return toString;
}

Input: 1/1/1972

Output: toString cannot be resovled to a variable return toString;

Expected output: 01/01/1972


Solution

  • You are going to have to use the format() function that is defined in the String class.

    for example

    public String toString() {
     String date = String.format("%02d/", day);
     date += String.format("%02d/", month);
     date += String.format("%02d/", year);
    
    
     return date;
    }
    

    In your original function you were just outputting text to the console, and you did not define a variable to be returned.

    Hopefully this solves your issue.