Convert bytes to KB,MB and GB using Java Program

In many cases, we might get the memory or size of the file/table in bytes.The simple java program can able to convert the bytes to KB,MB and GB using traditional way of calculation.Before we look into the program, lets understand the conversion method to change the memory unit from one to another.

Memory units

The data (File,Image,text,number..etc) is stored in the memory in the form of bits such as 0 & 1. Here the memory units helps to measure the storage of those data. The units are defined as below.

  • 1 Byte is equal to 8 bits
  • 1 Kilobyte(KB) is equal to 1024 Bytes
  • 1 Megabyte(MB) is equal to 1024 Kilobytes
  • 1 Gigabyte(GB) is equal to 1024 Megabytes
  • 1 Terabyte(TB) is equal to 1024 Gigabytes
  • 1 Petabyte(PB) is equal to 1024 Terabytes.

For example, we have a file size in terms of bytes and it is more than 1024 bytes. In that case, we can just divide that value by 1024 to get the size in Kilobytes(KB).

Similarly if we divide the Kilobytes by 1024 , It will give the Megabytes(MB). The same calculation is applicable for the remaining units.

Java Program to convert bytes to KB,MB and GB

Output:

Recommended Articles