Java Integer And Java BigInteger Class With Examples

This Tutorial Explains Java Integer, Java Long, Max Int, NextInt() Method with Examples. We will also look at Java BigInteger Class & its Application:

In this tutorial, we will discuss Java integer and the other primitive types that are related to Java integer like byte, short and long. We will also take a look at BigInteger class, it’s usage, and the application areas along with some suitable examples wherever applicable.

Some of the most popular frequently-asked questions related to the topic along with ample programming examples are also included, thus you can apply these techniques in your programs.

=> Visit Here To Learn Java From Scratch.

Java integer

Java Primitive Types

As we all know, Java has eight primitive types i.e. int, short, long, byte, float, double, char, and boolean. Out of these eight primitive types, Java integers include int, short, long, and byte.

All of these are “signed”, “positive” and “negative” value, and given below are the range of each of these types.

Primitive TypesWidthRange
long64–9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int32–2,147,483,648 to 2,147,483,647
short16–32,768 to 32,767
byte8–128 to 127

Java Integer

long

We have a “long” primitive type that has the highest width (signed 64-bit). So, if your program needs calculation of an integer that may produce a large output then you must declare your variable with “long”.

Syntax

// distance between Sun and Earth can be declared with long 

long distance;

int

The most commonly used Java integer type is “int” and you will often see them being used in the programs. It is a signed 32-bit type.

Syntax

int a;

short

This is the least used Java integer type. It is a signed 16-bit type and ranges from –32,768 to 32,767.

Syntax

short b;

byte

This is the smallest Java integer type. It is a signed 8-bit type and has a range from –128 to 127.

Syntax

byte c;

Java Integer Example

In this example, we will initialize four different variables with four different Java integer types. Also for demonstration purposes, we have initialized a byte integer type whose value is beyond the range. This will throw an error (commented).

One thing to remember is that any byte variable can be declared with short, int, and long as the range increases from byte ->short -> int -> long but it cannot be done vice versa.

The bottom line is that you are not allowed to assign a value that lies beyond the range of any particular Java integer type.

public class integer {

	public static void main(String[] args) {
		
		long a = 3000;
		int b = 2000;
		short c = 300;
		byte d = 30;
		
		/*
		 * the below initilization will throw error as it is out of range
		 * byte ranges from -128 to 127 
		 */
		
		//byte d = 400; (ERROR)
		
		long e = (a*b*c*d);
		System.out.println(e);
	}

}

Output

Java integer example

Java BigInteger Class

Java has a special class called BigInteger class that is used to perform operations that involve big integer calculation and whose result may fall outside the range of any of the above mentioned Java integer types.

For example: Calculating the factorial of 1000 will give you 2568 digits which is very huge. This cannot be contained in any of the Java integer types.

One of the major advantages of this class is that there is no bound on the limit or range because of the dynamic allocation of memory.

import java.math.BigInteger;public class BigInt {
	
	/*
	 *  This method fact(num) will be called in the main
	 *  method to calculate the factorial of num.
	 *  num can be any number that we will specify in the main method.
	 */
	
	static BigInteger fact(int num) {
		
		// Initializing BigInteger class
		BigInteger bi = new BigInteger("1");		/*
		 * Inside for loop, we are starting the loop from i = 1
		 * and multiplying bi with the value of “i” and then incrementing
		 * the value of “i” by 1.
		 * This is repeated until “i” becomes equal or greater than the number num.
		 */
		for (int i = 1; i <= num; i++)
			bi = bi.multiply(BigInteger.valueOf(i));		return bi;	}
	public static void main(String args[]) throws Exception {
		int num = 1000;
		
		/*
		 * calling method fact(num) and the output of bi will be the
		 * output for fact(num)
		 */
		System.out.print(fact(num));
	}

}

Output

The factorial of 1000 has 2568 characters. You can edit the value of N (in the main method) and provide a smaller number to calculate the factorial.

Java BigInteger Class - console

Java BigInteger Class - output

Java nextInt()

This method is an inbuilt method of the Java Scanner class. It is used to extract the integers. It comes under the package “ java.util.Scanner” and the syntax is given below.

Syntax

public int nextInt()

