Warning: Illegal string offset 'value' in /home/content/44/9038144/html/deegeu/wp-content/themes/Divi/includes/builder/main-modules.php on line 14095

Warning: Illegal string offset 'value' in /home/content/44/9038144/html/deegeu/wp-content/themes/Divi/includes/builder/main-modules.php on line 14095

Java Number class conversions in depth – J047

by | May 23, 2016

DeegeU Java Course

The “Java Number class conversions in depth” video is part of a larger free online class called “Free Java Course Online”. You can find more information about this class on “Free Java Course Online” syllabus.

Transcript – Java Number class conversions in depth

Hi, in this video we’re continuing our look at the Java Number classes by focusing on the methods used to convert our Number to and from different representations.

Java number class conversions using valueOf()

The Java number classes provide methods to convert from primitives. You’ll remember from the Number autoboxing and unboxing tutorial, valueOf() is used to convert primitives to the Number class.

Integer i = 42;
i = Integer.valueOf(42);
i = Integer.valueOf("42");
i = Integer.valueOf("42", 10);

valueOf() is heavily used for autoboxing and unboxing. We covered valueOf in depth in the auto boxing unboxing video, so we won’t go into depth again. Every example here does the same thing. They create an Integer instance with the value 42. This is just the beginning of the Java number conversions available.

Java number class conversions to Java primitives

The first set of Java number conversion methods available to us are methods to convert our Integer wrapper class to one of the primitive value types. The most useful conversion method is to convert the class to the matching Java primitive type. In this case, we’d convert an Integer to an int. We can also convert the Integer to other primitive data types, with varying consequences.

Integer i = 42;
int intValue = i.intValue();
// Shortening conversions
short shortValue = i.shortValue();
byte byteValue = i.byteValue();
// Widening conversions
long longValue = i.longValue();
float floatValue = i.floatValue();
double doubleValue = i.doubleValue();

If you convert the integer class to a smaller primitive type, say a short, you will cause a narrowing conversion. This is the same narrowing conversion we saw when casting primitives to smaller primitives in the variables video. Converting to larger primitives causes a widening conversion.

Java number class conversions from text to Integer

We also have methods to convert text to an Integer. We would want to do this when we get input from a user, or maybe we’re converting strings read from a text file. Text is contained in the String class. We’re covering the String class in depth after we’re done with Numbers. For now, just know a String is a class that represents text. In order to convert text to a Integer, we have the decode and parseInt methods. parseInt is Integer class specific. If we were working with the Long class, the method would be parseLong, but it has the same behavior. Let’s look closer at these methods.

Integer a = Integer.decode("42");   // Decimal
System.out.println("a = " + a);

Integer b = Integer.decode("0x42"); // Hex
System.out.println("b = " + b);

Integer c = Integer.decode("042");  // Octal
System.out.println("c = " + c);

The decode method takes any number string based on any radix, and converts it to an Integer instance. In order to determine the correct radix to use, decode expects the string to be formatted in a special way. If the number is a decimal, you just use the number with no special formatting. If the number is a hexadecimal number, the number must start with 0x, 0X, or #. If the number is octal, it needs to start with a 0. The decode method can handle numbers with a radix of 8, 10, or 16. So what do we use if we have something else, like a binary number?

Integer i;
i = Integer.parseInt("42", 10);
i = Integer.parseInt("42");

In that case, we need to use the static method parseInt(). Again, this method is specific to Integers. The Long class has parseLong. parseInt takes two parameters, the number to convert and the radix. In this case, we do not need to format the number text in any special way. The String should be just the number in the correct form.

Integer i;
i = Integer.parseInt("101010", 2);
System.out.println("a = " + a);

i = Integer.parseInt(“42”, 2); // ERROR

For example, if we need to convert a binary number 101010 we call it like this. And it returns 42. If we used a number String that is not a valid binary number, then the method will throw a NumberFormatException. In this case, 42 is not a binary number.

System.out.println("dog36 = " + i.parseInt("DOG", 36));
System.out.println("dog4 = " + i.parseInt("DOG", 4);   // ERROR
System.out.println("life = " + i.parseInt("42");

parseInt will work for any radix less than or equal to 36. If we set the radix to 36 and tried to convert “DOG”, we’ll get the value 17728. However using the same number and a radix of 4 gives us another NumberFormatException. There’s also an overloaded version of parseInt that takes only one parameter, the number to convert. This method defaults to radix 10, and expects a decimal number to parse.

Java number class conversions to String

If we need to convert back to a string, we also have methods for that. There are three static methods on the Integer class to convert to a particular radix, toBinaryString(), toHexString(), and toOctalString(). These methods will convert your Integer to a string. So if your initial number was -42, the string will look like this (11111111111111111111111111010110). It works the same for hex and octal numbers. There is also a toString method to output our number in any radix less than or equal to 36.

Integer i = -42;

System.out.println("Binary = " + Integer.toBinaryString(i));
System.out.println("Hex    = " + Integer.toHexString(i));
System.out.println("Octal  = " + Integer.toOctalString(i));

System.out.println("Base36 = " + Integer.toString(i, 36));
System.out.println("Default= " + Integer.toString(i));

We can also call toString on instances. This outputs the number contained by the wrapper class as a decimal string.

Unsigned integer functions were added in Java 8. This is for Integer and Long classes only. An unsigned integer in this context means the number is treated as if the sign bit adds to the magnitude. So we get bigger numbers, but they are all positive. If we parse this big number (4294967295) as an unsigned int and print it as an Integer, we get the number -1. That’s because we’re still working with a Java int primitive.

int uint = Integer.parseUnsignedInt("4294967295");

System.out.println("as Integer = " + Integer.toString(uint));

System.out.println("as Unsigned Integer = " + Integer.toUnsignedString(uint));

To get the number as an unsigned integer string, we need to use the method toUnsignedString().

To get the number as an unsigned integer string in different radix, we can use the overloaded method to take the radix as a parameter. It works like the other radix methods.


If you have any questions, add them to the comments below. Next we’ll look at comparing Java Number instances. Liking the video helps me know what I’m doing right. If you enjoyed the video, please like the video and share with your developer friends! You’ll also want to sign up for the DeegeU newsletter. It contains the videos for the month, and tips and news not contained in the videos. I’ll send it out once a month.

And with that, I’ll see you in the next tutorial!

Related Posts

Tools Used

  • Java
  • NetBeans

Media Credits

All media created and owned by DJ Spiess unless listed below.

  • No infringement intended

Get the code

The source code for “Java Number class conversions in depth” can be found on Github. If you have Git installed on your system, you can clone the repository by issuing the following command:

 git clone https://github.com/deege/deegeu-java-intro.git

Go to the Support > Getting the Code page for more help.

If you find any errors in the code, feel free to let me know or issue a pull request in Git.

Don't miss another video!

New videos come out every week. Make sure you subscribe!



DJ Spiess

DJ Spiess

Your personal instructor

My name is DJ Spiess and I'm a developer with a Masters degree in Computer Science working in Colorado, USA. I primarily work with Java server applications. I started programming as a kid in the 1980s, and I've programmed professionally since 1996. My main focus are REST APIs, large-scale data, and mobile development. The last six years I've worked on large National Science Foundation projects. You can read more about my development experience on my LinkedIn account.

Pin It on Pinterest

Share This