Introduction
The Integer
class in Java is a wrapper for the primitive type int
. It provides methods for converting and manipulating integer values, handling arithmetic operations, and comparing integers.
Table of Contents
- What is
Integer
? - Creating
Integer
Instances - Common Methods
- Examples of
Integer
- Conclusion
1. What is Integer?
Integer
is a final class that wraps a value of the primitive type int
in an object. It offers methods for converting between int
and String
, performing arithmetic operations, and comparing integers.
2. Creating Integer Instances
You can create Integer
instances in several ways:
- Using the
Integer
constructor:new Integer(int value)
ornew Integer(String value)
- Using the
Integer.valueOf(int value)
orInteger.valueOf(String value)
methods
3. Common Methods
intValue()
: Returns the value of thisInteger
as a primitiveint
.toString()
: Returns aString
representation of theint
value.parseInt(String s)
: Parses aString
to a primitiveint
.compareTo(Integer anotherInteger)
: Compares twoInteger
objects numerically.compare(int x, int y)
: Compares twoint
values.MAX_VALUE
: A constant holding the maximum value anint
can have (2^31-1).MIN_VALUE
: A constant holding the minimum value anint
can have (-2^31).
4. Examples of Integer
Example 1: Creating Integer
Instances
This example demonstrates how to create Integer
instances using constructors and valueOf
methods.
public class IntegerInstanceExample { public static void main(String[] args) { Integer i1 = new Integer(10); Integer i2 = Integer.valueOf(20); Integer i3 = Integer.valueOf("30"); System.out.println("i1: " + i1); System.out.println("i2: " + i2); System.out.println("i3: " + i3); } }
Output:
i1: 10 i2: 20 i3: 30
Example 2: Parsing a String to int
This example shows how to parse a String
to a primitive int
using parseInt
.
public class ParseIntExample { public static void main(String[] args) { int i1 = Integer.parseInt("50"); int i2 = Integer.parseInt("100"); System.out.println("i1: " + i1); System.out.println("i2: " + i2); } }
Output:
i1: 50 i2: 100
Example 3: Comparing Integer Values
In this example, we demonstrate how to compare two Integer
values.
public class CompareIntegerExample { public static void main(String[] args) { Integer i1 = Integer.valueOf(10); Integer i2 = Integer.valueOf(20); int comparison = Integer.compare(i1, i2); if (comparison < 0) { System.out.println("i1 is less than i2"); } else if (comparison > 0) { System.out.println("i1 is greater than i2"); } else { System.out.println("i1 is equal to i2"); } } }
Output:
i1 is less than i2
Conclusion
The Integer
class in Java is a useful wrapper for the primitive int
type. It provides methods for converting, manipulating, and handling integer values, making it a versatile tool in Java programming.