Primitive Data Types in Java

In this tutorial, we will learn about primitive data types in Java. A data type represents the type of data that a variable can hold. For example, you declare a variable like this:

int age = 20;

In the above declaration, there are three parts. The first is the data type, which determines the type of data the variable will store. Here, int is a keyword that specifies the data type of the variable. It indicates that the variable age can only store an integer value.

The second part of a declaration is the variable name (i.e. age), called identifier. It allows the program to refer to the memory location where the value is stored. 20 is the literal integer value that will be stored in the variable named age.

From the above example, it is clear that Java is a strongly typed language. This means that every variable must have a declared type. It may be integer, floating, string, character, etc. Each value in the memory is associated with a specific data type.

Types of Data Types in Java

In Java, there are two kinds of data types:

  • Primitive data types
  • Non- primitive data types
Data types in Java

In this tutorial, you will learn about the primitive data types in Java with the help of some important examples.

Primitive Data Types in Java

Primitive data types are the basic data types that are available in Java or any other programming languages. These data types are predefined by the Java programming language and named by a keyword.

The primitive data types are the fundamental data types that are used to represent a single value in Java. However, these data types are also used to define other data types. When you declare a variable with the primitive data type, it stores the actual data or primitive value.

Types of Primitive Data Types in Java

Java supports eight kinds of primitive data types that can be categorized into four groups:

  • Numeric Integral Types
    • byte
    • short
    • int
    • long
  • Fractional Numeric Types
    • float
    • double
  • Character Type
    • char
  • Boolean Type
    • boolean

So, let’s discuss the primitive data types and its limitations in Java programming language.

Integer Primitive Data Types in Java

Byte Data Type

This is the smallest integer primitive data type in Java, which is useful when working with a stream of data from a network or file. You can also use it to represent flags (on/off values), each bit representing a single flag.

  • Byte data type in Java is an 8-bit signed two’s complement integer.
  • Its range is -128 to 127, meaning the minimum value is -128 and maximum value 127. It can store integer values in the range of -128 to 127 (inclusive).
  • The default value of a byte data type is zero.
  • Byte data type occupies the size 1 byte (8 bits) in the memory.

Example 1:

package myProgram;
public class ByteExample {
public static void main(String[] args) {
  byte age = 25;
  System.out.println("Age: " +age);
  }
}
Output:
      Age: 25

Example 2:

package myProgram;
public class ByteExample {
public static void main(String[] args) {
   byte a = 120;  // Valid value within the range
   byte b = -128; // Valid lower boundary value
   byte c = 127;  // Valid upper boundary value
 // byte d = 128; // Compilation error: value out of range
   System.out.println(a);
   System.out.println(b);
   System.out.println(c);
  }
}
Output:
       120
       128
       127

Short Data Type

This data type is 2 times smaller than int but larger than byte.

  • Short data type is a 16-bit signed two’s complement integer.
  • It can store integer values in the range of -32,768 to 32,767 (inclusive). Minimum value is -32,768 (-2^15) and maximum value is 32,767 (2^15 – 1).
  • The default value of a short data type is 0 if it is not explicitly initialized.
  • A short consumes 2 bytes (16 bits) of memory.

Example 3:

package myProgram;
public class ShortExample {
public static void main(String[] args) {
   short a = 10000;  // Valid value within the range
   short b = -20000; // Valid lower boundary value
   short c = 32000;  // Valid upper boundary value
// short d = 40000; // Compilation error: value out of range

   System.out.println(a);
   System.out.println(b);
   System.out.println(c);
  }
}
Output:
      10000
     -20000
      32000

Example 4: Write a Java program to add two numbers using short data types.

package myProgram;
public class ShortExample {
public static void main(String[] args) {
	short a = 10000;  // Valid short value
    short b = -20000;
    short sum = (short) (a + b);  // Converts the sum into short data type.

    System.out.println("a: " + a);
    System.out.println("b: " + b);
    System.out.println("Sum: " + sum);
  }
}
Output:
     a: 10000
     b: -20000
     Sum: -10000

In this example, we have defined variables named a and b of short type, which have a maximum range of -32,768 to 32,767. When the arithmetic operation (a + b) is performed, Java first promotes the operands a and b to int data type because arithmetic operations are performed at least at the int level, regardless of the operand’s original data type.

So, even though both a and b are short, the result of a + b is an int, and it would be something like:

int result = a + b;  // result is of type int, not short.

The result of a + b is an int, but if you will try to assign it to a short variable sum, you will get compile time error. Since int can hold much larger values than short, Java will not automatically convert the int back to short to avoid potential data loss. Therefore, you need to explicitly cast the int result back to a short type.

short sum = (short) (a + b); 

Without the cast, you would get a compilation error because Java does not allow narrowing conversions without explicit casting.

