Doubt about the Initializer block

Asked

Viewed 59 times

0

I’d like to know why the code compiles but does not execute?

Follows the code:

package exemploinicializador2;

public class ExemploInicializador2 {

   private String nome = "Aurélio";
   private String sobrenome = "Soares";
   private  int idade = 25;
   private  double f = 354.34;

   // Bloco Inicializador
   {
    System.out.println ("Nome: " +nome);
    System.out.println ("Sobrenome: " +sobrenome);
    System.out.println ("Idade: "+idade);
    System.out.println ("F: "+f);
    }
   // Construtor
   public ExemploInicializador2 () {
       System.out.println ("Dentro do Construtor");
   }
}

The other code is:

package exemploinicializador2;

public class TesteInicializador2 {
    public static void main (String args []) {
        TesteInicializador2 objeto = new TesteInicializador2();
    }
}
  • 2

    Which of the two does not execute? Both must execute, only in the first does not have the main and in the second there is nothing to display.

  • The first class is never instantiated. If it does not instantiate, it will not display anything at all.

  • Did the answer help you? If yes, you can mark it as accepted by clicking on v the left of the answer :)

1 answer

5

Both codes compile and only the second one displays something. The fact that it does not display anything in the terminal does not mean that these actions did not occur.

The reason I don’t display anything from ExemploInicializador2 is because at no time it is instantiated. Now, if there is not an instance of an object of this class, nothing of it will be executed.

Try changing the second class as below:

package exemploinicializador2;

public class TesteInicializador2 {
    public static void main (String args []) {
        ExemploInicializador2 objeto = new ExemploInicializador2();
    }
}

In this case, both will continue to be compiled and the class snippet ExemploInicializador2 will be executed and displayed, since we are instantiating an object.

See working on ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.