Java: Data Types

Data types

Data type is an attribute of data that indicates the compiler or interpreter how the user intends to use it. The data type defines which operations can safely be performed to create, transform, and use the variable in another computation. 

We have two types of data types:

  • Primitive Data Types 
  • Non- Primitive Data types.
Data Types in Java

Primitive Data Type

Predefined data types that are supported by a programming language and cannot be broken down into further simpler types are known as Primitive data types.

We have eight Primitive data types namely;-

  • boolean
  • char
  • byte
  • short
  • int
  • long
  • float
  • double

1. Boolean

  • The boolean data type allows the programmer to store only two values- True or False.
  • Hence it represents only one bit of information but the size of this data type is implementation dependent.
  • It is often used as simple flag that is used to determine a True / False situation.
Run
public class Main
{
public static void main(String[] args) {
boolean a = true;
if (a == true)
System.out.println("Hey There Prepster");
}
}
Output :

Hey There Prepster

2. Byte

  • The Byte data type is an 8-bit signed two’s complement integer.
  • This can be used instead of int or other integer types to save memory when we are certain that the value will be within -128 and 127, since byte is 4 times smaller than the int type.
  • A special feature of this data type is that it is cyclic in nature. 
Run
class Main {
    public static void main(String[] args) {
 	byte num;

    	num = 126;

    	num++;

    	System.out.println(num);

    	num++;

    	System.out.println(num);

    }
}
Output :
127
-128

3. Short

  • The short data type is a 16-bit signed two’s complement integer.
  • Its value-range lies between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0.
  • The short data type can also be used to save memory in large arrays , just like byte data type. A short data type is 2 times smaller than an integer.
Run
public class Main
{
	public static void main(String[] args) {
		short num = 10000;
        System.out.println(num);
	}
}
Output :
10000

4. Int

  • The int data type is the preferred data type when we create variables with a numeric value.
Run
public class Main
{
public static void main(String[] args) {
short num = 10000;
System.out.println(num);
}
}
Output :
10000