Numeric Data Types in Java

Published by

on

Integral Data Types

Integral data type is a data type that represents numeric data whose values are integers. From Java, there are 5 integral data types, byte , short, int long and char.

1. byte data type

  • byte data type is a 8 bit signed integral data type
  • Range from -128 to 127 ( -2^7 ~ 2^7 -1 ). This is the smallest integer data type
  • ex) byte b1 = 100;

2. short data type

  • short data type is a 16 bit signed integral data type
  • Range from -32768 to 32767 ( -2^15 ~ 2^15 -1 )
  • ex) short s1 = 10000;

3. int data type

  • int data type is a 32 bit signed integral data type
  • Range from -2,147,483,648 to 2,147,483,647 ( -2^31 ~ 2^31 -1 )
  • ex) int i1 = 100000;

4. long data type

  • long data type is a 64 bit signed integral data type
  • Range from -2^63 to 2^63 – 1.
  • ex) long l1 = 1000000L;

5. char data type

  • char data type is a 16 bit unsigned data type
  • It represents a Unicode character.
  • Range from 0 to 65535 (0 ~ 2^16 -1 )
  • ex) char c1 = 'A';

Floating-Point Data Types

Floating point number is a number that contains a fractional part of number. ex) 3.14, 1.23, etc

1. float data type

  • float data type is a 32 bit data type which stores floating-point number using IEEE 754 standard format 
  • It can be positive or negative
  • Range is unlimited. (from 1.4 * 10^(-45) to 3.4 * 10^38)
  • Recommended to use a float (instead of double) if you need to save memory in large arrays of floating point numbers
  • ex) float f1 = 1.2F; float f2 = -1.3F;

2. double data type

  • double data type is a 64 bit data type which stores floating-point number using IEEE 754 standard format 
  • It can be positive or negative
  • Range is unlimited
  • A double literal may optionally end with d or D
  • ex) double d1 = 1.23; double d2 = 1.23D; double d3 = -1.23D;

Type Casting

When you want to assign a value of one primitive data type to another, you can use type casting.
Java supports 2 types of type casting

  • Widening Casting (automatically) – converting a smaller type to larger type
    ex) byte -> short -> char -> int -> long -> float ->double
  • Narrowing Casting (manually) – converting a larger type to smaller type. As we are converting to a smaller type of data type, this could cause data loss.
    ex ) double myDouble = 9.78;
    int myInt = (int) myDouble; // myInt = 9
    ex )double -> float -> long -> int -> char -> short ->byte

    ex)
    int num1 = 5;
    long num2 = 25L;
    num1 = num2; // compile-error. Even though 25 is within the range of int

    If you want to assign value of a long variable to int, you will need to explicitly cast the type to int, like so :
    num1 = (int)num2; // No error
    At runtime, Java will use only the least 32 significant bits of num2 and assign the value to num1. With that being said, this can cause data loss if there is a value outside the range of int data type.

Reference

Leave a comment