Int Data Type

The int data type in Java is one of the most commonly used primitive data types in Java. It is larger than the short data type and smaller than the long data type. It is default data type in Java.

  • The int data type represents a 32-bit signed integer value.
  • It takes 4 bytes (i.e. 32 bits) of memory, making it suitable for most general-purpose integer operations.
  • The int data type can store integer values in the range of -2,147,483,648 to 2,147,483,647 (inclusive). The range can be calculated as -231 to 231 – 1.
  • This range is due to the fact that int uses one bit for the sign (positive or negative) and the remaining 31 bits for the value.
  • The default value of an int data type is 0 if it is not explicitly initialized.

Example 5:

package myProgram;
public class IntExample {
public static void main(String[] args) {
	int a = 10000;    // Valid value within the range
	int b = -500000;  // Valid negative value within the range
	int c = 2147483647; // Maximum value for int.
 // int d = 2147483648;  // Compilation error: value out of range
	
	System.out.println(a);
	System.out.println(b);
	System.out.println(c);
  }
}
Output:
      10000
     -500000
      2147483647

Example 6:

package myProgram;
public class IntExample {
public static void main(String[] args) {
	int a = 10;
    int b = 20;
    int sum = a + b; // Arithmetic operation

    System.out.println("a: " + a);
    System.out.println("b: " + b);
    System.out.println("Sum: " +sum);
  }
}
Output:
     a: 10
     b: 20
     Sum: 30

Long Data Type

The long data type is a primitive data type in Java used to store large integer values where an int type is not large enough to hold the desired value. To represent a long literal in Java, you append an L or l (case-insensitive) to the value. For example, long distance = 384400000L;

  • The long data type represents a 64-bit signed integer value.
  • This data type occupies 8 bytes (64 bits) in memory.
  • The range of this data type is from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
  • The range of values is from -263 to (263) – 1.
  • The default value of a long data type is 0.

Example 7:

package myProgram;
public class LongExample {
public static void main(String[] args) {
	long distanceToMoon = 384400000L; // Distance in meters.
    long population = 7800000000L;   // Approximate world population.

    System.out.println("Distance to the Moon: " + distanceToMoon + " meters");
    System.out.println("World Population: " + population);
  }
}
Output:
      Distance to the Moon: 384400000 meters
      World Population: 7800000000

Example 8: Write a Java program to calculate distance travelled by the light in 1000 days.

package myProgram;
public class Distance {
public static void main(String[] args) {
 int lightSpeed;
 long days;
 long seconds;
 long distance;
 
// Approximate speed of light in miles per second.
 lightSpeed = 186000;
 days = 1000;

 seconds = days * 24 * 60 * 60;
 distance = lightSpeed * seconds;
 System.out.print("In " +days);
 System.out.print(" days light will travel about ");
 System.out.print(distance + " miles.");
  }
}
Output:
     In 1000 days light will travel about 16070400000000 miles.

Floating Primitive Data Types in Java

Float Data Type

The float data type is a primitive data type in Java which is used to represent fractional numbers or decimal values with single precision. To represent a float literal in Java, you must append the letter f or F to the decimal number because, by default, decimal values are treated as double in Java. The characteristics of float data type is as follows:

  • The float data type is a 32-bit single precision floating-point numbers using IEEE 754 – 1985 standard.
  • It occupies 4 bytes (32 bits) size in memory.
  • The approximate range of float is from -3.4 * 1038 to 3.4 * 1038.
  • The float can store values with up to 6 – 7 decimal digits of precision.
  • The default value of a float data type is 0.0f.

Example 9:

package myProgram;
public class FloatExample {
public static void main(String[] args) {
	float pi = 3.14159f;  // Approximate value of Pi.
    float earthGravity = 9.81f; // Earth's gravity in m/s^2

    System.out.println("Value of Pi: " + pi);
    System.out.println("Earth's Gravity: " + earthGravity + " m/s^2");
  }
}
Output:
      Value of Pi: 3.14159
      Earth's Gravity: 9.81 m/s^2

Example 10:

package myProgram;
public class FloatExample {
public static void main(String[] args) {
	float num1 = 5.75f;
    float num2 = 2.50f;

    float sum = num1 + num2;
    float difference = num1 - num2;
    float product = num1 * num2;
    float quotient = num1 / num2;

    System.out.println("Sum: " + sum);
    System.out.println("Difference: " + difference);
    System.out.println("Product: " + product);
    System.out.println("Quotient: " + quotient);
  }
}
Output:
      Sum: 8.25
      Difference: 3.25
      Product: 14.375
      Quotient: 2.3

Double Data Type

The double data type is a primitive data type in Java that is used for representing decimal numbers with double precision. It is commonly used when you need high precision in calculations. It can handle approximately 15-16 decimal digits of precision.

By default, decimal numbers are treated as double in Java, so no suffix (d or D) is required for representing double literals. Following are the important characteristics of double data type in Java:

  • The double data type is a 64-bit double-precision floating-point number using the IEEE 754-1985 standard.
  • It occupies 64 bits (8 bytes) to store a value in the memory.
  • The approximate range of this data type is ±4.9 × 10⁻³²⁴ to ±1.8 × 10³⁰⁸.
  • The default value for a double data type is 0.0.

Example 11:

package myProgram;
public class DoubleExample {
public static void main(String[] args) {
	double pi = 3.141592653589793; // Value of Pi with high precision
    double earthCircumference = 40075.017; // Earth's circumference in kilometers

    System.out.println("Value of Pi: " + pi);
    System.out.println("Earth's Circumference: " + earthCircumference + " km");
  }
}
Output:
      Value of Pi: 3.141592653589793
      Earth's Circumference: 40075.017 km

The double data type also supports scientific notation, which is useful for very large or very small numbers. Let’s take an example on it.

Example 12:

package myProgram;
public class ScientificNotationExample {
public static void main(String[] args) {
	double speedOfLight = 2.998e8; // 2.998 × 10^8 m/s
    double electronMass = 9.109e-31; // 9.109 × 10^-31 kg

    System.out.println("Speed of Light: " + speedOfLight + " m/s");
    System.out.println("Mass of an Electron: " + electronMass + " kg");
  }
}
Output:
      Speed of Light: 2.998E8 m/s
      Mass of an Electron: 9.109E-31 kg

Char Data Type

The character data type (char) is a primitive type in Java which is used to store a single character, such as uppercase or lowercase letters, digits, or symbols.. All the characters in Java are represented using Unicode. Unicode is a universal international standard character encoding that represents most of the world’s written language.

The process of assigning a number for each character is called character encoding. The important characteristics of char data type in Java are as follows:

  • The char data type occupies 2 bytes (16 bits) of memory to store Unicode character.
  • The range of char type is from ‘\u0000’ (or 0) to ‘\uffff’ (or 65,535), which includes all Unicode characters.
  • The default value of a char data type is ‘\u0000’ (null character).
  • Always use the single quotes (‘) to represent char literals. It you will use double quotes (“) then it will be considered as string value.

Example 13:

package myProgram;
public class CharExample {
public static void main(String[] args) {
	char letter = 'A';         // A single character
    char digit = '5';          // A numeric character
    char symbol = '@';         // A special character
    char unicodeChar = '\u0041'; // Unicode representation of 'A'

    System.out.println("Letter: " + letter);
    System.out.println("Digit: " + digit);
    System.out.println("Symbol: " + symbol);
    System.out.println("Unicode Character: " + unicodeChar);
  }
}
Output:
     Letter: A
     Digit: 5
     Symbol: @
     Unicode Character: A

The char data type uses Unicode universal character encoding standard. You can represent characters in Unicode format using the \uXXXX syntax, where XXXX is the hexadecimal code for the character.

Example 14:

package myProgram;
public class UnicodeExample {
public static void main(String[] args) {
	char smiley = '\u263A'; // Unicode for ☺
    System.out.println("Smiley: " + smiley);
  }
}
Output:
      Smiley: ☺

Boolean Data Type

The boolean data type in Java is used to store logical values either true or false. We often use it in conditional statements, loops, and logical operations where a binary decision is required. The important characteristics of boolean data type in Java are as follows:

  • The size of the boolean data type in memory is not precisely defined in Java. However, it generally uses 1 bit internally to store the value.
  • A boolean can hold only two values: true or false.
  • The default value for a boolean variable is false.

Example 15:

package myProgram;
public class BooleanExample {
public static void main(String[] args) {
	boolean isJavaFun = true;
    boolean isSkyGreen = false;

    System.out.println("Is Java fun? " + isJavaFun);
    System.out.println("Is the sky green? " + isSkyGreen);
  }
}
Output:
     Is Java fun? true
     Is the sky green? false

List of Primitive Data Types in Java

Here, we have listed all the primitive data types in Java with its size, range, and default value.

TypeSizeMinimum ValueMaximum ValueDefault Value
byteOne byte-1281270
shortTwo bytes-32,76832,7670
intFour bytes-2,147,483,6482,147,483, 6470
longEight bytes-9,223,372,036,854,775,8089,223,372,036,854,775,8070
floatFour bytes3.4E – 0383.4E + 0380.0f
doubleEight bytes1.7E – 3081.7e + 0380.0
charTwo bytesSingle character0 to 65,535\u0000
booleanOne bitLogical or boolean valuestrue or falsefalse

Please Share Your Love.

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *