Understanding Exercise Book use Java head

I did not understand the operation of the code below, maybe later in the book I have better explanations or I let something pass even in the review.

I will detail the points in the code itself where I have doubts.

    package qb5;

    public class Qb5 {

    static class Mix4{

    int counter = 0;

    public int maybeNew(int index){

        if (index < 7 ){

            Mix4 m4 = new Mix4();

            m4.counter = m4.counter + 1;

            return 1; //Sempre retornará 1, aqui entendi
    } 
        return 0; //Não achei o porque do return 0 neste ponto
    }
}

    public static void main(String[] args) {

        int count = 0;
        Mix4[] m4a = new Mix4[20];
        int x = 0;

        while (x < 7 ){
        m4a[x] = new Mix4();
        m4a[x].counter = m4a[x].counter + 1;  
        count += 1;
        count = count + m4a[x].maybeNew(x); 

        x +=1;
        }
        System.out.println(count + " " + m4a[1].counter); //Porque m4a[1]?
    }
}

Here I have the biggest doubt:

I understood that maybeNew(x), sends the value to the variable index in the method maybeNew to do the comparison, but this same maybeNew(x) somehow affects the assignment of the variable count itself of the start of the line?

The output of this exercise would be 14 1, but I was lost and I can not see how it got to 14, the 1 itself return indicates the value.

EDIT: This code really has catch, as well as another previous one, but the book itself says that there are things that will be clarified ahead, dirtying that pass forward if you do not understand, but I preferred to hit head. From what I understand, the variable counter only enters to confuse even, it will always be 1.

Already on Saida m4a[1].counter that index 1 is embellished, because I put 2 and also returned Result 1 from the counter.

@ Edjane cleared the mind by explaining the instance to zero the variable.

I did a manual debug adding a few more prints in the code and see the output, and next to the table test dirty by @Maniero I saw that did not beat the results, so I managed to understand.

I made a loop of 3 just to not get big the image, because in the output of m4 printed 2 times, I did not find the because of this, it is banal thing but to finish, this doubt remained.

Java logic

Author: Acneto, 2018-09-04

3 answers

I have studied a lot of exercises of this type to take the OCJP certification, it covers instantiation of classes and passing values, for example, because this line,

m4.counter = m4.counter + 1;

Contained in method public int maybenew (int index) always returns 1? Simply by the fact that whenever the method is invoked in main this value is restarted, when you instantiate the class.

 Mix4 m4 = new Mix4();

This is to test you and try to mislead you if you don't master it, you can deduce that m4.counter = m4.counter + 1; always this incrementing 1 to the previous value, which would give a different answer.

In this case you can even put the If return as m4.counter which will always return 1.

Another important point, see the comments in the code

    while (x < 7 ){
            m4a[x] = new Mix4(); //aqui nova instancia, ou seja, sempre é inicializado
            m4a[x].counter = m4a[x].counter + 1; //por ser inicializado sempre soma 0+1, ou seja aqui sempre vai ser 1
            count += 1; //aqui ele pega o valor anterior do count que não é inicializado e acrescenta 1
            //nesse ponto você percebe que a variável não instanciada continua com o seu valor anterior
            count = count + m4a[x].maybeNew(x); //soma o valor anterior com o valor passado pelo método, como você esta indo ate 7 ele passa 1, caso você faça um while maior que 7 ele passa 0

       x +=1;
    }

The output of this exercise would be 14 1, but I was lost and I can not fill up how it got to 14

Because the result is 14 1 let's put in the cycle ok?

1° ciclo:
m4a[x].counter = 1;
count += 1;
count = 1;
count = 1 + 1; // count = 2

2° ciclo:
m4a[x].counter = 1;
count += 1; //valor anterior = 2 + 1 = 3
count = 3;
count = 3 + 1; // count = 4

...
7° ciclo:
m4a[x].counter = 1;
count += 1;
count = 13;
count = 13 + 1; // count = 14

Result 14 1

What if you exceed 7 in while causing if to return 0? Example:

while (x < 8 )
8° ciclo:
m4a[x].counter = 1;
count += 1;
count = 15;
count = 15 + 0; // count = 15

Your final result would be 15 0

Continuing...

Already in Saida m4a [1].counter that index 1 is embellished, because I put 2 and also returned Result 1 from counter

Actually this value is not of embellishment, it always gives the same value because a new instance is always created, this is more an intention of you to be induced that this value has undergone an increment, which does not happen, for you to understand better, let's take this excerpt from your code:

static class Mix4{
  int counter = 0;
  ...

Now we take this excerpt:

if (index < 7 ){
    Mix4 m4 = new Mix4(); //nova instância de Mix4
    m4.counter = m4.counter + 1; // isso é a mesma coisa que ***m4.counter = 0+1***

In this case the received value for sum m4.counter is 0, because it took the value of counter defined in the Mix4 class. As long as you do not re-instantiate this class this value within this if will be 1 (m4.counter = 0+1 => 1)

Example:

if (index < 7 ){
    Mix4 m4 = new Mix4();
    m4.counter = m4.counter + 1; //m4.counter = 0 + 1
    System.out.println(m4.counter + " = m4"); //m4.counter 1
    m4.counter = m4.counter + 1; //m4.counter = 1 + 1
    System.out.println(m4.counter + " = m4"); //m4.counter 2

Another test to be clearer, what if the value of counter was 4

static class Mix4{
      int counter = 4;
      ...

Result:

if (index < 7 ){
    Mix4 m4 = new Mix4();
    m4.counter = m4.counter + 1;  //m4.counter = 4 + 1
    System.out.println(m4.counter + " = m4"); //m4.counter 5
    m4.counter = m4.counter + 1; //m4.counter = 5 + 1
    System.out.println(m4.counter + " = m4"); //m4.counter 6

Working with Java, you will never write or see such code, "unless you are a teacher" but these teachings are fundamental to a good developer.

...because on the output of the m4 printed 2 times

I did not see the reason for being printed 2 times

 2
Author: Edjane, 2018-09-06 12:32:26
return 1; //Sempre retornará 1, aqui entendi

Will not always return only if index is less than 7.

return 0; //Não achei o porque do return 0 neste ponto

It will execute whenever index is not less than 7. The function needs to have a return in any circumstances, it cannot return something only in some cases and in another it cannot.

Does this same maybeNew(x) somehow affect the assignment of the count variable itself from the beginning of the line?

It itself does not, but the whole line is affecting count, after all this line it is saying to save in count, and this by itself already affects something, a value that in the case is itself count Added from an expression

System.out.println(count + " " + m4a[1].counter); //Porque m4a[1]?

We have no way of knowing what is in the question, but for some reason it needs to take the second element of this array.

The output of this exercise would be 14 1, but I was lost and I can not see how it came to 14, the 1 itself return indicates the value.

He was following the algorithm. I could explain line by line, but the best is to do the table test yourself and identify. However, in a confusing code so it is best not to try. Learn from something more meaningful. Understanding this will be detrimental to your learning.

Rarely should main() be next to a class that needs to be instantiated. This confuses everything. There is no reason for every part of this class to exist and if you start working with meaningless things you will get used to it. Note that in each step there is the accumulation of 2. The first accumulation is quite explicit and then the other happens because maybeNew() always returns 1, this could have been written in one line.

It is not your fault to have difficulty understanding, it is the fault of the code.

The code is poorly written and poorly didactic. It teaches doing weird, confusing, and probably wrong things, so I would question the book. This book series was well regarded, so I don't know if it got worse over time or this one specifically was misspelled.

 5
Author: Maniero, 2020-08-04 20:28:26

This is quite confusing code and as @Maneiro said it is questionable as code to be in a book, but I will try to explain what is happening on the basis that this is the only code of the project.

It all starts in your main, where the class attributes are named and instantiated:

int count = 0;
Mix4[] m4a = new Mix4[20];
int x = 0;

Then makes a loop that will iterate 7 times increasing the value of x with each iteration

while (x < 7 ) // itera 7 vezes de x=0 até x=6

x +=1; //aumenta o valor de x a cada iteração

Well let's go the four lines of code inside the loop ( analyze what the code is doing=))

    m4a[x] = new Mix4();                   //linha 1
    m4a[x].counter = m4a[x].counter + 1;   //linha 2
    count += 1;                            //linha 3
    count = count + m4a[x].maybeNew(x);    //linha 4

On Line 1 main creates an instance of Mix4 and places it in the list m4a

In Line 2 the code is taking this instance that is now in the list and adding the value 1 to the attribute of that object, in the case of counter, which was 0 and is now 1

In Line 3 the code adds the value 1 to the variable count, since this code is executed 7 times we can say that this line is responsible for adding the value 7 to the variable count

In Line 4 the code is taking the value of count by adding a value to it * and saving that sum to the variable itself count, we can say that it is adding a value to the value it already had before.

Let's analyze this added value:

The code is calling the maybeNew method of the object that was just saved in the list, what we know his?

- > we know that the value of its attribute counter is equal to 1, and that the passed parameter (x) is always less than 7

Parsing method maybeNew:

The method has as its first line a if which checks if the passed parameter is less than 7 ( which we know it always is) and does a series of things if this condition is true.

 Mix4 m4 = new Mix4();
 m4.counter = m4.counter + 1;
 return 1;

First creates a new instance and assigns it to an object named m4, then modifies the value of the attribute m4 and finally returns the value 1

So we know that it will always return 1 and we now know how much is added to count in Line 4

Knowing that in Line 4 is always added 1 we have that at the end of the 7 iteration will be added the value 7.

System.out.println(count + " " + m4a[1].counter); 

We reached the result of 14

The value 1 of m4a[1].counter is the one that the code had added in Line 2

Hope I helped, any doubts leave a comment

 2
Author: Um Programador, 2018-09-04 11:47:38