Java int to string

There are 3 different ways to achieve this(Int to Java convertor) in Java.

  • String string = Integer.toString(i);

This is a normal way of converting int to String object

  • String string = String.valueOf(i);

This is almost similar to the first one except that that It will take input ( ‘I’ here) of any data type

  • String string = “” + i;

This is not highly preferable since concatenation takes up more time when compared to the first two. During compilation the above code will be resulting into creating a new Stringbuilder object and appending the empty string and “I” in two steps and at the end it is again converted back to String Object . So this takes more time compared to other .

If you want own code then the following

public static String Mystringconverter(int number)

{

   int StringConvert = 48;

   int numb = number;

   int numbaftdiv = number;

   String myString = "";

   while(numbaftdiv >0)

   {

       numb = numbaftdiv % 10;

       numbaftdiv = numbaftdiv / 10;

       if(numb == 0)

       {

           myString += "0";

       }

       else if(numb == 1)

       {

           myString += "1";

       }

       else if(numb == 2)

       {

           myString += "2";

       }

       else if(numb == 3)

       {

           myString += "3";

       }

       else if(numb == 4)

       {

           myString += "4";

       }

       else if(numb == 5)

       {

           myString += "5";

       }

       else if(numb == 6)

       {

           myString += "6";

       }

       else if(numb == 7)

       {

           myString += "7";

       }

       else if(numb == 8)

       {

           myString += "8";

       }

       else if(numb == 9)

       {

           myString += "9";

       }

   }

   String myString 2= "";

   for(int i = myString.length() -1 ; index >= 0 ; index--)

   {

       myString 2+= myString.charAt(i);

   }

   return myString2;

}

 

 

Leave A Comment

Your email address will not be published. Required fields are marked *