Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java && || in RETURN statements?

I'm looking at some Java algorithm examples and I come across this snippet code within a recursive method:

boolean subTree(TreeNode t1, TreeNode t2) {
    if (t1 == null) {
        return false;
    }
    if (t1.value == t2.value) {
        if (treeMatch(t1, t2))
            return true;;
    }
    return (subTree(t1.left, t2) || subTree(t1.right, t2));
}

Not knowing (and never seeing) || being used within a return statement before, let alone a recursive one, really made me confused. I copied the code into Eclipse to see if it was valid and it was. I then replaced the || with && and Eclipse didn't seem bothered by it. Logically, I understand that this recursive code is supposed to continue down the left and right subtrees of TreeNode t1, but I'm looking for a more theoretical explanation behind how this Java syntax works.

Can someone explain the meaning behind || and && within Java's return statement? What does it mean in terms of recursion? Is it only meaningful when used in conjunction with recursion?

like image 615
Sam Meow Avatar asked Feb 04 '14 15:02

Sam Meow


People also ask

What is Java used for?

Developers use Java to construct applications in laptops, data centres, game consoles, scientific supercomputers, cell phones, and other devices. Java is the worlds third most popular programming language, after Python and C - according to the TIOBE index, which evaluates programming language popularity.

What exactly is Java?

Java is a programming language and computing platform first released by Sun Microsystems in 1995. It has evolved from humble beginnings to power a large share of today's digital world, by providing the reliable platform upon which many services and applications are built.

What is Java called now?

Java, also spelled Djawa or Jawa, island of Indonesia lying southeast of Malaysia and Sumatra, south of Borneo (Kalimantan), and west of Bali. Java is home to roughly half of Indonesia's population and dominates the country politically and economically.

Is Java a programming or coding?

Java is a popular programming language, created in 1995. It is owned by Oracle, and more than 3 billion devices run Java. It is used for: Mobile applications (specially Android apps)


1 Answers

As defined in the method signature, you will have to return a boolean. Therefore, after the return keyword, you will have to provide a boolean or an expression which is evaluated to boolean.

In your case you have the expession (subTree(t1.left, t2) || subTree(t1.right, t2)); in which the two operands will be evaluated to boolean and you will apply an logical OR on them only if the first evaluates to false. If the first operand evaluates to true the second will not be evaluated and true will be retured.

like image 119
Konstantin Yovkov Avatar answered Sep 29 '22 01:09

Konstantin Yovkov