Mostrando las entradas con la etiqueta aplicación. Mostrar todas las entradas
Mostrando las entradas con la etiqueta aplicación. Mostrar todas las entradas

jueves, 6 de agosto de 2020

How does for loop works in Java?

 For loop


A loop is nothing more than a repetitive control structure that can execute instructions multiple times, in java there are various loops like:

 

do/while

        do {

           //Execution block

        } while (condition);

 

while:

        while (condition) {

            //Execution block

        }

 

for:

 

        for (int i = 0; i < args.length; i++) {

            //Execution block

        }

       

 

enhanced for (for each):

        for (String string : args) {

             //Execution block

        }

 

In this post we are going to focus on the regular for and the enhanced for (for each), we are going to see how both loops works and what are their differences.

 

The regular for loop in java is primary used to executed repetitive code, for example iterate through an array, print multiple messages, etc. 

 

As we can see in the declaration of the for loop, this is composed of:

  • key statement:  for
  • block of variable initialization: int i = 0
  • block of conditional checking:  i < 10
  • block where the variables are incremented: i++
  • and the execution block: //any code to be executed 

 

Most people can think that the step in which the regular for loop is executed is as showing in its declaration, but not, the steps that the JVM follow to execute a regular for loop are as follow:

  1. first the block of variable initialization is executed, in this block you initialize the variables that are going to be used in the for loop, you can have multiple var initialization, or even don't have any var initialization at all, as follow:

        for (int i = j = 0; i < 10; i++) {

            //Execution block

        }

 

in this example, if you are declaring an initializing more than one variable, these variables have to be of the same type and you have to set its value at the same time.

 

        you can have the var declaration outside de for loop, as follow:

        int i;

        int j;

        double d;

        for (i = 0, j = 0, d = 1.0; i < 10; i++) {

            //Execution block

        }

 

in this case you can have multiple variables of multiple types and you can initialize those variables using a comma separator.

 

2.     once all the variables are initialized, the next step is executing the block of conditional checking, this is the part where the program check if the for loop a meets the criteria to continue running.

  1. after the conditional checking is executed, the next step is executing the code block inside the for loop
  2. the final step is check block where the variables are incremented

these steps are repeated over and over again, going to the step 2 to check the conditional checking, then to the step 3 execution block inside the for loop and then the block where the variables are incremented, and so on until the for loop meets the criteria to continue running.

It is worth to mention that the block where the variables are incremented have to be a statement that return a value, in this case i++ return the value of i and then increment its value, of example if you have a for as follow: when you attempt to add 2 to the variable i the code will not compile:

        for (int i = 0; i < 10; i + 2) {

           //Execution block

        }

 

The enhanced for loop (for each) is not much different of the regular loop, it is just a way to use a for loop without worrying about the conditional checking and the incremental checking.

The enhanced for loop only works on collections that implements the iterator interface, this loop is just a help for the developer, once you compile your program, the compiler translates the for loop to a regular while loop if you are using a collection or to a regular for loop if you are using an array, let see an example:

List<Integer> list = new ArrayList<>(List.of(1,2,3,4));
for
(Integer var:list) {
    System.
out.println(var);
}

is compiled and translated to:

List<Integer> list = new ArrayList(List.of(1, 2, 3, 4));
Iterator var2 = list.iterator();

while
(var2.hasNext()) {
    Integer var = (Integer)var2.next()
;
   
System.out.println(var);
}

 

String[] string = {"1","2","3", "4"};
for
(String str: string) {
    System.
out.println(str);
}

is compiled and translated to:

String[] string = new String[]{"1", "2", "3", "4"};
String[] var8 = string;
int
var4 = string.length;

for
(int var5 = 0; var5 < var4; ++var5) {
    String str = var8[var5]
;
   
System.out.println(str);
}

 

 As you can see the enhanced for loop is translated to a regular loop when you compiled your code which indicate that the compiler will handle all the complexity of manage the conditional checking and incremental variable for us, which result in cleaner and easy to read code.

