OT: java quirks Was: Re: [ale] Introduction

Jason Day jasonday at worldnet.att.net
Wed Dec 1 10:06:06 EST 2004


On Tue, Nov 30, 2004 at 08:42:51PM -0500, Geoffrey wrote:
> The dream job!  You're confused though, it's the Java that is annoying 
> you.  I mean come on, try subtracting a character from a character in 
> order to get the numeric difference.  C ? yes, Java, I don't think so..

Sure you can.  You just have to realize that the JVM can only perform
arithmetic on ints and longs, and consequently whenever you do
arithmetic on a data type that's smaller than an int, the JVM will
automatically promote (and sign extend!!!) it to an int.  So,

int diff = 'd' - 'a';

is ok, but

char diff = 'd' - 'a';

is not, because the chars are promoted to ints to do the subtraction,
and the result is an int, and you can't stuff an int into a char without
an explicit cast.  So, you could do this:

char diff = (char)('d' - 'a');

if you really wanted to, but you probably want the diff as an int
anyway.

The same goes for bytes as well, but there's an extra hurdle because
bytes are signed, and the JVM sign-extends data types when it promotes
them.  So if you have a byte value that's greater than 127, and add it
to another byte, you won't get what you expected.  You have to first
explicitly cast it to an int and mask off the sign bit.  Fun.

Sorry for the lecture; I've just done way too much bit twiddling in
Java.  Don't get me started on the Date and Calendar classes.  Or the
StreamTokenizer class  *shudder*.

Jason
-- 
Jason Day                                       jasonday at
http://jasonday.home.att.net                    worldnet dot att dot net
 
"Of course I'm paranoid, everyone is trying to kill me."
    -- Weyoun-6, Star Trek: Deep Space 9



More information about the Ale mailing list