JavaRush /Java Blog /Random EN /Java Integer Class Guide

Java Integer Class Guide

Published in the Random EN group
In this article we will talk about the Integer class. Let's consider these questions:
  • what are wrapper classes;
  • autopacking/unpacking of primitives;
  • operation of the Integer class, its methods and constants.
Java Integer Class Tutorial - 1

Wrapper classes of primitive types

As you know, Java has various data types, which can be divided into two blocks:
  • primitive;
  • reference.
There are several primitive data types in Java:
  • integers - byte, short, int, long;
  • floating point numbers (real) - float, double;
  • logical data type - boolean;
  • character data type - char.
Each primitive data type has its own wrapper class. A reference data type that wraps its primitive little brother in a Java object. Below are the primitive data types and their corresponding wrapper classes:
Primitive type Wrapper class
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
In a practical sense, primitives and their wrapper classes have a lot in common. Most operations are performed identically. However, wrapper classes have a number of characteristics that are not characteristic of primitives. First, there are classes: when working with wrapper classes, we work with objects. Secondly (everything that follows follows from point one), these objects can be null. Third, wrapper classes provide a number of constants and methods that make it easier to work with a particular data type. In this article we will take a closer look at working with the Integer class.

The Integer

The Integer class is a wrapper class of the primitive type int. This class contains a single field of type int. As a wrapper class, Integer provides various methods for working with ints, as well as a number of methods for converting int to String and String to int. Below we will look at various examples of working with the class. Let's start with creation. The most commonly used (and easiest to use) is the following creation option:
Integer a = 3;
That is, the initialization of an Integer variable in this case is similar to the initialization of an int variable. Moreover, an Integer variable can be initialized with the value of an int variable:
int i = 5;
Integer x = i;
System.out.println(x); // 5
In the case above, autopacking occurs implicitly. We'll talk more about it below. In addition to the initialization options listed above, an Integer variable can be created like other objects, using a constructor and the new keyword:
Integer x = new Integer(25);
System.out.println(x);
However, it takes longer to write and longer to read, so this option is the least common. You can do everything with Integer variables that you can do with int variables. They can be:
Fold

Integer a = 6;
Integer b = 2;
Integer c = a + b;
System.out.println(c); // 8
Subtract

Integer a = 6;
Integer b = 2;
Integer c = a - b;
System.out.println(c); // 4
Multiply

Integer a = 6;
Integer b = 2;
Integer c = a * b;
System.out.println(c); // 12
Divide

Integer a = 6;
Integer b = 2;
Integer c = a / b;
System.out.println(c); // 3
Increment

Integer a = 6;
a++;
++a;
System.out.println(a); // 8
Decrement

Integer a = 6;
a--;
--a;
System.out.println(a); // 4
However, with all this, you need to be careful and remember that Integer is a reference data type, and a variable of this type can be null. In this case (if the variable is null), it is better to refrain from arithmetic operations (and any others in which null does not bode well). Here's an example:
Integer a = null;
Integer b = a + 1; // Здесь мы упадем с "Exception in thread "main" java.lang.NullPointerException"
System.out.println(b);
Most comparison operations are carried out in the same way as in the primitive type int:
Integer a = 1;
Integer b = 2;

System.out.println(a > b);
System.out.println(a >= b);
System.out.println(a < b);
System.out.println(a <= b);
Output:

false
false
true
true
The operation of comparing two Integer variables stands out. And the point here is that Integer is a reference data type, and its variables store references to values, and not the values ​​themselves (objects). Manifestations of this fact can be observed when executing the following code fragment:
Integer a = 1;
Integer b = 1;
Integer c = new Integer(1);

System.out.println(a == b); // true
System.out.println(a == c); // false
The result of the first equality will be true, and the second will be false. This happens because in the first case we compare two variables (“a” and “b”) that store references to the same object. And in the second case, we compare two variables that refer to two different objects (when creating the variable “c” we created a new object). Let's give another interesting example:
Integer a = 1;
Integer b = 1;

Integer x = 2020;
Integer y = 2020;

System.out.println(a == b); // true
System.out.println(x == y); // false
As we can see, the result of the first comparison is true, and the result of the second is false. It's all about caching. All integers in the range from -128 to 127 inclusive (these values ​​can be customized) are cached. So when we create a new variable and assign it an integer value between -128 and 127, we are not creating a new object, but rather assigning the variable a reference to an already created object in the cache. Now, knowing this fact, the example above does not seem so mystical. Variables a and b refer to the same object - an object from the cache. And during the initialization of the variables x and y, we created a new object each time, and these variables stored references to different objects. And as you know, the == operator compares the values ​​of variables, and the values ​​of reference variables are references. To accurately check for equality between two Integer variables, you must use (no matter how trivial it may sound) the equals method. Let's rewrite the example above:
Integer a = 1;
Integer b = 1;

Integer x = 2020;
Integer y = 2020;

System.out.println(a.equals(b)); // true
System.out.println(x.equals(y)); // true

Autopacking and unpacking Integer

