JAVATM- The Beginnings

Wrapper Classes

There are times when we want to treat a value of a primitive type as an object. Java provides a wrapper class for each primitive data type. Each wrapper class encapsulates its corresponding primitive data type. It is said to “wrap” a value of that type.

Section 1 - The Integer Class

The Integer class wraps an int value. You can create an Integer object by assignment to an int literal, variable, or expression.

        Integer i = 5;                        // Assignment to an int literal

        Integer j = 2+7;                        // Assignment to an int expression

        int x = 4;

        Integer k = x;                        // Assignment to an int variable

        System.out.println(i);                // Prints 5

        System.out.println(j);                // Prints 9

        System.out.println(k);                // Prints 4

Section 1a - The parseInt Method

The static parseInt method converts a string formatted as a signed integer to an int value.

        String s = “100”;                                // s contains string “100”

        int z = Integer.parseInt(s);                // z contains int value 100

        int y = Integer.parseInt(“-200”);                // y contains int value 200

The parseInt method can be called with a second argument that indicates the numeric base of the string.

        System.out.println(Integer.parseInt("8000",16));        // Prints 32768

        System.out.println(Integer.parseInt("-8000",16));        // Prints -32768

Copyright ©2017 by Ralph Lecessi Incorporated. All rights reserved.



Back to ralphlecessi.com