Integer datatype in java can hold the numbers and it can be positive number or negative. Java has its respective wrapper class Integer.
The class Integer can store both unsigned and signed integer values.
In Java, there are four types of integer such as Byte, Short, Int and Long. let see one by one with example
1. Byte
Byte data type is an 8-bit signed two's complement integer. Default value is 0.
It is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an int.
Example of Byte Data type
package BestJavaTutorial;
public class Simple
{
public static void main(String args[])
{
byte a=100;
byte b=-50;
System.out.println("Value of a: "+a);
System.out.println("Value of b: "+b);
int ans;
ans=a+b;
System.out.println("Answer is: "+ans);
}
}
run:
Value of a: 100
Value of b: -50
Answer is: 50
BUILD SUCCESSFUL (total time: 0 seconds)
2. Short
Short data type is an 16-bit signed two's complement integer. Default value is 0.
It can also be used to save memory as byte data type. A short is 2 times smaller than an int.
Example of short Data type
package BestJavaTutorial;
public class Simple
{
public static void main(String args[])
{
short a=-100;
short b=-50;
System.out.println("Value of a: "+a);
System.out.println("Value of b: "+b);
int ans;
ans=a+b;
System.out.println("Answer is: "+ans);
}
}
run:
Value of a: -100
Value of b: -50
Answer is: -150
BUILD SUCCESSFUL (total time: 0 seconds)
3. Int
Int data type is an 32-bit signed two's complement integer. Default value is 0.
It is generally used as the default data type for integral values unless there is a concern about memory.
Example of int Data type
package BestJavaTutorial;
public class Simple
{
public static void main(String args[])
{
int a=100;
int b=50;
System.out.println("Value of a: "+a);
System.out.println("Value of b: "+b);
System.out.println();
/*Mathematical Operation*/
int sum=a+b;
int sub=a-b;
int mul=a*b;
int div=a/b;
System.out.println("Addition is "+sum);
System.out.println("Subtraction is "+sub);
System.out.println("Multiplication is "+mul);
System.out.println("Division is "+div);
}
}
run:
Value of a: 100
Value of b: 50
Addition is 150
Subtraction is 50
Multiplication is 5000
Division is 2
BUILD SUCCESSFUL (total time: 0 seconds)
4. Long
Long data type is an 64-bit signed two's complement integer. Default value is 0L.
This type is used when a wider range than int is needed.
Example of long Data type
package BestJavaTutorial;
class Simple
{
public static void main(String args[])
{
long a=100000L;
long b=-200000L;
System.out.println("Value of a: "+a);
System.out.println("Value of b: "+b);
long sum=a+b;
System.out.println("Addition is "+sum);
}
}
run:
Value of a: 100000
Value of b: -200000
Addition is -100000
BUILD SUCCESSFUL (total time: 0 seconds)