I hope this post will help you understand how for loops works in Java, this can be an easy topic at first glance but having a good understanding of this topics will help you to face interviews or solving certification exams.

 


 

 

 







domingo, 8 de diciembre de 2019

¿Cómo crear un proyecto usando Spring Boot?


Como se explicó en posts anteriores, Spring Boot es un framework que nos permite acelerar nuestro desarrollo de aplicaciones Java, ayudándonos con ciertas configuraciones, en esta entrada vamos a ver como podemos tomar ventajas de estas configuraciones automáticas y crear un proyecto haciendo uso de Spring Initializr




















Si no sabes que es Spring Boot te recomiendo que vayas a este enlace (¿Que es Spring boot?)  y leas una breve introducción acerca de Spring Boot.

Para crear una aplicación con Spring boot tenemos múltiples opciones:

  • la primera option es usar la versión web de Spring Initializr.
  • la segunda utilizando algún IDE como Spring Tool Suite (STS) o Intellij, y finalmente  
  • con la herramienta de linea de comando de Spring Boot (CLI). 
En esta entrega vamos a aprender a crear nuestro proyecto usando la versión web de Spring initializr y usando el IDE STS.

En aras de mantener simple esta entrega vamos a crear una aplicación sencilla que almacena productos en una base de datos Mysql.

Comencemos entonces creando nuestra aplicación usando Spring initializr:

  1. Accedemos al siguiente enlace de Spring initializr, o podemos escribir en Google Spring Initializr y elegir la primera opción que nos recomienda Google, esto nos llevara a la pagina https://start.spring.io/ como se muestra en la siguiente imagen:

Una vez allí procedemos a completar los campos que la herramienta nos solicita:
  • Elegimos Maven Project como gestionador de dependencias
  • En la opción Laguange elegimos Java
  • En la opción Spring Boot, elegimos la ultima versión estable para esta caso la versión 2.2.2
  • En la opción project metadata procedemos a completar los  siguientes campos:
    • Group Id (nombre de nuestros paquetes), para este caso ingresamos: co.com.bateacode.products
    • Artifac Id (nombre de nuestra aplicación) ingresamos: approducts
  • Por ultimo procedemos a agregar las diferentes dependencias que nuestra aplicación va a utilizar: Spring web, Thymeleaf y Spring Data JPA, como se muestra en la siguiente imagen:


Una vez completada la información requerida, procedemos a hacer clic en el botón Generar:
Spring Initializr generará un archivo comprimido que procedemos a descomprimir en nuestro workspace:
Luego de haber descomprimido nuestro archivo procedemos a importarlo en nuestro IDE de la siguiente manera: 
Abrimos Spring STS, hacemos clic de File, luego en Import y elegimos la opción Existing Maven Projects y hacemos clic en el boton Next:





Elegimos la ubicación de nuestro proyecto en el explorador de archivos haciendo clic en el boton Browse:


Elegimos nuestro proyecto y hacemos clic en el boton Open:
Finalmente importamos nuestro proyecto haciendo clic en boton Finish:

La siguiente imagen muestra la estructura de nuestro:

2. A continuación muestro los pasos para crear nuestro proyecto usando el IDE STS

En STS vamos a la opción File, luego hacemos clic en la opción New y elegimos Spring Starter Project:
Esto nos lleva a la siguiente ventana, donde podemos llenar la información de nuestro proyecto, como pueden observar es la mismo información que llenamos en la opción web de Spring Initializr:


Una vez completa esta información hacemos clic en el boton Next, donde podemos elegir las dependencias de nuestro proyecto, en el buscador podemos escribir el nombre de la dependencia y elegir la dependencia que vamos a agregar, como se muestra en la siguiente imagen:

Finalmente hacemos clic en Finish y tenemos la estructura de nuestro proyecto creado:



Como pueden ver, crear un proyecto usando Spring Intializr es muy simple, Spring Boot gestiona algunas dependencias por nosotros y automatiza algunas tareas que explicaremos en publicaciones futuras, además vamos a desarrollar gradualmente nuestra aplicación de productos, así que esté atento para futuras publicaciones.