What is auto packing and unpacking? When creating new Integer variables, we used the following construction:
Integer a = 2020;
This way we created a new object without using the new key operator. This is possible thanks to the autopacking mechanism of the primitive type int. The reverse procedure occurs when assigning a primitive int variable to the value of an Integer reference variable:
Integer a = 2020;
int x = a;
In this case, we seem to have assigned a reference (namely, the reference to an object is the value of the variable “a”) to a primitive variable. But in fact, thanks to the auto-unpacking mechanism, the value 2020 was written to the “x” variable. Auto-packing/unpacking is a very common phenomenon in Java. Often it happens by itself, sometimes even without the programmer’s knowledge. But you still need to know about this phenomenon. We have an interesting article on this topic on Javarush .

Integer class constants

The Integer class provides various constants and methods for working with integers. In this section we will take a closer look at some of them in practice. Let's start with the constants. The table below shows all the class constants:
Costanta Description
SIZE The number of bits in the two-digit number system occupied by the int type
BYTES The number of bytes in the two-digit number system occupied by the int type
MAX_VALUE The maximum value that an int type can hold
MIN_VALUE The minimum value that an int type can hold
TYPE Returns an object of type Class from type int
Let's look at the values ​​of all these constants by running the following code:
public static void main(String[] args) {
        System.out.println(Integer.SIZE);
        System.out.println(Integer.BYTES);
        System.out.println(Integer.MAX_VALUE);
        System.out.println(Integer.MIN_VALUE);
        System.out.println(Integer.TYPE);
}
As a result, we get the following output:

32
4
2147483647
-2147483648
int

Methods of the Integer class

Now let's take a quick look at the most used methods of the Integer class. So, the “top” ones are headed by methods for converting a number from a string, or converting a string from a number. Let's start with converting a string to a number. The parseInt method is used for these purposes , the signature is below:
  • 
    static int parseInt(String s)
This method converts String to int. Let's demonstrate how this method works:
int i = Integer.parseInt("10");
System.out.println(i); // 10
If conversion is not possible—for example, we passed a word to the parseInt method—a NumberFormatException will be thrown. The parseInt(String s) method has an overloaded sibling:
  • 
    static int parseInt(String s, int radix)
This method converts the parameter s to int. The radix parameter indicates in which number system the number in s was originally written, which must be converted to int. Examples below:
System.out.println(Integer.parseInt("0011", 2)); // 3
System.out.println(Integer.parseInt("10", 8));   // 8
System.out.println(Integer.parseInt("F", 16));   // 15
The parseInt methods return a primitive data type int. These methods have an analogue - the valueOf method . Some variations of this method simply call parseInt internally. The difference from parseInt is that the result of valueOf will be an Integer, not an int. Let's consider below all the options for this method and an example of how it works:
  • static Integer valueOf(int i) - returns an Integer whose value is i;
  • static Integer valueOf(String s) - similar to parseInt(String s), but the result will be Integer;
  • static Integer valueOf(String s, int radix) - similar to parseInt(String s, int radix), but the result will be Integer.
Examples:
int a = 5;
Integer x = Integer.valueOf(a);
Integer y = Integer.valueOf("20");
Integer z = Integer.valueOf("20", 8);

System.out.println(x); // 5
System.out.println(y); // 20
System.out.println(z); // 16
We looked at methods that allow you to convert String to int/Integer. The reverse procedure is achieved using the toString methods . You can call the toString method on any Integer object and get its string representation:
Integer x = 5;
System.out.println(x.toString()); // 5
However, due to the fact that the toString method is often called implicitly on objects (for example, when sending an object to the console for printing), this method is rarely used explicitly by developers. There is also a static method toString, which takes an int parameter and converts it to a string representation. For example:
System.out.println(Integer.toString(5)); // 5
However, like the non-static toString method, using a static method explicitly is rare. More interesting is the static method toString, which takes 2 integer parameters:
  • static String toString(int i, int radix) - will convert i to a string representation in the radix number system.
Example:
System.out.println(Integer.toString(5, 2)); // 101
The Integer class has a couple of methods for finding the maximum/minimum of two numbers:
  • static int max(int ​​a, int b) will return the largest value among the passed variables;
  • static int min(int a, int b) will return the smallest value among the passed variables.
Examples:
int x = 4;
int y = 40;

System.out.println(Integer.max(x,y)); // 40
System.out.println(Integer.min(x,y)); // 4

Conclusion

In this article we looked at the Integer class. We talked about what kind of class this is and what wrapper classes are. We looked at the class from a practical point of view. We looked at examples of arithmetic operations, including comparison operations. We took a look at the intricacies of comparing two Integer variables, and examined the concept of cached objects. We also mentioned the phenomenon of auto-packing/unpacking of primitive data types. In addition, we managed to look at some methods of the Integer class, as well as some constants. They gave examples of converting numbers from one number system to another.

Homework

  1. Study what other methods of the Integer class there are (you can study them on the website with the official documentation ), write in the comments which of the methods you have studied (excluding those given in the article) is most useful in your opinion (will be used by you most often). And also provide reasons for your opinion.

    PS There are no correct answers here, but this activity will allow you to better study the class.

  2. Solve a small simple problem to consolidate the material.

    We have two numbers:

    1100001001 - in the binary number system
    33332 - in the quinary number system

    It is necessary, using only methods of the Integer class, to determine the maximum among two given numbers, and then display the difference between the maximum and minimum value in the ternary number system.

  3. Convert the maximum possible Integer value to the octal number system and display the number of digits in the resulting number (count the number programmatically).

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION