DEV Community

Cover image for Datatypes in Java
Sasireka
Sasireka

Posted on

Datatypes in Java

Datatypes in java

  • Java is a statically-typed language, meaning every variable must be declared with a data type before use.

  • These types are divided into two main categories: Primitive and Non-Primitive.

Primitive datatype:

  • A primitive data type in Java is a basic, predefined data type that stores simple, raw values directly in memory (on the stack), rather than a reference to an object.

  • Java has eight primitive data types:

1) byte

  • An 8-bit signed integer used for saving memory in large arrays, with a range from -128 to 127.

  • Example: byte age = 25;

2) short

  • A 16-bit signed integer, used when a byte is insufficient, with a range from -32,768 to 32,767.

  • Example: short temp = -200;

3) int

  • A 32-bit signed integer and the most commonly used integer type, with a range of approximately -2.1 billion to +2.1 billion.

  • Example: int population = 2000000;

4) long

  • A 64-bit signed integer for values that exceed the range of an int. Long literals should be suffixed with an L or l (e.g., 100L).

  • Example: long worldPopulation = 7800000000L;

5) float

  • A single-precision 32-bit floating-point type for fractional numbers. It offers 6 to 7 decimal digits of precision and literals require an F or f suffix (e.g., 3.14f).

  • Example: float pi = 3.14f;

6) double

  • A double-precision 64-bit floating-point type that is the default for decimal numbers in Java. It offers about 15 decimal digits of precision.

  • Example: double pi = 3.141592653589793;

7) char

  • A single 16-bit Unicode character (e.g., 'A', '%'). It can be created using single quotes, Unicode escape sequences (\u0000), or integer values.

  • Example: char symbol = '$';

8) boolean

  • Represents one of two logical values: true or false. It is typically used for simple flags or conditional logic.

  • Example: boolean answer = true;

Top comments (0)