String.valueOf(int i)  /   Integer.toString()

What's the difference between these methods? They seem to both do the same thing... convert an int into a string

No, they don't
static String valueOf(int i)
          Returns the string representation of the int argument.
String toString()
          Returns a String object representing this Integer's value. Perhaps you intended to compare the String.valueOf to this?
static String toString(int i)
          Returns a String object representing the specified integer. If so, then yes, they do the same thing.

Similar Messages

  • String to Int and Int to String

    How can I convert a string to Int & and an Int to String ?
    Say I've
    String abc="234"
    and I want the "int" value of "abc", how do I do it ?
    Pl. help.

    String.valueOf(int) takes an int and returns a string.
    Integer.parseInt(str) takes a string, returns an int.
    For all the others long, double, hex etc. RTFM :)

  • Integer static valueOf(int) question

    Hi there.
    Im wondering is it at all possible for an Integer reference variable to be returned
    a null by invoking this method from the API:
    Integer myInt = Integer.valueOf(//some int);The reason I am asking this question is that my SCJP book asks a question
    about using a method that is similar to the following:
    class BankAccount {
    private Map<String, Integer> accountFunds = new HashMap<String, Integer>();
    public int customerBalance(String custAccount) {
       return accountFunds.get(custAccount);
    public void setCustomerBalance(String custAccount, int balance) {
       accountFunds.put(custAccount, Integer.valueOf(balance));
    }Looking at the single return statement in the customerBalance method, my book states that this is inappropriate
    because a null cant unbox to 0 I disagree because if you look at the setCustomerBalance method you are putting an Integer
    instance that is initialized with an int primitive into the Map. So how could it be possible to have
    a null Integer instance in the map if you pass an int primitive to the valueOf method? I can understand
    if you were using a String to instantiate the Integer, and you passed null, that you would get a NumberFormatException or something like that, but about you are using a primitive, not an Object.
    Any clarification greatly received,
    Thanks & best regards.

    I disagree because if you look at the setCustomerBalance method you are putting an Integer
    instance that is initialized with an int primitive into the Map.And what happens if you call customerBalance() (which should really be named getCustomerBalance()) with a customer ID that doesn't exist?

  • Exact Difference and Usage between .toString / String.valueOf() / (String)

    Hi
    What are the differences in .toString / String.valueOf() / (String) ?
    I have tried the following :
    String a = "a";
             Object o = "o";
             int i = 1;
             System.out.println("String Value of " + String.valueOf(i));
             System.out.println("(String) " + (String)o);
             System.out.println(".toString() " + i.toString()); // does not work
             System.out.println(".toString() " + String(i)); // does not workThanks in Advance !!

    x.toString() calls the object's toString() method. It cannot be used for primitives, and it will give NullPointerException if x is null.
    String.valueOf(x) will call the object's toString() method if x is a non-null reference. If x is a null reference, it will return the string "null". If x is a primitive, it will return a String representation of that primitive, probably by calling toString on an appropriate wrapper object, or a static String.valueOf method on the appropriate wrapper class. You can look at the source code in src.zip if you're curious.
    Both toString() and String.valueOf are just methods. There's nothing special about them. You can look at their docs and/or source code to see what they do.
    (String)x will attempt to cast the reference x to a String. I doesn't change the object in any way. If x is not a reference to one of String's supertypes--Object, Comparable, etc.--then it will be a compile-time error. If x is a reference to one of String's supertypes, but points to an object at runtime that is not a String, it will be a ClassCastException.
    This is just casting, an there's nothing special about casting with Strings vs. any other class.
    Edited by: jverd on Apr 27, 2010 4:07 PM

  • [svn] 2142: swfutils: Somehow a Java 1.5 API (Integer.valueOf(int)) slipped into the 30x branch, and has only sporadically caused build problems.

    Revision: 2142
    Author: [email protected]
    Date: 2008-06-18 15:17:01 -0700 (Wed, 18 Jun 2008)
    Log Message:
    swfutils: Somehow a Java 1.5 API (Integer.valueOf(int)) slipped into the 30x branch, and has only sporadically caused build problems.
    * By "somehow" I mean it was my injection :)
    * Apparently this compiles in 1.4.2 on a Mac, go figure? I assume Windows JDK doesn't accept it.
    * Replaced it with 'new Integer(int)'
    Reviewer: Matt, community folks
    Bugs: n/a
    QA: no
    Doc: no
    Modified Paths:
    flex/sdk/branches/3.0.x/modules/swfutils/src/java/flash/swf/tools/SwfxPrinter.java

    Revision: 2142
    Author: [email protected]
    Date: 2008-06-18 15:17:01 -0700 (Wed, 18 Jun 2008)
    Log Message:
    swfutils: Somehow a Java 1.5 API (Integer.valueOf(int)) slipped into the 30x branch, and has only sporadically caused build problems.
    * By "somehow" I mean it was my injection :)
    * Apparently this compiles in 1.4.2 on a Mac, go figure? I assume Windows JDK doesn't accept it.
    * Replaced it with 'new Integer(int)'
    Reviewer: Matt, community folks
    Bugs: n/a
    QA: no
    Doc: no
    Modified Paths:
    flex/sdk/branches/3.0.x/modules/swfutils/src/java/flash/swf/tools/SwfxPrinter.java

  • Convert from String to Int

    Hi,
    I have a question.
    How do I convert from String to Integer?
    Here is my code:
    try{
    String s="000111010101001101101010";
    int q=Integer.parseInt(s);
    answerStr = String.valueOf(q);
    catch (NumberFormatException e)
    answerStr="Error";
    but, everytime when i run the code, i always get the ERROR.
    is the value that i got, cannot be converted to int?
    i've done the same thing in c, and its working fine.
    thanks..

    6kyAngel wrote:
    actually it convert the string value into decimal value.In fact what it does is convert the (binary) string into an integer value. It's the String representation of integer quantities that have a base (two, ten, hex etc): the quantities themselves don't have a base.
    To take an integer quantity (in the form of an int) and convert it to a binary String, use the handy toString() method in the Integer class - like your other conversion, use the one that takes a radix argument.

  • Please help me with my code (has conversion from string to int)

    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    public class Test3 extends MIDlet implements CommandListener
    {   Form mForm;
        Command mCommandQuit;
        Command mCommandItem;
        TextField input,prime1,prime2,prime3,output;
        Display mDisplay;
        int i,j=0,k1,k2,p,q,b;
        //int [] current=new int [1000];
        String mstring,a="";
        String [] temp=new String [1000];
        public void startApp()
        {System.out.println("startApp");
         mForm=new Form("RSA Encryption");
         mCommandQuit=new Command("QUIT",Command.EXIT,0);
         mCommandItem=new Command("ENCRYPT",Command.ITEM,0);
         mForm.append("Enter text:\n");
         input=new TextField(null,"",100, TextField.ANY);
         mForm.append(input);
         mForm.append("Enter first prime number(p):\n");
         prime1=new TextField(null,"",100, TextField.ANY);
         mForm.append(prime1);
         mForm.append("Enter second prime number(q):\n");
         prime2=new TextField(null,"",100, TextField.ANY);
         mForm.append(prime2);
         mForm.append("Enter d:\n");
         prime3=new TextField(null,"",100, TextField.ANY);
         mForm.append(prime3);
         mForm.addCommand(mCommandQuit);
         mForm.addCommand(mCommandItem);
         mDisplay=Display.getDisplay(this);
         mDisplay.setCurrent(mForm);
         mForm.setCommandListener(this);
        public void pauseApp()
        {System.out.println("pauseApp");
        public void destroyApp(boolean unconditional)
        {System.out.println("destroyApp");
        public void commandAction(Command c, Displayable d)
        {System.out.println("commandAction");
         if(c==mCommandQuit)
            notifyDestroyed();
         else if(c==mCommandItem)
         {p = Integer.parseInt(prime1.getString());
             q = Integer.parseInt(prime2.getString());
             b = Integer.parseInt(prime3.getString());
             //breaking up of big string into ints
             mstring=input.getString();
             temp[0]="";
             for(i=1;i<mstring.length();i++)
                {if (mstring.charAt(i) == ' ')
                    {j++;
                     temp[j]="";
                 else
                    {temp[j]=temp[j]+mstring.charAt(i);
             mForm.append("\n\nThe array is:\n");
             for(i=0;i<temp.length && temp!=null;i++)
    {k1=Integer.parseInt(temp[i]); ***********************
    k2=k1;
    for(j=1;j<b;j++)
    {k1=k1*k2;
    k1=k1 %(p*q);
    k2=k1 %(p*q);
    a=a+new Character((char)k2).toString();
    output=new TextField(null,a,100, TextField.ANY);
    mForm.append(output);
    }hi
    this code basically takes an input of string like " 179 84 48 48 155 " (with spaces)
    then it creates smaller strings in an array like "179","84","48","48","155" without the spaces
    then it creates int values 179,84,48,48,155 and finally after some math functions it prints the corresponding letters.
    the problem is that it is not printing the letter because of some exceptions-->java.lang.NumberFormatException .it comes in the line where i have put stars
    could anybody please help me print the letters                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    thanks for all ur help guys, but me and my team member solved it on our own. here is the new code:
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    public class Test3 extends MIDlet implements CommandListener
    {   Form mForm;
        Command mCommandQuit;
        Command mCommandItem;
        TextField input,prime1,prime2,prime3,output;
        Display mDisplay;
        int i,j=0,l,k1,k2,p,q,n,b;
        String mstring,a = "";
        String [] temp=new String [1000];
        public void startApp()
        {System.out.println("startApp");
         mForm=new Form("RSA Encryption");
         mCommandQuit=new Command("QUIT",Command.EXIT,0);
         mCommandItem=new Command("DECRYPT",Command.ITEM,0);
         mForm.append("Enter text:\n");
         input=new TextField(null,"",100, TextField.ANY);
         mForm.append(input);
         mForm.append("Enter first prime number(p):\n");
         prime1=new TextField(null,"",100, TextField.NUMERIC);
         mForm.append(prime1);
         mForm.append("Enter second prime number(q):\n");
         prime2=new TextField(null,"",100, TextField.NUMERIC);
         mForm.append(prime2);
         mForm.append("Enter d:\n");
         prime3=new TextField(null,"",100, TextField.NUMERIC);
         mForm.append(prime3);
         mForm.addCommand(mCommandQuit);
         mForm.addCommand(mCommandItem);
         mDisplay=Display.getDisplay(this);
         mDisplay.setCurrent(mForm);
         mForm.setCommandListener(this);
        public void pauseApp()
        {System.out.println("pauseApp");
        public void destroyApp(boolean unconditional)
        {System.out.println("destroyApp");
        public void commandAction(Command c, Displayable d)
        {System.out.println("commandAction");
         if(c==mCommandQuit)
            notifyDestroyed();
         else if(c==mCommandItem)
         {p = Integer.parseInt(prime1.getString());
             q = Integer.parseInt(prime2.getString());
             b = Integer.parseInt(prime3.getString());
             n=p*q;
             //breaking up of big string into ints
             mstring=input.getString();
             temp[0]="";
             for(i=1;i<mstring.length();i++)
                {if (mstring.charAt(i) == ' ')
                    {j++;
                     temp[j]="";
                 else
                    {temp[j]=temp[j]+mstring.charAt(i);
             l=j;
             mForm.append("\n\nThe result is:\n");
             for(i=0;i<l;i++)
                {k1=Integer.valueOf(temp).intValue();
    k2=k1;
    for(j=1;j<b;j++)
    {k2=k2*k1;
    k2=k2 %n;
    k1=k2 %n;
    a=a+new Character((char)k1).toString();
    output=new TextField(null,a,100, TextField.ANY);
    mForm.append(output);

  • Help with Integer.toString or casting

    I'm kinda new to this java stuff. I'm trying to pass information from stockReturnNumber to a string variable called stringHolder. This method is declared as a void. Is that part of the problem? What can i do to convert stockReturnNumber to a string?
    Thank you
    nick
    void enterSampleData()
    int stockElement = 0;
    int stockHigh = 1;
    int stockReturnNumber = 0;
    String stringHolder;
    while(stockElement < stockElementCounter)
    while(stockHigh<=181)
    stringHolder = Integer.toString(stockReturnNumber); // <-- program will not go beyond here
    stockNames[stockElement][stockHigh] = stringHolder;
    stockHigh++;
    stockReturnNumber++;
    stockElement++;
    }

    Here is some more information that i did not tell you about before.
    i'm using NetBeans IDE 3.6 for my debugger... When i run the program
    i have it run all the way and have it stop just before it tries to convert
    the string and have it step into the
    stringHolder = String.valueOf(stockReturnNumber);
    The error message has a caption in the box that says
    "Question"
    then the error message says..
    "Debugger has been stopped at
    java.lang.String.valueOf, line 2236.
    Source of class has not been found in mounted filesystems.
    select an action that will be performed upon stepping
    into a method without source:
    Stop
    Step out
    Stop at the first line with source
    I declared at the begining of the program
    #import java.lang.*;
    is there any thing else i have to do to make sure that the
    source class is available? I know that i'm successfuly
    declareing string variables cause i have been able to add
    strings into it from a file in a previous method.
    Thanks for helping me out with this. I really appreciate it.

  • Conversion from String to int..NumberFormatException??

    Hey all
    I am trying to read in a file that has nothing but numbers listed one per line. I am using the bufferedReader class and reading in by line. When I check to see if the one 'string' is the same as another, it says they are the same, when really they are different. I then thought to convert the numbers to integers after reading them in, but it gives me a number format exception. My process is simple:
    1) line = in.readLine();
    2) int variable = Integer.valueOf(line).intValue();
    This gives me the damn exception. The numbers are three digits, e.g. 333, etc. Does anybody know how I can avert this problem or achieve the result I am looking for another way? All I want is to know what numbers are listed in their, without going through by hand checking. Thanks

    hi...try this..
    1.Use filereader instead of bufferedreader..OKAY
    2. OR USE...
    String str = br.readLine();
    use... int sanjeev = Integer.parseInt(str);
    3 OR...and helloooo one thing more...how u r checking that these 2 strings r same..
    get CLEAR IDEA about equals method and "=="..

  • How to convert String to int in JSP?

    Hi,
    I set a session attribute in Servlet and want use it in JSP, How can I convert it to int or Integer?
    the line in my code doesn't work:
    int quantity=(int)session.getAttribute("vehiclequantity") ;
    Thanks in advance.
    Wolf
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    <HTML>
    <HEAD>
    <TITLE>Using the for Statement</TITLE>
    </HEAD>
    <BODY>
    <H1>Using the for Statement</H1>
    <%=session.getAttribute("vehiclequantity") %>;
    <%
    int loopIndex;
    int quantity=(int)session.getAttribute("vehiclequantity") ;
    out.println(quantity);
    for (loopIndex = 1; loopIndex <=2; loopIndex++) {
    out.println("This is iteration number "
    + loopIndex + "<BR>");
    %>
    </BODY>
    </HTML>

    Learning how to read errors and understand them will help you solve your problems quicker by yourself... So lets take a look at the error and classes involved...
    The error says:
    "Cannor Resolve Symbol: method valueOf(java.lang.Object) in the class java.lang.Integer" and gives you line line where the error occurs: Integer quantity = Integer.valueOf(session.getAttribute("vehiclequantity"));
    Now, if we look at the API for the Integer we notice that are are only two valueOf methods: valueOf(java.lang.String s) and valueOf(java.lang.String s, int radix). Not valueOf(java.lang.Object) method.
    Now we look at the getAttribute(java.lang.String name) method of HttpSession we see that the method returns a java.lang.Object. Now, you know you put a java.lang.String into that attribute, but the get method returns an Object. This is because you could have put any object in there, an Integer, a String, or some other class instance. But you know it is a String, so you can cast the returned value to a String, so that you will be calling the valueOf(java.lang.String s) method of Integer with the Object returned from the HtttpSession's getAttribute(java.lang.String name) method:
    Integer quantity = Integer.valueOf((String)session.getAttribute("vehiclequantity"));

  • How can i cast array of string to int ?

                       while(st.hasMoreTokens()){
                                  test[count] = st.nextToken();
                                  count++;
                          }Since token deal with string, i have to pass them into String of array, but how can i convert all of them to int to perform arithmetic operation?

         public static void main (String[] args) throws IOException{
               DataInputStream dis = null;
                 String dbRecord = null;
                 int tokenCount = 0;
                 int numOfQuestion = 0;
                 int questionnAireNum = 0;
                 int postCode = 0;
                 int age = 0;
                 int gender = 0;
                 String [] response = new String[10];
                    File f = new File("polldata.txt");
                    FileInputStream fis = new FileInputStream(f); 
                    BufferedInputStream bis = new BufferedInputStream(fis); 
                    dis = new DataInputStream(bis);
                    // read the first record of the database
                    while ( (dbRecord = dis.readLine()) != null) {
                       StringTokenizer st = new StringTokenizer(dbRecord, ",");
                       tokenCount = st.countTokens();
                       numOfQuestion = tokenCount-4;
                       String rquestionNum = st.nextToken();
                       questionnAireNum = Integer.parseInt(rquestionNum);
                       String rpostCode = st.nextToken();
                       postCode = Integer.parseInt(rpostCode);
                       String rAge  = st.nextToken();
                       age = Integer.parseInt(rAge);
                       String rGender = st.nextToken();
                       gender = Integer.parseInt(rGender);
                       for(int i=0; i<numOfQuestion;i++){
                            response[i] = st.nextToken();
                       }hi how come when i cast the string as int it prompt me error as shown below ? I wonder what causes this because this is normally how i cast string to int, somehow it won work this way with token.
    Exception in thread "main" java.lang.NumberFormatException: For input string: " 3"
         at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
         at java.lang.Integer.parseInt(Integer.java:447)
         at java.lang.Integer.valueOf(Integer.java:553)
         at test.main(test.java:43)

  • Number-chars in string to int?

    Are there any string method that converts number-chars within a string to integers?

    String line = "12345";
    int i = Integer.parseInt(line);
    the other way aroundint i = 12345;
    String line = String.valueOf(i);just a little remark.. :)

  • String into int & vice versa

    Hi all
    i cant convert the String into int although using
    Integer.parseInt & vice versa
    any ideas
    here is the code
    // fontCB & styleCB & sizeCB are ComboBoxes
    String fontName,fontStyle,fontSize;
    int fontStyleInt=1,fontSizeInt=1;
    fontName                = (String)fontCB.getSelectedItem();
    fontStyle               = (String)styleCB.getSelectedItem();
    fontSize               = (String)sizeCB.getSelectedItem();
    try
    fontStyleInt      = Integer.parseInt(fontStyle);
    fontSizeInt      = Integer.parseInt(fontSize);
    catch (NumberFormatException nfe)
    System.out.println("I'm an error");
    Font fontTemp           = new Font(fontName,fontStyleInt,fontSizeInt);
    myTextArea.setFont(fontTemp);

    The getSelectedItem() method returns a type called "Object". Therefore, to convert it to a string, u have to use String.valueOf(fontCB.getSelectedItem);Font styles are integers, i.e. PLAIN=0, BOLD=1, ITALIC=2, BOLD & ITALIC =3
    So, u can do the following,
    String styles={"Plain","Bold","Italics","Bold and Italics"};
    styleCB=new JComboBox(styles);To get the appropriate style, all u have to do is:
    int style=styleCB.getSelectedIndex();As for the font size,
    int size=Integer.parseInt(String.valueOf(sizeCB.getSelectedItem()));I think u r having plans for a text editor. right?

  • String to int conversion

    can n e body tell me how can i convert a String to an int

    always remember to use the try/catch block with thins that throw exceptions
    String gg;
    int in;
    try{  
    gg = "30";
       in = Integer.parseInt(gg);
    catch(NumberFormatException e){ 
      e.printStackTrace();
    }Ant

  • Conversion of String to Int

    Had some trouble with passing a string input via the command screen and changing it to an int. Im prob using the wrong code but im not sure if that is it.
    import javax.swing.JFrame;
    import java.util.Scanner;
    public class P524Driver
    public static void main ( String args[] )
         Scanner input = new Scanner(System.in);
         // Input the rows of the Diamond
         System.out.print ("Input the number of rows (Must be and oddnumber): ");
    int x = input.nextInt();
         String z;
         if (x > 0) //     Determine if the value entered was valid
         while ( x % 2 == 0 )
              System.out.print( "You Input a even number try again: ");
              x = input.nextInt();
              while ( x % 2 != 0)
              System.out.print( "Input the charater: ");
              z = input.next();
              int y = Integer.parseInt(z);
    {else{ System.exit(0);}
    }

    Ok I don't know if this is going to work with your input, but here goes. The way I declared user input was as so : BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); and the way I declared the integer value of the input was as so : int value = Integer.parseInt(console.readLine());Hope this helps!

Maybe you are looking for

  • Business Graphics and WebEnterprise

    I have a two part question. First, what is the best way to create business graphics such as line, bar, and point graphs? OLE to Excel, OCX, some third party commercial graphics library such as Brahma Software's Beacon? Second, once I have a business

  • Won't detect Logitech Bluetooth mX900 mouse unless moving it at startup

    When I start up my iMac, it does not automatically detect my Logitech MX 900 bluetooth mouse unless I am moving the mouse around at the right moment. If I am not moving the mouse, a screen pops up saying the computer has been unable to detect the mou

  • OVD Database Adapter w/ JDBC Thin Driver to 10G RAC DB Resource

    I'm looking for feedback as to whether anyone has successfully consumed a RAC database resource through an OVD database adapter? If so, I am interested in what your host value in the adapter ui looked like. I am successful with this connection only i

  • My "unlimited plan" just auto-renewed, but under what terms?

    First, the apparent good news via email from ATT: +Congratulations, your auto-renew of Unlimited data for 30 days for $29.99 was successful.+ +Your credit/debit card has been charged $29.99.+ But at the very end of the email: +The terms for the AT&T

  • IPhoto not retrieving photos

    I have iPhoto 11, and when I open the program, a message window saying "Alert the photo _____ (file name) could not be opened, because the original item cannot be found." How can I fix this?