Variables y Tipos de Datos en Java
Learn to store and manipulate information in your programs
What is a Variable?
A variable is like a box
It stores data that you can use and modify while the program runs.
Technical Definition:
A variable is a space in memory reserved to store a value that can change while the program runs.
Name
Unique identifier to access the variable
edad, nombre, contador
Type
Determines what type of data it can store
int, String, double
Value
Data stored in the variable
25, "Ana", 19.99
Address
Location in the computer's memory
0x7FF...1234
Variable Declaration
1. Declaration
Reserve space in memory
int edad;
Variable declared but with no value assigned
2. Initialization
Assign initial value
int edad = 25;
Variable declared and initialized
3. Assignment
Change the stored value
edad = 26;
Updated value
Practice the Declaration
2
3
4
5
6
Memory State:
Output:
Run the code to see the output
Challenge:
Try declaring three variables:
String nombre,
double precio,
boolean activo
Primitive Data Types
Integer Numeric Types
Decimal Numeric Types
Other Types
byte
8 bitsDescription
Signed 8-bit integer. Ideal for saving memory when working with small values.
Range
Usage Examples
byte edad = 25;
A person's age
byte temperatura = -5;
Temperature in degrees
byte contador = 100;
Small counter
Common Errors
byte numero = 200; // Error: fuera de rango
200 exceeds the maximum of 127 that a byte can store
Bit Calculator
Sign: 0 (positive)
Value: 25
Primitive Type Comparison
| Type | Size | Range | Default Value | Example | Typical Use |
|---|---|---|---|---|---|
byte |
8 bits | -128 to 127 | 0 | byte b = 100; |
Files, raw data |
short |
16 bits | -32,768 to 32,767 | 0 | short s = 1000; |
Memory saving |
int |
32 bits | -2^31 to 2^31-1 | 0 | int i = 100000; |
General integers |
long |
64 bits | -2^63 to 2^63-1 | 0L | long l = 100000L; |
Large numbers |
float |
32 bits | ±3.4E-38 to ±3.4E+38 | 0.0f | float f = 3.14f; |
Single-precision decimals |
double |
64 bits | ±1.7E-308 to ±1.7E+308 | 0.0d | double d = 3.14159; |
Double-precision decimals |
char |
16 bits | '\u0000' to '\uffff' | '\u0000' | char c = 'A'; |
Unicode characters |
boolean |
1 bit* | true / false | false | boolean b = true; |
Logical values |
Type Conversion (Casting)
Implicit Conversion
Automatic, from lower to higher precision
int entero = 100;
double decimal = entero; // 100.0 (implícito)
Explicit Conversion
Manual, from higher to lower precision (casting)
double precio = 19.99;
int precioEntero = (int) precio; // 19 (truncado)
Loss of precision when converting to smaller types
Casting Simulator
Generated Code:
double valorOriginal = 127.8;
int valorConvertido = (int) valorOriginal;
Variables vs Constants
Variable
Its value can change during execution
int contador = 0;
contador = 1; // ✅ Permitidocontador = 2; // ✅ Permitido
When to use it?
- Counters
- Calculation results
- User input
- Changing state
Constant (final)
Its value CANNOT change after being initialized
final double PI = 3.14159;
PI = 3.14; // ❌ ERROR: No se puede modificar
When to use it?
- Mathematical values (π)
- Fixed settings
- Days of the week
- Values that shouldn't change
Game: Identify the Constants
Drag each value to the correct category:
Math.PI
edadUsuario
DIAS_SEMANA
saldoCuenta
VELOCIDAD_LUZ
temperatura
Constants (final)
Variables
Variable Scope
Block Scope
Variables declared inside { }
Class Scope
Variables declared at class level
Scope Explorer
public class ScopeDemo {
// Variable de clase static int claseVariable = 100;
public static void main(String[] args) {
// Variable local al método main int mainVariable = 50;
if (true) {
// Variable de bloque if int bloqueVariable = 25;
System.out.println("Dentro del if:");
System.out.println("claseVariable: " + claseVariable);
System.out.println("mainVariable: " + mainVariable);
System.out.println("bloqueVariable: " + bloqueVariable);
}
// bloqueVariable no es accesible aquí // System.out.println(bloqueVariable); // ❌ Error
System.out.println("Fuera del if:");
System.out.println("claseVariable: " + claseVariable);
System.out.println("mainVariable: " + mainVariable);
}
}
Practical Exercises
Age Calculator
Declare variables to calculate age in different units:
- Create a variable
int anioNacimientowith your birth year - Create a variable
int anioActualwith the current year - Calculate the age in years and store it in
int edadAnios - Calculate the age in months (approximately)
- Calculate the age in days (approximately)
Mini-Challenge: Correct Declaration
Select the correct variable declarations:
Summary and Best Practices
Naming Rules
- Use camelCase:
miVariable - Starts with a letter or _
- Don't use reserved words
- Descriptive names
- Avoid generic names
Common Errors
- Not initializing variables
- Using incorrect types
- Forgetting the semicolon
- Incorrect scope
- Unnecessary casting
Professional Tips
- Use
finalfor constants - Choose the most appropriate type
- Initialize when declaring
- Document complex variables
- Use self-explanatory names
Quick Reference Sheet
Basic Declaration:
tipo nombre;
tipo nombre = valor;
Primitive Types:
int, double, boolean, char
byte, short, long, float
Casting:
// Implícito (automático)int a = 10;
double b = a;
// Explícito (manual)double x = 9.99;
int y = (int) x;
Constants:
final double PI = 3.14159;
final int MAX_USUARIOS = 100;