Java Numbers

Java Numbers are declared by primitive data types such as  byte, short, int, long, float, double, etc.

Primitive number types are divided into two groups

Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals. Valid types are byte, short, int and long. Which type you should use, depends on the numeric value.

Floating point types represents numbers with a fractional part, containing one or more decimals. There are two types: float and double.

Integer Types

1. Byte

The byte data type can store whole numbers from -128 to 127. This can be used instead of int or other integer types to save memory when you are certain that the value will be within -128 and 127:
Example :

byte byteNum = 50;
System.out.println(byteNum);

2. Short
The short data type can store whole numbers from -32768 to 32767.

Example :

short shortNum = 2300;
System.out.println(shortNum);

3. Int

The int data type can store whole numbers from -2147483648 to 2147483647. The int data type is the preferred data type when we create variables with a numeric value.

Example :

int intNum = 546;
System.out.println(intNum);

4. long

The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807. This is used when int is not large enough to store the value. Note that you should end the value with an "L":

Example :

long longNum = 7455645645655L;
System.out.println(longNum);

 

Floating Point Types

The float and double data types can store fractional numbers.

1. float

The precision of float is only six or seven decimal digits.  You should end the value with an "f" for floats.

Example :

float floatNum = 8.54f;
System.out.println(floatNum);

1. double

The precision of double variables are 15 digits..  You should end the value with an "d" for floats.

Example :

double doubleNum = 45.5d;
System.out.println(doubleNum);


 

Example :

class Aryatechno {
public static void main(String[] args) {

byte byteNum = 50;
System.out.println(byteNum);
short shortNum = 2300;
System.out.println(shortNum);
int intNum = 546;
System.out.println(intNum);
long longNum = 7455645645655L;
System.out.println(longNum);
float floatNum = 8.54f;
System.out.println(floatNum);
double doubleNum = 45.5d;
System.out.println(doubleNum);


}
}

Output :

50
2300
546
7455645645655
8.54
45.5

Comments

Leave a Reply

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

67471