Results 1 to 2 of 2
  1. #1
    Psyclone is offline Member
    Join Date
    Jan 2010
    Posts
    81
    Rep Power
    0

    Default Is it OK to do this... (converting int to string)

    Is it OK to do this...

    Java Code:
    int x = 7;
    String string = ""+x;
    I'm just using that as an example, in my code I'm using it like this...

    Java Code:
    activationCost.setText(""+masterArray[masterCardID].getCost())
    Cost is an integer in my code, but I need to display it as a string to get it to work in a JLabel. I know there's another way to convert String to int, but this seems like a shortcut to me. Will this create any problems/issues down the road?

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,655
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Psyclone View Post
    Is it OK to do this...

    Java Code:
    int x = 7;
    String string = ""+x;
    I'm just using that as an example, in my code I'm using it like this...

    Java Code:
    activationCost.setText(""+masterArray[masterCardID].getCost())
    Cost is an integer in my code, but I need to display it as a string to get it to work in a JLabel. I know there's another way to convert String to int, but this seems like a shortcut to me. Will this create any problems/issues down the road?
    There are no repercussions but it's not the most efficient way of converting an int to a String, i.e. the compiler helps you but it generates code like this:

    Java Code:
    // String String= ""+x;
    String string= new StringBuilder("").append(x).toString();
    The String class itself has better alternatives for it (although they are a bit longer source code wise speaking):

    Java Code:
    String string= String.valueOf(x);
    kind regards,

    Jos

Similar Threads

  1. Converting a String into a array.
    By taraxgoesxboom in forum New To Java
    Replies: 12
    Last Post: 02-22-2009, 05:29 AM
  2. NullPointerException converting String to double
    By infaddict in forum New To Java
    Replies: 3
    Last Post: 07-19-2008, 06:01 PM
  3. Converting object to string
    By Preethi in forum New To Java
    Replies: 4
    Last Post: 06-14-2008, 03:29 AM
  4. Converting String to Double
    By srini in forum New To Java
    Replies: 1
    Last Post: 12-24-2007, 08:03 PM
  5. Converting Epoch to string Date
    By amyedwards in forum New To Java
    Replies: 3
    Last Post: 12-14-2007, 10:33 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •