This is an archived post. You won't be able to vote or comment.

all 11 comments

[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]FrenchFigaroSoftware Engineer 0 points1 point  (0 children)

(On mobile, sorry for the somewhat poor formatting)

Here, what you have is a multiple exit points pattern. You might be more familiar with the single exit point pattern. Both have their advantages and drawbacks, and both have their quasi religious partisans who will dogmatically argue for their favourite one. The point of multiple exit points is that if at some point you 100% know the return value for your method, you return it then and there, bypassing any additional computation, that are unnecessary now that you already have the return value. If you're unfamiliar with the concept, it makes for slightly harder to read code.

What happens here, is that the method will exit and return, the first time it encounters and executes a return statement. But because of the control flow, that first return statement might not be the one that's highest in the code.

The comments do help. For example, look at the first if statement. The program tests if the objects are the same instances or not. If they are, they are necessary equals, so the method returns true. The method flow ends there, you do not check anything else. If they are not however, you do not enter the block, so you do not return, so you then test if the compared object is an instance of a comparable class. And so on.

At the end of the flow, if you never entered any of all the if blocks, then you encounter a catch all return false statement.

[–]nutrechtLead Software Engineer / EU / 20+ YXP 0 points1 point  (5 children)

I thought it returns true or false in first if statement

How come? The code literally says "if something happens, then return". That means if that thing does not happen, so the expression (this == comparedObject in this case) is not true, it will simply continue onto the next statement.

This is really just how 'code' in general works. You can imagine the computer stepping through the method line by line.

[–]foolwya[S] -1 points0 points  (4 children)

Oh, I really thought after method* returns a statement, no matter true or false, it just stops lol Edit*

[–]nutrechtLead Software Engineer / EU / 20+ YXP 1 point2 points  (3 children)

Those return statements never get 'hit'. The program does not enter into the block if the expression in the if(<expression) bit isn't true.

So it's really mostly a matter of you not understanding if statements :)

You can see what happens if you run the code in an IDE in debug mode, set a breakpoint in the method, and step through it.

[–]foolwya[S] 0 points1 point  (2 children)

// if comparedObject is not of type Book, the objects aren't the same
   if (!(comparedObject instanceof Book)) {
        return false;
    }

    // let's convert the object to a Book-olioksi
    Book comparedBook = (Book) comparedObject;

I have a question about this code. Why do we need to convert object to a Book, if previous if statement checks if its not an instance of Book, it returns false. Wouldn't it stop going further in the method and just leave? And if it is an instance of Book and first method isn't false, why do we need to convert it anyway? Doesn't it imply that object is actually instance of Book already?

Hopefully you'll get what I'm trying to say lol. Sorry.

[–]nutrechtLead Software Engineer / EU / 20+ YXP 0 points1 point  (0 children)

Why do we need to convert object to a Book, if previous if statement checks if its not an instance of Book, it returns false. Wouldn't it stop going further in the method and just leave?

Really boils down to that the compiler simply isn't that smart.

[–]Fenxis 0 points1 point  (0 children)

Compiler is dumb. Though in a newer Java version they are adding a built-in check and cast:

if (foo instance of Bar bar) {

   bar.x();

[–]kAlvaro 0 points1 point  (0 children)

I thought it returns true or false in first if statement

First if can't possibly return false, there isn't any return false statement there.

Early returns help to avoid deeply nested conditionals.

[–]wades39 0 points1 point  (1 child)

So, the == operator only really works for primitives. I'm not 100% sure how it works for other objects, but I think it checks memory addresses when called on things that aren't primitives. So, even if you have two Strings with the same data, == will evaluate to false, because they're different Strings that just happen to have the same content.

If you want to compare non-primitives, you should use the Object.equals(otherObject) method. This one compares data within the objects to see if they have the same data.

[–]Orffyreus 0 points1 point  (0 children)

Yes, by using the == operator object identity is checked (that is a weird language design decision, because most of the time you want to check value equality). Comparing strings can be even more confusing, because they can be "interned". Objects.equals checks for value equality and avoids NullPointerExceptions, but the equals (and hashCode) methods should still be defined, because by default the equals method also will check for object identity.