0

I have a class which has 3 int variables named: day, month and year. I also have a method called toString() that would take the three fields and return in the format "dd/mm/yyyy" (there is no need to put 0 if the day or month has only 1 number in it).

What is the best way to do this?

public String toString(){
        String dateString = this.day + "/" + this.month + "/" + this.year;
        return dateString;
    }

OR

public String toString(){
        String dateString = Integer.toString(this.day) + "/" + Integer.toString(this.month) + "/" + Integer.toString(this.year);
        return dateString;
    }
2
  • 4
    The first way looks a lot simpler. Commented May 9, 2018 at 6:01
  • 2
    And what about String.format("%d/%d/%d", day, month, year) ? You can even add leading zero in the format if you need. Commented May 9, 2018 at 6:05

3 Answers 3

6

As an alternative, I would use String.format to create that String

return String.format("%d/%d/%d", day, month, year)

You want to format your date with leading zero ? Easy with the formatter :

return String.format("%02d/%02d/%02d", day, month, year)

- 0 - use leading zero instead of spaces.
- 2d - Minimum two character to print (so "2" will use " 2")

You can find the complete documentation about the flags allowed in Formatter

A simple example :

String.format("%002d", 5);

005

And an example with the date,

String.format("%02d/%02d/%02d", 9, 5, 18);

09/05/18

Sign up to request clarification or add additional context in comments.

Comments

3

You may also write that in a single statement. There's no need to typecast Integer to String explicitly unless you're not sure that day, month and year are integers i.e. int, or you want to do an explicit exception handling.

@Override
public String toString() {
    return (this.day + "/" + this.month + "/" + this.year);
}

Comments

2

First one with out any doubt, in the second one you are converting Integer to String explicitly and then again concatenating in String while returning which does not make much sense.

3 Comments

you meant converting integers into string and then concatenate?
Yes. Concatenating converts them to string only.
It's not converting a String to Integer first. Integer.toString() converts an int to a String. However it's still unnecessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.