Primitive Data Types in Java

From time to time I find myself searching online for the ranges of the data types in whichever programming language I happen to be using.

It is important to choose the adequate data type for our variables depending on what we’re going to store.

If we’re just thinking on storing a number between 1 and 10, it would be a waste of memory to declare the variable as int.

The table below shows the primitive data types available in Java, for your reference.

Type Description Bytes Range Default value
byte Very short integer 1 -128 to 127 0
short Short integer 2 -32,768 to 32,767 0
int Integer 4 -2,147,483,648 to 2,147,483,647 0
long Long integer 8 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 0L
float Single-precision, floating-point number with up to 7 significant digits 4 +/-1.4E-45 (+/-1.4 times 10-45) to +/-3.4E38 (+/-3.4 times 1038 0.0f
double Double-precision, floating-point number with up to 16 significant digits 8 +/-4.9E-324 (+/-4.9 times 10-324) to +/-1.7E308 (+/-1.7 times 10308) 0.0d
char Unicode character 2 \u0000 to \uFFFF ‘\u0000’
boolean True or False value 1 true or false false

Examples

public class Example {

	public static void main(String[] args) {
		//declare variables
		byte month = 12;
		int counter = 0;
		double pi = 3.1415926535897932384626433832795;
		float rate = 4.25e2F;
		char letter = 'Z';
		boolean found = true;

		//print values
		System.out.println(month); //will print 12
		System.out.println(counter); //will print 0
		System.out.println(pi); //will print 3.141592653589793
		System.out.println(rate); //will print 425.0
		System.out.println(letter); //will print Z
		System.out.println(found); //will print true
	}

}
Get Free Updates
Related Posts
Comments