conversion : Java Glossary

go to home page C words local find full screen, hide local find menu Google search web for more information on this topic jump to foot of page translate this page with Babelfish by Roedy Green ©1996-2009 Canadian Mind Products
index page for letter ⇒ punctuation 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 (all)
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 also written the Conversion 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.

Conversion Amanuensis Rounding
Conversion Matrix for JDK 1.4- Left Zeros
Conversion Matrix for JDK 1.5+ Formatted Output
Primitives Reading Numeric Data
Basic Types StreamTokenizer
Truncation StringTokenizer
byte[] ⇔ String Binary
char[] ⇔ String Metric
Hexadecimal Links
StringBuffers & StringBuilders

Primitives

Primitive variables include boolean, char, byte, short, int, long, float and double. Strings, arrays and Objects are not considered primitives.
Java Primitives
Type Signed? Bits Bytes Digits Lowest Highest Mnemonic
boolean n/a 1 1 1 false true zero/one
char unsigned Unicode 16 2 4:5 '\u0000' [0] aka Character.MIN_VALUE '\uffff' [216-1] aka Character. MAX_VALUE Unicode chars are twice as big as C’s.
byte signed 8 1 2:3 -128 [-27] aka Byte. MIN_VALUE +127 [27-1]aka Byte. MAX_VALUE Bytes are signed, so half the usual 255 range.
short signed 16 2 4:5 -32,768 [-215] aka Short. MIN_VALUE +32,767 [215-1] aka Short. MAX_VALUE 32K
int signed 32 4 9:10 -2,147,483,648 [-231] aka Integer. MIN_VALUE +2,147,483,647 [231-1] aka Integer. MAX_VALUE 2 gig
long signed 64 : [-263] aka Long. MIN_VALUE [263-1] aka Long. MAX_VALUE exabytes, or billion gig
float signed exponent and mantissa : ±1.40129846432481707e-45 aka Float.MIN_VALUE ±3.40282346638528860e+38 aka Float.MAX_VALUE
or roughly ±2127
with to significant digits of accuracy.
A float can exactly represent integers
in the range -224 to +224.
rough, compact float
double signed exponent and mantissa : ±4.94065645841246544e-324 aka Double.MIN_VALUE ±1.79769313486231570e+308 aka Double.MAX_VALUE
or roughly ±21023
with to significant digits of accuracy.
A double can exactly represent integers
in the range -253 to +253.
high precision float

Primitives vs Immutable Wrapper Objects

Contrast that table of primitives, with this table of basic Java types:
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

Truncation

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.

byte[] ⇔ String

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( byteArray, "Cp1252" /* encoding */ );

// subset of byte[] -> String
String t = new String( byteArray, offset, length, "UTF-8" /* encoding */ );

char[] ⇔ String

Interconverting char [] and String is easier because there is no encoding involved. Encoding is about how to represent 16-bit Unicode in 8-bit bytes.
String s = "abc" ;
// string -> char[]
char[] ca = s.toCharArray();
// char[] -> String
String s = new String( ca );

Beware of char[].toString(). It does not convert the character array to String. It prints out the address of the array — not useful for anything. Use new String ( chararray ) instead.

Hexadecimal

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

StringBuffers & StringBuilders

Strings and StringBuffers can be interconverted, as can Strings and StringBuilders

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.;

floating point for more details.

Left Zeros

The standard conversions give you no leading blanks or leading zeroes. Here is a code snippet to convert an int to a 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.

Java 1.5+, java.io. PrintWriter. printf, java.io. PrintStream. printf and the java.util. Formatter class give you abilities similar to C’s printf. See printf for more details.

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. You may be able to use my CSVReader class. Or 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

StringTokenizer Method of Reading Integers From An ASCII file

Binary

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.

Metric Conversions

You can convert metric to Imperial or other measurements by putting expressions in ordinary Google search boxes:

Learning More

Sun’s Javadoc on the Byte class : available:
Sun’s Javadoc on the Character class : available:
Sun’s Javadoc on the Double class : available:
Sun’s Javadoc on the Float class : available:
Sun’s Javadoc on the Integer class : available:
Sun’s Javadoc on the Long class : available:
Sun’s Javadoc on the Short class : available:
Sun’s Javadoc on the String class : available:

CMP homejump to top
CMP logo
feedback Please email your feedback for publication, errors, omissions, broken/redirected link reports
and suggestions to improve this page to Roedy Green : feedback email
made with CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[65.110.21.43]
Your face IP:[38.103.63.58]
You are visitor number 149,956.
You can get a fresh copy of this page from: or possibly from your local J: drive (Java virtual drive/mindprod.com website mirror)
http://mindprod.com/jgloss/conversion.html J:\mindprod\jgloss\conversion.html