Introducción a los primitivos de Java

1. Información general

El lenguaje de programación Java presenta ocho tipos de datos primitivos.

En este artículo, recordaremos qué son los primitivos y los repasaremos.

2. Tipos de datos primitivos

Las ocho primitivas definidas en Java son int , byte , short , long , float , double , boolean y char; no se consideran objetos y representan valores sin procesar.

Se almacenan directamente en la pila (consulte este artículo para obtener más información sobre la administración de memoria en Java).

Echemos un vistazo al tamaño de almacenamiento, los valores predeterminados y ejemplos de cómo usar cada tipo.

Comencemos con una referencia rápida:

Tipo Tamaño (bits) Mínimo Máximo Ejemplo
byte 8 -27 27– 1 byte b = 100;
corto dieciséis -215 215– 1 corto s = 30_000;
En t 32 -231 231– 1 int i = 100_000_000;
largo 64 -263 263– 1 largo l = 100_000_000_000_000;
flotador 32 -2-149 (2-2-23) · 2127 flotar f = 1.456f;
doble 64 -2-1074 (2-2-52) · 21023 doble f = 1,456789012345678;
carbonizarse dieciséis 0 216– 1 char c = 'c';
booleano 1 - - booleano b = verdadero;

2.1. En t

El primer tipo de datos primitivo que vamos a cubrir es int . También conocido como un número entero, el tipo int contiene una amplia gama de valores numéricos no fraccionarios.

Específicamente, Java lo almacena usando 32 bits de memoria . En otras palabras, puede representar valores de -2,147,483,648 (-231) a 2,147,483,647 (231-1).

En Java 8, es posible almacenar un valor entero sin signo hasta 4.294.967.295 (232-1) mediante el uso de nuevas funciones auxiliares especiales.

Simplemente podemos declarar un int simplemente:

int x = 424_242; int y;

El valor predeterminado de un int declarado sin una asignación es 0.

Si la variable está definida en un método, debemos asignar un valor antes de poder usarlo.

Podemos realizar todas las operaciones aritméticas estándar en int s. Solo tenga en cuenta que los valores decimales se cortarán al realizarlos en números enteros.

2.2. byte

byte es un tipo de datos primitivo similar a int , excepto que solo ocupa 8 bits de memoria . Entonces, ¿por qué lo llamamos byte? Debido a que el tamaño de la memoria es tan pequeño, el byte solo puede contener los valores de -128 (-27) a 127 (27 - 1).

Podemos crear byte :

byte b = 100; byte empty;

El valor predeterminado de byte también es 0.

2.3. corto

La siguiente parada en nuestra lista de tipos de datos primitivos en Java es breve .

Si queremos ahorrar memoria y el byte es demasiado pequeño, podemos usar el tipo a medio camino entre los dos: short .

Con 16 bits de memoria, es la mitad del tamaño de int y el doble de byte . Su rango de valores posibles es de -32,768 (-215) a 32,767 (215 - 1).

short se declara así:

short s = 202_020; short s;

También similar a los otros tipos, el valor predeterminado es 0. También podemos usar toda la aritmética estándar.

2.4. largo

Nuestro último tipo de datos primitivo relacionado con los números enteros es largo .

long es el hermano mayor de int . Se almacena en 64 bits de memoria para que pueda contener un conjunto significativamente mayor de valores posibles.

Los posibles valores de un largo están entre -9,223,372,036,854,775,808 (-263) a 9,223,372,036,854,775,807 (263 - 1).

Podemos simplemente declarar uno:

long l = 1_234_567_890; long l;

Al igual que con otros tipos de enteros, el valor predeterminado también es 0. Podemos usar toda la aritmética en long que funcione en int .

2.5. flotador

Representamos números fraccionarios básicos en Java usando el tipo flotante . Este es un número decimal de precisión simple. Lo que significa que si superamos los seis puntos decimales, este número se vuelve menos preciso y más estimado.

En la mayoría de los casos, no nos importa la pérdida de precisión. Pero, si nuestro cálculo requiere precisión absoluta (es decir, operaciones financieras, aterrizaje en la luna, etc.) necesitamos utilizar tipos específicos diseñados para este trabajo. Para obtener más información, consulte la clase Java Big Decimal.

This type is stored in 32 bits of memory just like int. However, because of the floating decimal point its range is much different. It can represent both positive and negative numbers. The smallest decimal is 1.40239846 x 10-45, and the largest value is 3.40282347 x 1038.

We declare floats the same as any other type:

float f = 3.145f; float f;

And the default value is 0.0 instead of 0. Also, notice we add the f designation to the end of the literal number to define a float. Otherwise, Java will throw an error because the default type of a decimal value is double.

We can also perform all standard arithmetic operations on floats. However, it's important to note that we perform floating point arithmetic very differently than integer arithmetic.

2.6. double

Next, we look at double – its name comes from the fact that it's a double-precision decimal number.

It's stored in 64 bits of memory. Which means it represents a much larger range of possible numbers than float.

Although, it does suffer from the same precision limitation as float does. The range is 4.9406564584124654 x 10-324 to 1.7976931348623157 x 10308. That range can also be positive or negative.

Declaring double is the same as other numeric types:

double d = 3.13457599923384753929348D; double d;

The default value is also 0.0 as it is with float.Similar to float, we attach the letter D to designate the literal as a double.

2.7. boolean

The simplest primitive data type is boolean. It can contain only two values: true or false. It stores its value in a single bit.

However, for convenience, Java pads the value and stores it in a single byte.

Declare boolean like this:

boolean b = true; boolean b;

Declaring it without a value defaults to false. boolean is the cornerstone of controlling our programs flow. We can use boolean operators on them (i.e., and, or, etc.).

2.8. char

The final primitive data type to look at is char.

Also called a character, char is a 16-bit integer representing a Unicode-encoded character. Its range is from 0 to 65,535. Which in Unicode represents ‘\u0000' to ‘\uffff'.

For a list of all possible Unicode values check out sites like Unicode Table.

Let's now declare a char:

char c = 'a'; char c = 65; char c;

When defining our variables, we can use any character literal, and they will get automatically transformed into their Unicode encoding for us. A characters default value is ‘/u0000'.

2.9. Overflow

The primitive data types have size limits. But what happens if we try to store a value that's larger than the maximum value?

We run into a situation called overflow.

When an integer overflows, it rolls over to the minimum value and begins counting up from there.

Floating point number overflow by returning Infinity. When they underflow, they return 0.0.

Here's an example:

int i = Integer.MAX_VALUE; int j = i + 1; // j will roll over to -2_147_483_648 double d = Double.MAX_VALUE; double o = d + 1; // o will be Infinity

Underflow is the same issue except if we store a value smaller than the minimum value.

2.10. Autoboxing

Each primitive data type also has a full Java class implementation that can wrap it. For instance, the Integer class can wrap an int. There is sometimes a need to convert from the primitive type to its object wrapper (e.g., using them with generics).

Afortunadamente, Java puede realizar esta conversión automáticamente. A este proceso lo llamamos Autoboxing . Aquí hay un ejemplo:

Character c = 'c'; Integer i = 1;

3. Conclusión

En este tutorial, hemos cubierto los ocho tipos de datos primitivos admitidos en Java.

Estos son los bloques de construcción utilizados por la mayoría, no todos los programas Java que existen, por lo que vale la pena comprender cómo funcionan.