Its return type is the integer scanned from the input.

Swapping Digits Of A Number

In the below example, we have demonstrated how the nextInt() method works. This method is useful when we want to provide input through a console. Here, we are trying to swap two digits of a number by using a third variable and printing before and after swapping the digits ‘x’ and ‘y’.

import java.util.Scanner;

public class Swap {	public static void main(String[] args) {

		int x, y, temp;
		System.out.println("Enter x and y");
		
		// Initializing scanner class for input through a console
		Scanner in = new Scanner(System.in);
		
		// used nextInt() method to extract the value of x and y
		x = in.nextInt();
		y = in.nextInt();
		
		// Printing x and y before swapping
		System.out.println("Before Swapping" + x + y);
		temp = x;
		x = y;
		y = temp;
		
		// Printing x and y after swapping
		System.out.println("After Swapping" + x + y);
		
	}

}

Output

Swapping digits of a number

Finding Integers In String

In the below example, we are trying to find the integers in a String using the nextInt() method. We have initialized a String with an alphanumeric value and then used looping for the conditional check of the String as more characters.

Thereafter, we have used the nextInt() method to print the integer inside the if-else condition.

import java.util.*;

public class example {
	public static void main(String[] argv) throws Exception {

		String str = "This 78 Num % 6 9 98 85M";
		// initialized scanner class and passed the String
		Scanner scanner = new Scanner(str);		while (scanner.hasNext()) {			

// if the next item is integer then print this block
			if (scanner.hasNextInt()) {
				System.out.println("Integer: " + scanner.nextInt());
			}			// if next item is not an integer then print this block
			else {
				System.out.println("Not an integer: " + scanner.next());
			}
		}
		scanner.close();
	}
}

Output

Finding integers in String

Java max Int

As we know that the Java integer type ‘int’ has a range from –2,147,483,648 to 2,147,483,647 which is also from -231 to 231-1. We can also derive these values by using Java max int. We just have to use Integer.MAX_Value and Integer.MIN_Value.

Let's consider the below program.

public class MaxMin {

	public static void main(String[] args) {
		
		System.out.println(Integer.MAX_VALUE);
		System.out.println(Integer.MIN_VALUE);	}}

Output

Java max Int

Frequently Asked Questions

Q #1) Is isInteger, a method in Java?

Answer: Yes. Java has a method isInteger() whose return type is boolean and is used to check if the input is an integer or not. It returns true if it is an integer.

Q #2) What is the difference between Integer and int?

Answer: Given below is the difference between Integer and int.

Integerint
It is a class type.It is a primitive type.
It has 128 bits.It has 32 bits for storage.
Converts int into objects and vice versa.Stores integer value into memory.

Q #3) Is Java Integer immutable?

Answer: Yes. Once you have created an instance of Integer, you cannot change it. They are synchronous as well.

Q #4) How to check the bytes and width of an integer?

Answer: Given below is the program to get the bytes and width of an integer.

public class integer {

	public static void main(String[] args) {
		
		System.out.println("Integer has " +Integer.BYTES + " bytes");
		System.out.println("Width of an Integer is : " +Integer.SIZE);	
}

}

Output

check bytes and width of an integer - output

Q #5) Write a program to convert an integer to binary and then find the bit count.

Answer: In this program, we have taken an input through the console using the nextInt() method. Then we have used the inbuilt method of the Integer to get the binary representation (base 2) as well as the bit count.

import java.util.Scanner;
public class integer {
	public static void main(String[] args) {
		int x;
		System.out.println("Enter the number");
		Scanner in = new Scanner(System.in);
		x = in.nextInt(); 
		
		// converting the integer to binary
		System.out.println(Integer.toBinaryString(x));
		
		// finding the bit count
		System.out.println(Integer.bitCount(x));
		
	}
}

Output

convert an integer to binary - output

Conclusion

In this tutorial, we discussed Java Primitive types and Java Integer types along with the range, width, and simple examples.

We explore Java BigInteger class and Java nextInt() from the Scanner class, its usage, application area, etc. Apart from these, we also covered the max and min range of int with the help of a program using which you can derive the range.

=> Watch Out The Simple Java Training Series Here.