
Introduction
In the world of programming, a variable A variable is a data container that acts as a location in a computer's memory, which can store a value that may change during program execution. Variables are used to represent information that must be processed, stored, and manipulated, such as numbers, text, or logical states.
On the other hand, a data type defines the nature of the value that a variable can store and specifies the operations that can be performed on that value. In Java, a strongly typed language, each variable has a specific data type (e.g., int
, double
either String
), ensuring that they are used consistently throughout the execution of the application.
1. Variables in the Java language 21
In Java, a variable is a data container with a specific type and an identifying name. Although Java has historically been a strongly typed language, since Java 10 the keyword var
to allow type inference on local variables without losing type safety. This helps reduce verbosity when the type is evident from the assigned value.
In Java, a variable is declared by indicating the tipo de dato
and a name for the variable. The basic syntax is tipo nombreDeVariable;
, see a Example with explicit declaration and type inference:
// Declaración explícita int numero = 10; // Uso de inferencia de tipos (disponible para variables locales) var mensaje = "Hola, Java 21!";
The flexibility it offers var
It serves to simplify the code, as long as it is used judiciously to maintain clarity.
2. Primitive variables in Java
Java defines eight primitive data types: byte
, short
, int
, long
, float
, double
, boolean
and char
These types store simple values and are allocated on the memory stack, allowing for efficient handling in terms of performance. Each of these types has a specific value range and should be chosen based on the application's precision and memory usage needs.
Example of declaration and use of primitive variables:
byte b = 100; // 8 bits short s = 30000; // 16 bits int i = 100000; // 32 bits long l = 10000000000L; // 64 bits (nota la 'L' al final) // Variables reales float f = 3.14F; // 32 bits (se utiliza 'F') double d = 3.141592653589793; // 64 bits
Every decision in type selection influences memory usage and computational efficiency.
3. Simple ordinal or integer data in the Java language
Integer data represents numbers without a decimal point, used for counting, indexing, and performing basic arithmetic operations. Integer types in Java are:
byte
: 8 bits (range -128 to 127)short
: 16 bits (range -32,768 to 32,767)int
: 32-bit (the most common integer type) (range -2,147,483,648 and 2,147,483,647)long
: 64 bits (for large magnitude numbers) (range -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807)
Example:
byte edad = 25; short cantidadEstudiantes = 320; int numeroDeUsuarios = 1_000_000; long distanciaEnMetros = 9_461_000_000L;
Using the right type prevents unnecessary memory usage, which is especially important in resource-constrained applications.
4. Real simple data in Java language
To represent numbers with decimal part, Java has mainly two types:
float
: Single precision (32 bits). A suffix must be usedF
(eitherf
) in the literal.double
: Double precision (64-bit); this is the default type for operations on real numbers.
Example:
float temperatura = 36.6F; double distancia = 12345.6789;
It is vital to note that floating point representation can introduce small inaccuracies into mathematical calculations.
5. Boolean and char variables
Boolean
The guy boolean
stores logical values, and can only contain true
either false
. It is mainly used in conditional expressions and control structures.
boolean esValido = true; if (esValido) { System.out.println("La condición es verdadera."); }
Char
The guy char
represents a single Unicode character and is declared using single quotes.
char letra = 'A'; char simbolo = '€';
These types are essential for controlling program logic and character representation.
6. Variable names
Choosing meaningful and correct variable names is crucial for code clarity and maintainability. The basic rules are:
- They must start with a letter, an underscore
_
or a dollar sign$
(although the latter is rarely used). - They may include digits, but No must start with them.
- Are case-sensitive (For example,
edad
andEdad
are considered different). - It is recommended to use the convention camelCase for compound nouns (example:
numeroDeEstudiantes
).
Example:
int numeroDeEstudiantes = 30; double precioTotal = 99.99; boolean esActivo = false;
7. Numeric literals
Literals are direct representations of numbers in code. Different number bases can be used in Java:
Decimal:
int decimal = 50;
Hexadecimal: The prefix is used 0x either 0X.
int hexadecimal = 0x1A; // 26 en decimal
Binary: Since Java 7 the prefix is used 0b either 0B.
int binario = 0b1101; // 13 en decimal
Octal: Represented with a 0 initial.
int octal = 075; // 61 en decimal
These various representations are useful when performing bit-wise operations or when you want to improve the readability of certain values.
8. Scope of existence of the variables
Scope determines the visibility and duration of a variable within the program. In Java, there are three main types:
Local variables: Declared within a method, constructor, or block. They only exist within that block.
public void metodo() { int contador = 0; // Variable local }
Instance variables: They are the non-static attributes of a class; each object has its own copy.
public class Estudiante { private String nombre; // Variable de instancia public Estudiante(String nombre) { this.nombre = nombre; } }
Class variables (static): Declared with the static modifier, they belong to the class and are shared by all instances.
public class Configuracion { public static final String VERSION = "1.0.0"; // Variable de clase public static void mostrarVersion() { System.out.println("Versión: " + VERSION); } }
Understanding scope is essential to avoiding errors and managing memory properly.
9. The String class
Although used to represent text, variables of type String
In Java they are objects of the class String
, not primitive types. A key feature is that strings are immutable: Once created, their value cannot be modified. This improves security and allows for efficient use of the String pool.
In Java, a String variable It is a variable that stores a sequence of characters and, unlike primitive types, is an object of the class String
This implies the following:
- Immutability: Once a string is created, its contents cannot be altered. If you perform an operation that "modifies" the string, a new object is actually created.
String
. - Useful methods: The class
String
It comes equipped with numerous methods that make text manipulation easier, such aslength()
,toUpperCase()
,substring()
,replace()
, among others. - Literalness: Strings are defined by enclosing the text in double quotes.
- Chain Pool: Java manages a pool of strings, which allows instances of strings to be reused.
String
when identical literals are used, saving memory and increasing efficiency.
String saludo = "Hola, mundo!";
In summary, the variables String
They are essential for text handling in Java and their immutable nature along with the available methods makes them a powerful tool for working with textual data.
public class EjemploString { public static void main(String[] args) { String saludo = "Hola"; // Concatenación de cadenas saludo = saludo + ", mundo!"; System.out.println(saludo); // Imprime "Hola, mundo!" // Uso de métodos de String System.out.println("Longitud: " + saludo.length()); System.out.println("En mayúsculas: " + saludo.toUpperCase()); } }
10 What is a constant variable?
A constant variable It is an identifier to which a value is assigned that cannot be modified once set. In Java, the way to define a constant is by using the keyword final
. When declaring a variable as final
, its value is guaranteed to remain unchanged throughout the execution of the program, which helps to avoid accidental modifications and to clarify the purpose of certain fixed values in the code.
By convention, constant names are written entirely in capital letters, using underscores to separate words. This makes them easy to identify in code and distinguish them from variables whose values can change.
Example of a constant variable:
final double PI = 3.14159; final int MESES_EN_UN_AÑO = 12;
In these examples, PI
and MESES_EN_UN_AÑO
They are constants. Once assigned an initial value (3.14159 and 12, respectively), that value cannot be modified anywhere in the program. This makes them ideal for representing universal or fixed values that shouldn't change, such as mathematical parameters, settings, or any data used globally in the application.
11. The variables var in Java
The keyword var
, introduced in Java 10 and present in Java 21, allows the compiler to infer the type of local variables based on the assigned value. This reduces redundancy in the declaration, as long as the type is obvious to the reader.
Advantages and Disadvantages of Using var
Advantages:
- Reduce verbosity: It is not necessary to repeat the type when it is deduced from the assigned value.
- Improves maintainability: Facilitates refactoring in complex expressions and avoids redundancies.
- Cleaner code: Especially useful when working with long or generic types.
Disadvantages:
- Loss of clarity: In cases where the type is not obvious, it can make it difficult to understand the code.
- Limited to local variables: It cannot be used in class attributes or method parameters.
- Potential ambiguity: Its indiscriminate use can lead to errors if the inferred type is not the expected one.
Example of use:
var numero = 100; // Se infiere como int var mensaje = "Hola, Java"; // Se infiere como String
The proper use of var
makes it easier to write code, without losing security at compile time.
12. Table of data types in Java with their characteristics
Below is a summary table of the main data types in Java:
Data Type | Memory Size | Range / Accuracy | Characteristics |
---|---|---|---|
byte | 8 bits | -128 to 127 | Integer; ideal for operations with few values and saving memory in large arrays. |
short | 16 bits | -32,768 to 32,767 | Integer; useful in resource-limited settings. |
int | 32 bits | -2,147,483,648 and 2,147,483,647 | Default integer type for most numeric operations. |
long | 64-bit | -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 | Integer for very large values; requires suffix L in literals. |
float | 32 bits | Approximately 1.4E-45 to 3.4028235E38 (6-7 decimal places) | Single-precision floating point; requires suffix F . |
double | 64-bit | Approximately 4.9E-324 to 1.7976931348623157E308 (15 decimal places) | Double-precision floating point; default type for real numbers. |
boolean | Not exactly defined | true either false | Logical value; actual size depends on the JVM implementation. |
char | 16 bits | 0 to 65,535 (Unicode values) | Represents a single Unicode character, ideal for letters, digits, and symbols. |
String | Variable (depends on content) | N/A | Class for handling text; immutable, with numerous manipulation methods. |
var | Not applicable | N/A | Keyword for inferring the type of local variables; the type is determined at compile time. |
\* The size of a boolean
varies depending on the JVM implementation.
13. Practical examples of using each data type in Java
Below are examples of how to declare and print variables of each type:
byte
byte edad = 25; System.out.println("Edad (byte): " + edad);
short
short cantidadEstudiantes = 320; System.out.println("Estudiantes (short): " + cantidadEstudiantes);
int
int numeroDeUsuarios = 1_000_000; System.out.println("Usuarios (int): " + numeroDeUsuarios);
long
long distancia = 9_461_000_000L; System.out.println("Distancia (long): " + distancia);
float
float temperatura = 36.6F; System.out.println("Temperatura (float): " + temperatura);
double
double pi = 3.141592653589793; System.out.println("Valor de pi (double): " + pi);
boolean
boolean esValido = true; System.out.println("Es válido (boolean): " + esValido);
char
char letra = 'A'; System.out.println("Letra (char): " + letra);
String
String saludo = "Hola, mundo!"; System.out.println("Saludo (String): " + saludo);
var (inferred)
var mensaje = "Inferido como String"; System.out.println("Mensaje (var): " + mensaje);
14. Complete Java program with all data types
The following is a demonstration program that declares variables of all the types mentioned and prints their values:
public class TiposDeDatos { public static void main(String[] args) { // Declaración de variables de los tipos primitivos byte b = 100; // 8 bits short s = 30000; // 16 bits int i = 100000; // 32 bits long l = 10000000000L; // 64 bits (se utiliza sufijo L) float f = 3.14F; // 32 bits (se utiliza sufijo F) double d = 3.141592653589793; // 64 bits boolean bool = true; // Valor lógico, true o false char c = 'A'; // Un solo carácter // Declaración de variables de referencia String str = "Hola, mundo!"; // Cadena de caracteres // Uso de var para inferir el tipo en variables locales var varInt = 123; // Se infiere como int var varString = "Inferido como String"; // Se infiere como String var varDouble = 99.99; // Se infiere como double // Impresión de cada variable sin utilizar ningún método de la clase String System.out.println("byte: " + b); System.out.println("short: " + s); System.out.println("int: " + i); System.out.println("long: " + l); System.out.println("float: " + f); System.out.println("double: " + d); System.out.println("boolean: " + bool); System.out.println("char: " + c); System.out.println("String: " + str); System.out.println("var (int): " + varInt); System.out.println("var (String): " + varString); System.out.println("var (double): " + varDouble); } }
Explanation:
- Variables of each type (primitive and reference) are declared.
- Variables are used with
var
to demonstrate type inference. - The value of each variable is printed.
We create a file called TiposDeDatos.java
, we compile and run with javac
and java
:
$ javac TiposDeDatos.java // Sin errores de compilación. // Compilamos... $ java TiposDeDatos // Resultado por consola: byte: 100 short: 30000 int: 100000 long: 10000000000 float: 3.14 double: 3.141592653589793 boolean: true char: A String: Hola, mundo! var (int): 123 var (String): Inferido como String var (double): 99.99
15. Different ways to define a variable in Java
Java allows you to declare variables in a variety of ways depending on the context and need:
15.1. Declaration and Initialization in a Single Instruction
The most common form, where the variable is declared and assigned a value immediately.
int numero = 10; String nombre = "Soraya"; double precio = 99.99;
15.2. Declaration without Initialization (Post Assignment)
The variable is declared without immediately assigning a value to it, to initialize it later. It is essential to assign a value before using it, especially with local variables.
int contador; contador = 5; String mensaje; mensaje = "Buenas tardes";
15.3. Multiple Declarations on a Single Line
Multiple variables of the same type can be declared on a single line, separated by commas.
int a = 1, b = 2, c = 3;
15.4. Block and Loop Declarations
Variables can be declared within blocks or loops, limiting their scope to the block in question.
for (int i = 0; i < 10; i++) { System.out.println("Valor de i: " + i); }
15.5. Instance and Class Variables
Instance Variables: Declared in the class body but outside of methods. Each object has its own copy.
public class Persona { private String nombre; // Variable de instancia public Persona(String nombre) { this.nombre = nombre; } }
Class Variables (Static): Declared with the keyword static
, belong to the class and are shared by all instances.
public class Configuracion { public static final String APP = "MiAplicacion"; }
15.6. Declaration of Immutable Variables (Constants)
A constant variable It is one to which a unique value is assigned that can't change during the execution of the program.
- The keyword is used
final
to declare them. - By convention, their names are written in capital letters with underscores to separate words.
final double PI = 3.14159; final int MESES_EN_UN_AÑO = 12;
15.7. Declaration with Type Inference Using var
With var
The compiler infers the type of the variable based on the assigned value.
var edad = 25; // Se infiere como int var mensaje = "Hola, Mundo!"; // Se infiere como String
Each declaration method has its use depending on the context, and the correct choice contributes to the clarity, scalability, and maintainability of the code.
16. Converting between primitive data types in Java
In Java, there are two main ways to convert data from one type to another when working with primitive types:
- Implicit (automatic) conversion
- Explicit conversion (manual or "casting")
The choice between these methods depends on the size and precision of the data type we want to convert. Below, both concepts are explained with easy-to-understand examples.
16.1. Implicit (automatic) conversion
Implicit conversion occurs when the Java compiler Automatically converts a smaller data type to a larger one. This happens because the larger type has enough space to store the value of the smaller type without losing information.
Data types in Java have a size order, from smallest to largest: byte → short → int → long → float → double
Example of implicit conversion:
public class ConversionImplicita { public static void main(String[] args) { int numeroEntero = 100; // Tipo int double numeroDecimal = numeroEntero; // Conversión automática a double System.out.println("Número entero (int): " + numeroEntero); System.out.println("Número decimal (double): " + numeroDecimal); } }
Explanation: The value of the type int
(100
) is automatically converted to double
, without the need for any casting. There is no data loss because double
has greater precision and size than int
.
Another example with float
and double
:
float numeroFlotante = 3.14F; // Tipo float double numeroDoble = numeroFlotante; // Conversión automática a double System.out.println("Número flotante (float): " + numeroFlotante); System.out.println("Número doble (double): " + numeroDoble);
Again, the conversion happens smoothly because double
has more storage capacity than float
.
16.2. Explicit conversion (manual or "casting")
Explicit conversion is when the programmer tells the compiler to convert a larger type to a smaller one. This can cause data loss if the information from the larger type doesn't fit into the smaller type.
To perform this conversion, the following is used: casting, which consists of placing the data type in parentheses before the variable we want to convert.
Explicit conversion example:
public class ConversionExplicita { public static void main(String[] args) { double numeroDecimal = 9.99; // Tipo double int numeroEntero = (int) numeroDecimal; // Conversión manual a int System.out.println("Número decimal (double): " + numeroDecimal); System.out.println("Número entero (int después de casting): " + numeroEntero); } }
Explanation: The number 9.99
is stored as double
, but when converting it to int
, the decimal part is lost and only remains 9
. This is a classic example of loss of accuracy when casting double
to int
.
Another example with long
and short
:
long numeroGrande = 100000L; // Tipo long short numeroPequeño = (short) numeroGrande; // Conversión explícita System.out.println("Número grande (long): " + numeroGrande); System.out.println("Número pequeño (short después de casting): " + numeroPequeño);
Here the manual conversion of long
to short
it works, but if the number long
would have been greater than the range of short
(-32,768 to 32,767), the result would be incorrect due to data overflow (overflow).
16.3 Conversion Summary
Conversion rate | How does it happen? | Can information be lost? | Example |
---|---|---|---|
Implicit (automatic) | Java does it without programmer intervention | No, because the destination type is bigger | int → double , float → double |
Explicit (manual / casting) | The programmer indicates the conversion with (tipo) | Yes, if the destination type is smaller | double → int , long → short |
Conversion Tips:
- Use implicit conversions when Java can handle the change smoothly.
- Use explicit casting only when you are sure that there will be no significant data loss.
- Be careful with the conversion of
double
toint
, since it eliminates the decimal part. - Always check the range of values before converting larger types to smaller ones to avoid errors or overflows.
These conversion concepts are fundamental in Java, since it is often necessary to convert data between different types depending on the program logic.
Summary
This tour has covered the fundamental aspects of managing variables and data types in Java 21:
- Variables in Java: They are data containers with a defined type and a name. The introduction of
var
allows the compiler to infer the type of local variables, reducing verbosity without compromising compile-time safety. - Primitive Types and Simple Data: Included
byte
,short
,int
,long
,float
,double
,boolean
andchar
, each optimized for different purposes (storage, calculations and representation). - Integer and Real Data: They are used to store numbers with and without decimals, respectively, essential in every application.
- Boolean and Char variables: They handle logical values and single characters.
- Nomenclature and Literals: Correct naming and literal representation are vital to code readability.
- Scope of Variables: Understanding scope (local, instance, or class) is essential to avoid errors.
- The String Class: It is used to handle character sequences in an immutable way.
- Use of
var
: Provides flexibility through type inference, with advantages and some limitations. - Declaration of Constants: Through
final
Constant variables are defined, whose value does not change during execution, providing stability and clarity to the program. - Comparative Table and Practical Examples: The characteristics of each type are summarized and specific examples are offered, culminating in a complete program.
- Ways to Declare Variables: Various methods are explored (immediate declaration, multiple, in loops, instance/class variables, constants and use of
var
) to suit different programming scenarios.
Mastering these concepts is essential for writing efficient, readable, and maintainable code, serving as a foundation for developing robust and scalable Java applications.