Converting Numbers to and from Strings using Java

By: Mashoud Emailed: 1728 times Printed: 2329 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

One of the most common programming chores is converting the string representation of a number into its internal, binary format. Fortunately, Java provides an easy way to accomplish this. The Byte, Short, Integer, and Long classes provide the parseByte( ), parseShort( ), parseInt( ), and parseLong( ) methods, respectively. These methods return the byte, short, int, or long equivalent of the numeric string with which they are called. (Similar methods also exist for the Float and Double classes.)

The following program demonstrates parseInt( ). It sums a list of integers entered by the user. It reads the integers using readLine( ) and uses parseInt( ) to convert these strings into their int equivalents.

/* This program sums a list of numbers entered
by the user. It converts the string representation
of each number into an int using parseInt().
*/
import java.io.*;
class ParseDemo {
public static void main(String args[])
throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
String str;
int i;
int sum=0;
System.out.println("Enter numbers, 0 to quit.");
do {
str = br.readLine();
try {
i = Integer.parseInt(str);
} catch(NumberFormatException e) {
System.out.println("Invalid format");
i = 0;
}
sum += i;
System.out.println("Current sum is: " + sum);
} while(i != 0);
}
}

To convert a whole number into a decimal string, use the versions of toString( ) defined in the Byte, Short, Integer, or Long classes. The Integer and Long classes also provide the methods toBinaryString( ), toHexString( ), and toOctalString( ), which convert a value into a binary, hexadecimal, or octal string, respectively.

The following program demonstrates binary, hexadecimal, and octal conversion:

/* Convert an integer into binary, hexadecimal,
and octal.
*/
class StringConversions {
public static void main(String args[]) {
int num = 19648;
System.out.println(num + " in binary: " +
Integer.toBinaryString(num));
System.out.println(num + " in octal: " +
Integer.toOctalString(num));
System.out.println(num + " in hexadecimal: " +
Integer.toHexString(num));
}
}

The output of this program is shown here:

19648 in binary: 100110011000000
19648 in octal: 46300
19648 in hexadecimal: 4cc0


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(1)


1. View Comment

Good examples. However... I am testing for a Hex value (07 or A0) in a string read from a file. How can I compare a one character string (retrieved with substring) to a constant int hex07 = 0x07 or int hexA0 = 0xA0.
I have tried parse, valueOf, etc. I could get there from bit-wise. But I can't get the String (i byte) to an integer. The parses/valueOf give me NUMBER FORMAT EXCEPTION.

I realize you are not QUESTIONS Central... But I Thought I would try... Doug


View Tutorial          By: Doug Whitehead at 2008-11-29 17:10:43

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Mashoud
ThreadGroup Sample in Java
Converting Numbers to and from Strings using Java
Using toLowerCase( ) and toUpperCase( ) in Java
How to use regionMatches( ) in Java
startsWith( ) and endsWith( ) in Java
equals( ) Versus == in Java
compareTo( ) in Java
String Conversion and toString() in Java

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to Send SMS using Java Program (full code sample included)
The Basic Structure of a Simple Java program
XML and Java - Parsing XML using Java Tutorial
What is Java?
Method Overloading (function overloading) in Java
Method Overriding in Java
How to use ArrayList in Java
FileReader and FileWriter example program in Java
Vector example in Java
Simple Port Scanner application using Java
append() in Java
Read from a COM port using Java program
Calendar - sample program in Java
Count number of vowels, consonants and digits in a String in Java
indexOf( ) and lastIndexOf( ) in Java
Most Emailed Articles (in Java)
Vector in Java - Sample Program
Configuring a DataSource in Tomcat
Applet Notinited : Applet xxxxxxxxxxxx notinited
Use of 'finally' in Java
Basics of Exception Handling in Java
Tomcat and httpd configured in port 8080 and 80
Calculate average sale of the week in Java
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
LinkedList in Java
Taking the size of an Array at runtime & generate random numbers to populate the Array
Getting Started with Java
Creating Users and Passwords with Tomcat using tomcat-users.xml
What is JasperReports?