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.

edad
int
25
0x7FF...1234
nombre
String
"Ana"
0x7FF...5678
precio
double
19.99
0x7FF...9ABC

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;
edad int ?

Variable declared but with no value assigned

2. Initialization

Assign initial value

int edad = 25;
edad int 25

Variable declared and initialized

3. Assignment

Change the stored value

edad = 26;
edad int 26

Updated value

Practice the Declaration

Variable Editor
1
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 bits
Description

Signed 8-bit integer. Ideal for saving memory when working with small values.

Range
-128
127
Minimum: -128 Maximum: 127 Possible values: 256
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

byte
short
int
long
float
double
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

Original Value
127.8
double
Converted Value
127
int
Loss
0.8
decimals
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
VS

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
Score: 0/6

Variable Scope

Block Scope

Variables declared inside { }

public void metodo() {
int x = 10;
System.out.println(x); // ✅ correcto
}
System.out.println(x); // ❌ Error
Only visible here
x = 10

Class Scope

Variables declared at class level

public class MiClase {
int contador = 0;
public void metodo1() {
contador++; // ✅ correcto
}
public void metodo2() {
contador--; // ✅ correcto
}
}

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);
    }
}
Global Scope
claseVariable 100
Method main()
mainVariable 50
args []
Block if
bloqueVariable 25
1 claseVariable declared = 100
4 mainVariable declared = 50
7 bloqueVariable declared = 25
15 bloqueVariable no longer exists

Practical Exercises

Age Calculator

Declare variables to calculate age in different units:

  1. Create a variable int anioNacimiento with your birth year
  2. Create a variable int anioActual with the current year
  3. Calculate the age in years and store it in int edadAnios
  4. Calculate the age in months (approximately)
  5. 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 final for 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;

Knowledge Test

1
2
3
4
5

What is the size in bytes of the int type?