In: Computer Science
(c) Explain TWO (2) differences between int and Integer in the context of Java programming using suitable example,
public class Main
{
public static void main (String[]args)
{
/* 1. First difference is that int can only store int type
values
while Integer class can also be used for storing values of string
type and
latter that is converted to int type */
// Storing integer value as it is a primitive data type
int a1 = 10;
//int a1 = "10" will cause compile time error, since int is a
primitive type
// it cannot store different type of values
// Storing String because Integer is a class
// a2 is an object of Integer class
Integer a2 = new Integer ("10");
// Print the sum of integer value of "10"(from a2) and 10(from
a1)
int r = a1+a2;
System.out.println ("Sum of "+a1+"(int) and " + a2+"(Integer) is :
"+r);
// Output 20
/* 2. Another difference is that since Integer is a class,
Different inbuilt methods can be applied while
int is only used for storing int value */
System.out.println("Number of set bits in "+a2+" is :
"+Integer.bitCount(a2));
System.out.println("Binary of "+a2+" is :
"+Integer.toBinaryString(a2));
System.out.println("Octal of "+a2+" is :
"+Integer.toOctalString(a2));
System.out.println("Hexadecimal of "+a2+" is :
"+Integer.toHexString(a2));
}
}
OUTPUT
: