Why does if only work with the return of a method?

Asked

Viewed 1,732 times

3

Follow my code that contains a boolean method:

import java.util.Scanner;

public class ativ16 {
    public static void main(String[] args) {
        int n, i, v[];
        Scanner entrada = new Scanner(System.in);
        n = entrada.nextInt();
        v = new int[n];

        for (i = 0; i < n; i++) {
            System.out.println("Digite um número: ");
            v[i] = entrada.nextInt();
        }


        if (VetorEhPalindromo(v, n)) {
            System.out.println("vetor é palíndromo");
        } else {
            System.out.println("vetor não é palíndromo");
        }
    }

    static boolean VetorEhPalindromo(int v[], int n) {

        int i, temp;
        int t[] = new int[v.length];
        boolean ehPalindromo = false;

        for (i = 0; i < v.length; i++) {
            t[i] = v[i];
        }

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

            if (i < (t.length / 2)) {
                temp = t[i];
                t[i] = t[t.length - i - 1];
                t[t.length - i - 1] = temp;
            }

        }

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

            if (t[i] == v[i]) {
                ehPalindromo = true;
            } else {
                ehPalindromo = false;
            }
        }

        return ehPalindromo;
    }
}

My question is about parole if in the method main(). Why the if(VetorEhPalindromo(v,n)) does not receive a condition and still executes the code correctly? For example: if(VetorEhPalindromo(v, n) == true).

  • 1

    I didn’t understand what the doubt is. The method returns a boolean, so what’s the problem?

  • @bigown think it is because the return of the method cited is the condition of if only.

  • The simple fact that the method returns a boolean already represents a pro condition if check. Remember, if evaluates a condition like true or false, if the method itself already returns it, its return which is the condition checked.

  • So by default whenever I just call the function inside the if, the program understands as a function type condition == true?

  • @Leko in java does not need to compare boolean returns this way, typing will not allow you to use any condition other than a logical operation (with true or false return). Making an analogy to language, use if(VetorEhPalindromo() == true) instead of if(VetorEhPalindromo()) would sound like a pleonasm. It’s not a syntax error, it just unnecessarily increases the complexity. That’s why it works.

  • @seamusd the title was very strange after editing(actually it was, but it was even more so)

  • @diegofm realized it was really weird. The issue of editing was because I realized part of the title was on the tag, so maybe it would be better to leave without. But you are right.

  • 1

    @diegofm I tried to improve it, I think it got better this way.

Show 3 more comments

2 answers

9


Look at this code:

class Main {
    public static void main (String[] args) {
        int x = 10;
        boolean cond = x == 10;
        System.out.println(cond);
        if (cond) System.out.println("executou");
        cond = metodo();
        System.out.println(cond);
        if (cond) System.out.println("executou");
        System.out.println(x == 10);
        if (x == 10) System.out.println("executou");
        System.out.println(metodo());
        if (metodo()) System.out.println("executou");
    }
    public static boolean metodo() {
        return true;
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Many people should be surprised that it is possible to keep the result of the boolean expression, which people often call a condition.

The first day I saw something about the subject in programming at the time I realized that this was normal, I was in eighth grade, I didn’t even have a complete math training, but I knew the basics that everyone should know. I was lucky enough to start learning from below. Today people learn what comes from above without having the foundation.

One thing that many programmer beginner does not understand, and incredibly even some with years of experience, is that a if will execute the command block, or pass through it without executing, based on a value boolean, ie if you have a true value enters the block, if you have false then you do not enter the block (you will enter the else if you have). That’s all the if does, anything else is not his function, if by chance there are other things happening there, it is independent of the if and in practice will be executed before, your result will be stored temporarily somewhere to be used by if.

Where does this boolean value come from? It can come from any expression, as long as the result is a true or a false. It is common for this expression to use a comparison operator (==, !=, >, <, >=, <=), after all they always generate a boolean result. Relational operators (&&, ||, !) also generate a boolean, the latter even require the operands to be boolean as well.

But if you use a variable that already holds a boolean value? This is an expression that generates a boolean result and can be used in if no problem, he has what is expected.

Just as you use an "integer variable" to make an account, why not use a "boolean variable" to establish a condition? It would be weird not to do that, it would be asymmetrical. So you can do:

int x = 1;
int y = x + 5;

in place of

int y = 1 + 5

Why couldn’t you do what is in the above example?

What if instead of using a variable I use a method that returns a boolean? Won’t it give the same result? Won’t provide exactly what I need to use on if?

What I understand is that people think if is something special, and he is not, he only does what I described above. In fact all language is assembled in the most symmetrical way possible. Where a thing is worth, it is for everything. If somewhere it is not worth making an exception justified in its specification and implementation.

Just as I don’t understand why programmers create variables without any need* (variables are only one form of storage, if you don’t need to store it, why create it? ), I don’t understand why people think you have to do it

if (metodo() == true)

Actually this is absolutely redundant taking the example above. That would be the same as doing

x = x; //sim, está só atribuindo o valor de x em x, todo mundo vê a redundância.

In this example you are taking the value that the method returns, in which case we know it is true and compare to see if he is true, so it will give true. Why not just use the received value if that’s what we want? Why create an additional step that does nothing more than what we already know? I see "every excuse" when the programmer is caught making a mistake like this...

Sometimes I see methods do something like this:

public boolean condicao(int x) {
    if (x == 10) {
        return true;
    } else {
        return false;
    }
}

When just do it:

public boolean condicao(int x) {
    return x == 10; //retorna exatamente o que precisava
}

I put in the Github for future reference.

When I see this, I know that that person’s code will have a lot of wrong things because they don’t have the slightest notion of the basic things of computation, or even mathematics, and they will only be able to follow recipes, which is far from being actual programming.

I think the problem is even this. People do not see that the if eliminates a variable that everyone thinks is necessary always.

How languages work

Forget this condition business, what exists is a boolean expression. There’s no magic, there’s nothing special about it, otherwise it would be special. This is not all programming, this is (basic) mathematics, nothing more. A person who has learned mathematics fully understands this without reading a programming material.

Languages have well-defined rules of how they work and they try to be as intuitive as possible, try to be linear, symmetrical, just making the obvious.

Everything written is executed in pairs of values (some things can perform alone or not need a value, but never in threes or more elements) and always an instruction of what to do with the value.

A if is the result of a Boolean value that is evaluated and decides whether to deviate the execution to another point or maintain the sequence. In addition it has unconditional deviations hidden to control the block. This boolean value must be something unique. If he is not unique he must perform the expression that is written there to give the unique result. If this expression has sub-expressions (pairs of operated with an operator), each of them needs to be executed before.

Actually, you work that way, too. To evaluate a complete expression, your brain will evaluate sub-expressions, you make "one contained" at a time and will pick up the result to use in the next contained, until, step by step, made the "contona" that gave the final result. As can be seen here:

Avaliação de expressão

That is why I say that the first language one should learn is Assembly (even if only the superficial one). Understand how the computer works before creating abstractions. It is very difficult to understand how things are when abstraction comes first.

Behold How is a compiler made? to help get an idea of how this works. Pay attention to the abstract syntax tree, which is what I’m talking about in the paragraph before the diagram. It is so because the computer can only perform very simple concrete operations, the rest is abstraction on top of that.

Some "programmers" die without understanding this. In fact they have always been followers of rules that I always talk about, never been programmers. There is a difference between programming and writing a handful of code that one doesn’t even understand what one is doing. Luckily some are curious and ask and learn, that’s why we’re here.


*Creating a variable for no apparent reason, not even documentation is the most obvious case of the person following cake recipes without understanding what they are doing. Another very common example is to declare a variable before and soon after assign its value instead of doing everything at once. I understand why people declare all variables at the beginning of the function or method, they have learned wrong that this is good. They learned this because ancient languages required it to be so, but the most correct statement is to be as close to its use as possible and with as little scope as possible. Inside the smallest scope possible.

5

It’s simple to understand. If you test a condition, if the condition is satisfied then the condition returns true. Soon if you test a Boolean you will already be giving the result to the IF.

See the example for you to understand:

Test of "affirmation"

    Boolean teste = true;
if(teste){
// Vai entrar aqui porque teste é verdadeiro
} else {
// Não vai entrar aqui porque a condição já foi satisfeita
}

Denial test

Already if you put one ! before the variable in the conditional your test will be reversed, ie instead of you are testing if the condition is satisfied you will be testing if the condition is not satisfied

    Boolean teste = true;
if(!teste){
// Não vai entrar aqui porque teste é verdadeiro
} else {
// Vai entrar aqui porque teste é verdadeiro e o if está testando se a condição NÃO foi satisfeita
}

Browser other questions tagged

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