Search code examples
javaintegerconcatenationtostringjava-6

Tips in String concatenation in Java 1.6 with multiple integers


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;
    }

Solution

  • 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