Int

One of the most commonly used primitive data types is integer, or in Java, int, which can represent any whole number between -2,147,483,648 and 2,147,483,647. View the example below to learn how to declare and use an int variable.

IntegerDataTypeExample.java
package exlcode;

public class IntegerDataTypeExample {

// int can be any integer between -2147483648 and 2147483647
public static int exampleVariableOne = 27;
public static int exampleVariableTwo = -27;
public static int exampleVariableThree = 100000;

public static void main(String[] args) {
System.out.println(exampleVariableOne);
System.out.println(exampleVariableTwo);
System.out.println(exampleVariableThree);
}
}

The integer data type is efficient and versatile; it should be used for any integer math. Notice that int must be a whole number. In case you were wondering, 0 is also a whole number. Assigning int to any non-whole number would cause an error.

In addition to what we see in the example above, we are also able to assign a value to an int by performing a mathematical operation with two numbers, such as int varOne = 10+10; will assign 20 to varOne. As with the other data types we have covered, we are using '=' so that the identifier points to a value it can store.

The negative aspect of the integer data type is if there are any equations that try to create a non-whole number with a decimal out of integer variables, the program will fail because int only allows whole numbers.

Application Question

Which one of these is a valid integer declaration?