Integer types in java

Previous
Next

Integer types:

  • We have 4 integer types among eight available primitive types in java.
  • We can represent size in bytes of memory.
  • Integer data type values come under positive and negative.
  • Data types allow you to select the type appropriate to the needs of the application..
  • Java supports Primitive and Referenced data types.
  • Primitive types are categorized as Integer, Floating, Character and Boolean.

Note: 1 byte = 8 bits = 2^8 = 256 à (-128 to +127)

Following are integer limits representation.

 typeSizeLimits
byte1-128(-2^7) to  +127(2^7-1)
short2-32,768(-2^15) to 32,767(2^15-1)
int4-2,147,483,648(-2^31) to 2,147,483,647(2^31-1)
long8-9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63-1)

Wrapper classes:

  • For every primitive type such as byte, short , float…, there is a corresponding wrapper class like Byte, Short, Float….
  • Using wrapper classes we can perform data conversions like
    • Primitive à Object
    • Primitive à String
    • String à Object
    • ……
  • Wrapper classes containing set of variables(static).
  • Wrapper class variables are used to find the size and limits of each primitive type.

Printing byte limits and size:

class ByteInformation 
{
	public static void main(String[] args) 
	{
		System.out.println("byte minimum limit : " + Byte.MIN_VALUE);
		System.out.println("byte maximum limit : " + Byte.MAX_VALUE);
		System.out.println("byte size in bits : " + Byte.SIZE);
	}
}
  • All variables are static.
  • We need to access these variables their class names.
  • These variables are constants(hence defined in capital letters)
class Sizes
{
	public static void main(String[] args) 
	{
		System.out.println("byte : " + Byte.SIZE/8 + " bytes");
		System.out.println("short : " + Short.SIZE/8 + " bytes");
		System.out.println("int : " + Integer.SIZE/8 + " bytes");
		System.out.println("long : " + Long.SIZE/8 + " bytes");
	}
}

Note: All wrapper classes providing the same set of fields(variables) to find the size and limits.

class LongInformation 
{
	public static void main(String[] args) 
	{
		System.out.println("long minimum limit : " + Long.MIN_VALUE);
		System.out.println("long maximum limit : " + Long.MAX_VALUE);
		System.out.println("long size in bits : " + Long.SIZE);
	}
}

Note: We select the data type depends on the value. We cannot store any value beyond its limit.

class Datatypes 
{
	public static void main(String[] args) 
	{
		byte b1 = 100;
		System.out.println(b1);

		byte b2 = 130;  // Error : out of range
		System.out.println(b2);
	}
}

We need to select the type depends on value range:

class Datatypes 
{
	public static void main(String[] args) 
	{
		byte b1 = 100;
		System.out.println(b1);

		short s1 = 130; 
		System.out.println(s1);

		long l1 = 50000;
		System.out.println(l1);
	}
}
Previous
Next

Add Comment

Courses Enquiry Form