'int' data type

Data Types - In order to assign a value to a variable in Java, we have to first declare the variable as any type. For example, if you want to store integers like 10, 100 etc into a variable say 'var', we have to declare the 'var' as type 'int' as shown below -


int var;

Now we can assign an integer value say 100 as shown below -

var = 100; 

Now if you try to assing a non-interger value say "cat", Java will give you an error -

var = "cat";

Hence in Java, we use Data Types to define the variables to store the required type of values. The below examples will give you an understanding of how Data Types help us to declare variables of different types and assign values to the variables.



int is the most commonly used integer data type.


A sample program for demonstration the usage of int data type:

class Sample1
{
     public static void main(String args[])
     {
          int count = 100;    // A variable declared using integer data type int can store integer values like 100 
          System.out.println(count);
      }
 }

The output of this program will be:

100




What happens on passing the decimal values to an integer variable?

class Sample2
{
    public static void main(String args[])
    {
         int count;
         count = 100.123;
         System.out.println(count);
     }
 }

The following error will be displayed on compiling this program:

error: possible loss of precision

      count=100.123;
            ^
  required: int
  found:    double
1 error


'short' data type is also an integer data type but stores less range of values from -32768 to 32767. This is a very less used data type, so I'm not writing it in a separate post.

'byte' data type is also an integer data type but stores less range of values from -128 to 127. This is a very less used data type, so I'm not writing it in a separate post.

Ranges of Integer data types: