πŸ’©

programierds

PROGRAMIERDS_OS // JAVA_SUBPROGRAMS

Subprograms

In Java, subprograms are reusable blocks of code that perform a specific task. They are mainly classified into functions (return a value) and procedures (do not return a value, typically declared with void).

01 // BASIC STRUCTURE

1. Basic Structure

General syntax of a function in Java:

tipoDeRetorno nombreFuncion(Tipo parametro1, Tipo parametro2) {
  // cuerpo del mΓ©todo
  return valor; // solo si tipoDeRetorno no es void
}
02 // PROCEDURE

2. Procedure (void method)

A procedure performs actions but does not return a value:

void imprimirMensaje(String msg) {
  System.out.println(msg);
}

public static void main(String[] args) {
  imprimirMensaje("Hola desde un procedimiento");
}
03 // FUNCTION

3. Function (subprogram with return)

A function performs a calculation and returns a result:

int sumar(int a, int b) {
  return a + b;
}

public static void main(String[] args) {
  int r = sumar(3, 5);
  System.out.println("Suma: " + r);
}
04 // PARAMETERS

4. Parameters and Pass by Value

In Java, primitive types are passed by value. To modify the original data, you use references or wrapper objects.

void incrementar(int n) {
  n = n + 1; // solo modifica la copia local
}

void incrementarReal(int[] n) {
  n[0] = n[0] + 1; // modifica el original via referencia
}
05 // BEST PRACTICES

5. Best Practices

  • Name methods with descriptive verbs: calcularTotal, imprimirReporte.
  • Prefer small methods with a single responsibility.
  • Document parameters and return values with clear comments.
  • Use final when you don't want the function to alter the received data.
06 // COMPLETE EXAMPLE

6. Complete Example

public class Ejemplo {
  static void imprimirBienvenida() {
    System.out.println("Bienvenido a Programierds");
  }

  static int multiplicar(int x, int y) {
    return x * y;
  }

  public static void main(String[] args) {
    imprimirBienvenida();
    int res = multiplicar(6, 7);
    System.out.println("6 * 7 = " + res);
  }
}
END // MORE RESOURCES