Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

I wrote the following code to convert a time in milliseconds to string in mins:seconds. My question is will this code work? If not what change will make it work?

public String time_to_string(long t) // time in milliseconds

{

    String ans;

    int mins,secs;

    if (t < 0)

    {

        return "-";

    }

    else

    {

        secs = (int)(t/1000);

        mins = secs/60;

        secs = secs - (mins * 60);

        ans = ""+mins+":"+String.format("%02d", secs);

        return ans;

    }

}

1 Answer

0 votes
by (13.1k points)

Your code works fine. There is no problem in returning the strings in this manner.

In Java, a String is a reference to an immutable object which is coupled with garbage collection and takes care of much of the potential complexity by itself without you worrying that string would disappear on you, or that someone somewhere would modify it.

You can make these changes to your code for stylistic reasons:

public String time_to_string(long t) // time in milliseconds

{

    if (t < 0)

    {

        return "-";

    }

    else

    {

        int secs = (int)(t/1000);

        int mins = secs/60;

        secs = secs - (mins * 60);

        return String.format("%d:%02d", mins, secs);

    }

}

As you can see, I have pushed the variable declarations as later as I could. I have also eliminated ans and have replaced it with the mix of string concatenation and String.format() with a single call to String.format().

Want to learn Java? Check out the Java certification from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Apr 13, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
asked Feb 12, 2021 in Java by Jake (7k points)
0 votes
1 answer

Browse Categories

...