This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
Integer.parseInt converts string to int. Is the reverse also true? Would String.parseString convert an int to a string? Would Long.parseLong convert a # or a string to a long? Would this example work with all of the primitive types?
Originally posted by Theresa Duick: Integer.parseInt converts string to int. Is the reverse also true? Would String.parseString convert an int to a string? Would Long.parseLong convert a # or a string to a long? Would this example work with all of the primitive types?
This will take an integer and turn it into a String. It is no longer a primitive type, it is now an object and must be treated as such. I have never tried it, but I guess this would work for any primitive type. int x = 543; String y = new Integer(x).toString(); System.out.println(y);
There's a static method that will do this a little quicker, without needing to instantiate an Integer just to use a method: <code><pre> int x = 543; String y = Integer.toString(x);</pre></code> Note that this is not the standard toString() inherited from Object - it's an overloaded version. There are similar methods in all the wrapper classes I believe.
"I'm not back." - Bill Harding, Twister
Joined: Feb 16, 2000
Thanks, Jim! The problem is finding the similar methods. I'm just beginning to learn how to do the necessary research.
Joined: Jan 30, 2000
The wrapper classes are Byte, Short, Character, Integer, Long, Float, Double, Boolean, and Void (sorta). Most (not all) of these have a static method toString(someArgument) - you can check in the API to find out which.
To convert a number to a String, use String.valueOf( ) methods. There're 9 overloads of the them. Eg. int var01 = 9; String strVar01 = String.valueOf(var01); This will result in strVar01 to be set to the string "9".
Originally posted by Theresa Duick: Thanks, Jim! The problem is finding the similar methods. I'm just beginning to learn how to do the necessary research.
The Java API docs should be towards the top of your list when you research how to do something in Java. Learning to navigate them is a necessary skill, imho. In this case, you can scroll the upper-left frame down until you find the java.lang package. When the lower-left frame finishes loading, scroll down to the Integer, Double, Short, etc. class and click on it. The documentation for the class you chose appears in the main frame on the right.
The link I gave above is specifically for J2SDK 1.4.2. If you are using a different version, visit here to find the appropriate documentation. [ November 09, 2004: Message edited by: Layne Lund ]