Java Converting Numbers to Objects and Vice Versa - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript Java Converting Numbers to Objects and Vice Versa - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Monday, December 31, 2018

Java Converting Numbers to Objects and Vice Versa

Java Converting Numbers to Objects
and Vice Versa

Problem

You need to convert numbers to objects and objects to numbers.

Solution

Use the Object Wrapper classes listed in Table at the beginning.

Explained

Often you have a primitive number and you need to pass it into a method where an
Object is required. This frequently happens when using the Collection classes and earlier.

To convert between an int and an Integer object, or vice versa, you can use the
following:

// IntObject.java
// int to Integer
Integer i1 = new Integer(42);
System.out.println(i1.toString( )); // or just i1
// Integer to int
int i2 = i1.intValue( );
System.out.println(i2);

No comments:

Post a Comment

Post Top Ad