Mostrando las entradas con la etiqueta app. Mostrar todas las entradas
Mostrando las entradas con la etiqueta app. 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 initializationint i = 0
  • block of conditional checking:  i < 10
  • block where the variables are incrementedi++
  • 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.

 


 

 

 







sábado, 18 de julio de 2020

Naming conflicts in Java


@jwimmerli

















In Java there are situations that you have to use a class that have the same name but resides in different packages, for example the Date class, you can find a implementation of the Date class in the package java.util  and in the package java.sql , both classes have similarities but work for different purposes.

What if you have to use both classes ( java.util.Date and  java.sql.Date  ) in a class of your program, how you can deal with the naming collision  that you have if you try to import both classes.

Let's see the following example to have a clear idea of the problem that we are trying to solve:
in the following snippet of code we have a class named Comment that is declaring two variables of type Date:
package mysite;

import java.util.Date;
import java.sql.Date; // this import will throw an error: The import java.sql.Date collides                         // with another import statementJava(268435842)
public class Comment {
private Date date;
private Date dateSql;

public Comment(Date date, Date dateSql){
this.date = date;
        this.dateSql = dateSql;
}

public Date getDate(){
return this.date;
}
public Date getDateSql(){
return this.dateSql;
}
}

As  you can see,  if you try to import a class with the same name, you will have a compiler time error indicating that the second class that your are importing collides with the first class,  in this case java.sql.Date  collides with the  java.util.Date

You can solve this naming conflict in several ways, but I recommend you, if you are having this type of naming collisions, always use the full qualified name declaration to remove ambiguity and make your code easier to read.
In this case, I remove all the explicit imports and declare the variables using FQN, as you can see in the following code snippet:

package mysite;


public class Comment {

private java.util.Date date;
private java.sql.Date dateSql;

public Comment(java.util.Date date, java.sql.Date dateSql){
this.date = date;
this.dateSql = dateSql;
}


public java.util.Date getDate(){
return this.date;
}
public java.sql.Date getDateSql(){
return this.dateSql;
}
}

This is more long typing coding, but this assure that every person that read your code will understand from which package your are using a specific class.


Recommended readings:





lunes, 9 de diciembre de 2019

How to create a project using Spring Boot?


As mentioned in previous posts, Spring Boot is a Framework that allows as to accelerate our development, helping us with some configurations, in this post we will see how we can take advantage of these automatic configurations creating a simple application using Spring Initializr





















If you don't not what Spring Boot is, I recommend you to go to (What is Spring Boot?) and read a brief introduction about Spring Boot.


We have multiples opciones to create a project using Spring Boot: the fisrts one is using the web version of Spring Intializr, the second one through an IDE like Spring Tool Suite (STS) or Intelij and the third using the CLI or command line interface, we are gooign to learn how to create a project using de web version of Spring Initializr and using de STS IDE

In order to maintain this posts as simple as posible we are goin to create a simple project that stores product information in a Mysql data base

Let's start by creating project using Spring Initializar:


  1. First we need to access to the web version of Spring Initialize through this link (Spring initializr,) o searching Spring initializr in Goole, you will see a page like the one shown in the following image:




















One you are in the Spirng Intiliazr page, you have to fill some fileds request by the tool:
  • Choose Maven Project as dependency manager
  • Choose the latest stable version of Spring Boot, in this case V 2.2.2
  • In the project metadata option fill the fill the following fields:
    • Group Idco.com.bateacode.products
    • Artifac Id (nombre de nuestra aplicación) ingresamos: approducts
  • Finally choose the dependencies: Spring webThymeleaf y Spring Data JPA,
as shown in the following image:


One you have completed the by the Spring Innitializr tool, you have to clic on Generate Button to generar the project:
This tool will generate a Zip file, unzip the file in the STS workspace 
To import the project in Spring STS you have to follow the next steps:

Open Spring STS, Click in File, the click in Import, choose the option Existing Maven Prorject and Finally clic in the Next button:




Choose the path of the project you have downloaded from Spring web Intializr, clicking in the Brose button:



Finally clic in the Finish button to import the maven project:

this image show the structure of our project:

2. The second option to create a project using Spring Boot is through some IDE, we are goin tho show how to perform this task using Spirng STS IDE:

Open STS, choose File, click in New, then clic in Spring Starter Project:
you will see a windows where you can fill the fields to create the project, if you notice this fields are almost the same that we filled in the web version of Spring Initializr:


The next step is to choose the dependency, you can search those dependencies in the search field and then add it to the project:

Finally click in the Finish button, and then you can see the project structure:

As you can see, creating a project using Spring Intializr is simple and straightforward, Spring Boot manage some dependencies  for us and automate some task that we will explain in future posts, additionally we are goin to  incremental develop our simple products app, so stay tuned for future posts.