Java Glossary : conversion

CMP home Java glossary home Menu no menu Last updated 2004-06-28 by Roedy Green ©1996-2004 Canadian Mind Products

Java definitions: 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

You are here : home : Java Glossary : C words : conversion.

conversion
How do you convert Strings to ints, vice versa and the like? You can't always simply cast them. Java has a rather chaotic naming convention for the various routines to do the conversions. Look for candidate static and dynamic methods on both the source and target classes, and related wrapper classes like Integer. Likely conversion method names are valueOf, toString, parse???, ???Value, to???.I have composed a 20x20 matrix crib sheet for java 1.4 and earlier and also a version for Java 1.5 and later to tell you how to convert any of the 20 basic types into any of the others. It also shows you how to get left leading zeros. I have also written an amanuensis Applet in Java, available with source code, that will generate Java source code for any of the 400 possible conversions between the 20 basic types. You can then cut and paste the result into your code.

Mutable Primitives Immutable Objects
boolean Boolean
ordinary signed byte Byte
unsigned byte Byte
short Short
char Character
int Integer
long Long
float Float
double Double
char[] String

Converting Notes

If a long is converted to an int, or an int to a byte, the high order bits are simply truncated. This can result in surprising results including sign reversal.

Interconverting byte [] and String is tricky because there is always an implied encoding translation. "8859_1" encoding simply chops the high byte off or pads the high byte with 0s, what newbies erroneously imagine happens all the time.

String s = "abc";
// string -> byte[]
byte [] b = s.getBytes( "8859_1" /* encoding */ );
// byte[] -> String
String t = new String( b , "Cp1252" /* encoding */ );

Interconverting char[] and String is easier because there is no encoding involved.

String s = "abc" ;
// string -> char[]
char[] ca = s.toCharArray();
// char[] -> String
String s = new String( ca );

Hexadecimal

The radix feature of the toString and parseInt methods lets you handle hexadecimal numbers. Just set the radix to 16.

StringBuffers

Strings and StringBuffers can be interconverted.

StringBuffer q;
String s;
q = new StringBuffer(s);
s = new String(q);
s = q.toString();

Rounding

Rounding often surprises because fractions like 0.1 cannot be precisely be represented in IEEE floating point format. Often you find yourself having to add tiny numbers just prior to printing to get the desired effects.

// Rounding to an integer:
long n = Math.round(d);
double d = Math.rint(d);

// Rounding to two decimal places:
long n = Math.round(d *100.); /* keep as "pennies" */
double d = Math.rint (d *100.)/100.;

Left Zeros

The standard conversions give you no leading blanks or leading zeroes. Here is a code snippet to convert an integer to string padded with leading left zeroes. With an obvious modification it would give you lead blanks.

public static String toLZ( int i, int len )
   {
   // converts integer to left-zero padded string, len  chars long.
   String s = Integer.toString(i);
   if ( s.length() > len ) return s.substring(0,len);
   else if ( s.length() < len ) // pad on left with zeros
      return "000000000000000000000000000".substring(0, len - s.length ()) + s;
   else return s;
   } // end toLZ

Formatted Output

JDK 1.0.2 has no function like C's printf that lets you control how many positions and decimal places you want in your output. You have to roll your own.

JDK 1.1 has formatting picture classes such as java.util.DateFormat, SimpleDateFormat and DecimalFormat.

Formatting is such a common request, you might attain sainthood if you wrote a formatting class that gives you all the power of printf without the overhead of parsing strings for % produce a string. e.g.

public class Form
   {
   static String display (int value , int width , int decimalPlaces , int base , boolean leadZeroes);
   static String display (int value , int width , int decimalPlaces , int base);
   static String display (int value , int width , int decimalPlaces);
   static String display (int value , int width);
   static String display (int value);
   static String display (double value , int width , int decimalPlaces);
   static String display (double value , int width);
   static String display (double value);
   }

Reading Numeric Data From an ASCII file

Java has no built-in methods for reading data of the form: 123 456,-4.

You have to roll your own method. Use java.io.StreamTokenizer or java.util.StringTokenizer, perhaps in combination with readLine to get your data into strings. StreamTokenizer has bells and whistles to deal with parsing source code, including white space, comments and numbers. StringTokenizer just splits the text up based on delimiter characters. Then use the conversion methods in the table above to convert to integers etc. See below for a simplified examples of how you would do this.

StreamTokenizer Method Of Reading Integers From An ASCII File

// Read space or comma-delimited file of integers
// Convert from ASCII to internal binary

...
BufferedReader in = new BufferedReader(new FileReader("C:\\temp\\foo.in" ) );
StreamTokenizer st = new StreamTokenizer(in);
// process the entire file, of space or comma-delimited ints
int found = StreamTokenizer.TT_NUMBER;
while ( found != StreamTokenizer.TT_EOF )
   {
   found = st.nextToken ();
   if ( found == StreamTokenizer.TT_NUMBER )
      {
      int i = (int)st.nval;
      System.out.println(i);
      } // end if
   } // end while

StringTokenizer Method Of Reading Integers From An ASCII file

// Read space-delimited file of integers
// Convert from ASCII to internal binary

...
BufferedReader in =
new BufferedReader(new FileReader( "C:\\temp\\foo.in" ), 4096 /* buffsize */ );
String aLine = in.readLine();
StringTokenizer st = new StringTokenizer(aLine);
// process one line worth of space-delimited integers
while ( st.hasMoreTokens() )
   {
   String s = st.nextToken();
   int i = Integer.parseInt(s);
   System.out.println(i);
   } // end while

Binary is a compact, machine-friendly, human-unintelligible format. For human readable i/o, Java works with Strings of characters. You separately convert these to and from internal binary format e.g. int. See the conversion Amanuensis for how.


CMP logo
CMP_home
home
Canadian Mind Products CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[24.87.56.253]
Your IP:[80.134.30.163]
You are visitor number 6122.
Please send errors, omissions and suggestions
to improve this page to Roedy Green.
You can get a fresh copy of this page from: or possibly from your local J: drive mirror:
http://mindprod.com/jgloss/conversion.html J:\mindprod\jgloss\conversion.html