Java Integer Class

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

  1. What is Integer?
  2. Creating Integer Instances
  3. Common Methods
  4. Examples of Integer
  5. 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) or new Integer(String value)
  • Using the Integer.valueOf(int value) or Integer.valueOf(String value) methods

3. Common Methods

  • intValue(): Returns the value of this Integer as a primitive int.
  • toString(): Returns a String representation of the int value.
  • parseInt(String s): Parses a String to a primitive int.
  • compareTo(Integer anotherInteger): Compares two Integer objects numerically.
  • compare(int x, int y): Compares two int values.
  • MAX_VALUE: A constant holding the maximum value an int can have (2^31-1).
  • MIN_VALUE: A constant holding the minimum value an int 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.

Leave a Comment

Scroll to Top