A little Java trick

I accidentally run into this code and well, it gave me some headache.

You probably won’t meet such coding errors but it is good to see something like this too.

Take a look at the following simple Java code:

/**
 * @author GHajba
 *
 */
public class ChangeCalculator {

    static int getChange(final int price, final int bankNote) {
        // example: \u000d price = 100;
        return bankNote - price;
    }
}

Well, it does not seem peculiar but let’s compile it (any Java version should be fine):

ChangeCalculator.java:8: error: final parameter price may not be assigned
        // example: \u000d price = 100;
                           ^
1 error

Not so good. What’s the matter with the compiler?

The solution

The problem is with the unicode character. If you search after it on the Internet you will find that it is the unicode carriage return character.

While Java is parsing your code it will see that “Hey, this is a CR, let’s start a new line!”. And because of this the code

price = 100;

will get on a new line outside of the comment and now you get the compile error because price is declared as a final argument.

Take case when you are using special unicode character sequences in your comments. They may lead to different errors you won’t think of.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s