aarav
aarav

Reputation: 230

Java String best practices

I have 4 String parameter's in Java (from request object)

String dd = req.getParameter(dd);
String mm = req.getParameter(mm);
String yyyy = req.getParameter(yyyy);

after validating dd,mm,yyyy I am building date object in 4th String variable by buildingString date = dd+"/"+mm+"/"+yyyy; again in some places i need to replace the date format as following,

date = yyyy+mm+dd;
date =mm+"/"+dd+"/"+yyyy;  // storing in db need this format

How much memory would consume since 4 objects need to pass till persist in table? Was it costlier memory call? Is there any best practice? At last howmany string objects would be in Stringpool?

Upvotes: 1

Views: 556

Answers (1)

TheCodingFrog
TheCodingFrog

Reputation: 3514

My suggestion is that you should not be worry about micro improvement as other also suggested. May be create a wrapper object e.g. MyDate and construct Date object once. After that you can use different formatter to format your date.

package com.dd;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.joda.time.LocalDate;

public class MyDate {

    private Date date;

    public MyDate(Request req) {
        int day = req.getParameter("dd");
        int month = req.getParameter("mm");
        int year = req.getParameter("yyyy");
        date = new LocalDate(year, month, day).toDate();
    }

    public String format(String givenFormat) {
        SimpleDateFormat sdf = new SimpleDateFormat(givenFormat);
        return sdf.format(date);
    }

}

Note - You need to confirm and validate what values you're getting from your request and if they are in same notation as expected by LocalDate

Upvotes: 4

Related Questions