0
0
Javaprogramming~15 mins

Common wrapper methods in Java

Choose your learning style8 modes available
menu_bookIntroduction

Wrapper methods help you convert between simple values and objects easily. They make working with numbers and text smoother.

When you want to convert a number from text to a number type.
When you need to convert a number to a string to show it on screen.
When you want to compare two numbers as objects.
When you want to check if a string can be turned into a number.
When you want to get the value inside a wrapper object.
regular_expressionSyntax
Java
Integer.parseInt(String s)
Integer.valueOf(String s)
String.valueOf(int i)
intValue()
doubleValue()
booleanValue()

parseInt converts a string to a simple int.

valueOf converts a string to an Integer object.

emoji_objectsExamples
line_end_arrow_notchTurns the text "123" into the number 123.
Java
int num = Integer.parseInt("123");
line_end_arrow_notchCreates an Integer object holding 456 from text.
Java
Integer numObj = Integer.valueOf("456");
line_end_arrow_notchTurns the number 789 into the text "789".
Java
String text = String.valueOf(789);
line_end_arrow_notchGets the simple int value from the Integer object.
Java
int n = numObj.intValue();
code_blocksSample Program

This program shows how to convert text to numbers and back using wrapper methods.

Java
public class WrapperMethodsDemo {
    public static void main(String[] args) {
        String numberText = "100";
        int number = Integer.parseInt(numberText);
        Integer numberObj = Integer.valueOf(numberText);
        String textFromNumber = String.valueOf(number);

        System.out.println("Text to int: " + number);
        System.out.println("Text to Integer object: " + numberObj);
        System.out.println("Integer to text: " + textFromNumber);
        System.out.println("Integer object to int: " + numberObj.intValue());
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch

Use parseInt when you only need the simple number.

line_end_arrow_notch

Use valueOf when you want an object to use methods on.

line_end_arrow_notch

Wrapper classes also help with null values and collections.

list_alt_checkSummary

Wrapper methods convert between strings and numbers easily.

parseInt returns a simple number, valueOf returns an object.

You can get the simple value back from an object with methods like intValue().