Slashdot Mirror


Java Puzzlers

Kylar writes "When you have spare time and decide to do something with a book (That's like an analog webpage, for the neuronauts among us), how often do you turn to a computer related book? How often has it happened in the last year? Right. The problem being that computer books are often either: a) boring, b) difficult to read, c) poorly written, or possibly: d) made of cheese." Read on for the rest of Kylars' review. Traps, Pitfalls, and Corner Cases - Java Puzzlers author Joshua Bloch, Neal Gafter pages 282 publisher Addison-Wesley rating 9 out of 10 reviewer Tom Byrne ISBN 0-321-33678-X summary 95 Corner cases and traps that any serious java developer should be aware of (or entertained by.)

Java Puzzlers is none of the above(*), being well written, amusing, whimsical, and above all, informative. Bloch and Gafter have brought us a book that entertains us with corner-cases, one-in-a-million chances and other happenings that explore the ins, outs, and guts of the Java Programming Language.

Anyone who has been a serious java programmer in the last several years should know the name Josh Bloch, and more importantly, should have read his book Effective Java. Josh, acting as java's platform architect has been directing and guiding Java into it's current incarnation as a mature, robust (Cue the laughter from the peanut gallery) programming language.

This book primarily references the Java 1.5 programming language, and some of the puzzles are 1.5-specific, although a significant portion of the problems are applicable to previous versions. Also, this book is aimed towards people who are competent-to-expert java programmers, and although there is a lot of good information, people who are new to Java will probably be a bit lost. As it stands, I have 7 years of Java experience, and I was only able to figure out about 15% of the puzzles without resorting to code, or more frequently the answer. The reason that I didn't stop to try out most of these problems is that the book is eminently readable, and difficult to put down (unusual for a computer book, and doubly so for one that delves deeply into a language specification document.)

This book dives into a lot of esoteric bits of the Java Language Specification, also known as "The Big Paper That Sometimes Tells Us Why Java Acts Like That," and there are lots of bits in there that don't even make sense, let alone seem intuitive.

Divided into 10 parts, each part presents a series of different code problems that usually present a small method or class that looks innocuous, but in reality exposes a piece of behavior that is strange, spectacular, or, more often, completely confusing. The book exposes flaws in the language, including one of my personal pet peeves, their inability to have a consistent Date object, and this is noted in Puzzle 62 by my favorite line in the book: "The lesson for API designers is: If you can't get it right the first time, at least get it right the second..."

One topic that I found was a continually recurring theme had to do with handling primitives and what happens when they are cast into different types. Java provides a lot of ways to deal with primitives, and for the most part, they play nicely with each other. There are several occurrences that really surprised me. A perfect example is the following innocent statements:

byte b = -1;
char c = (char)b;

so c=-1, right? Wrong. Places like this are things that you could potentially knock your head against the wall trying to figure out why something doesn't do what it appears to do.
(In this case, byte is signed, char isn't, and the widening cast fills in bits, leaving c=65535.)

A good job is also done describing best-practices for API and library designers, as well as us, the more mundane programmers.

The only downside (from my background and point of view - that of an applications architect, and not generally as a language or API designer) - is that some of the amazing optical illustrations can cause dizziness and nausea - although I can't guarantee that won't happen by the loops and twists that your mind will be tied into because of the puzzles.

Lastly, Bloch & Gafter include an appendix that serves as a summary to all the pitfalls and traps that are introduced in the book, and almost could be an appendix to Bloch's 'Effective Java'.

The bottom line is that in reading this book I learned a fair amount about several edge cases and issues that I had actually encountered - and it increased my understanding as to HOW java does things - although I'm fairly certain that I'll never understand the WHY. And most of all - I enjoyed this book, from start to finish, and that's rare, and worth the time.

You can purchase Java Puzzlers from bn.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.

239 comments

  1. I enjoyed Java Puzzlers, but... by Anonymous Coward · · Score: 5, Funny

    ...it took a long time to load the first page. On the other hand, if you drop the book on the ground, it automatically throws itself into the garbage can.

    1. Re:I enjoyed Java Puzzlers, but... by jolshefsky · · Score: 1

      The really strange part, though, is that while the book is automatically thrown in the garbage can, all my other books stop working.

      --
      --- Jason Olshefsky

      Karma: Poser (mostly affected by adding this line long after everyone else did)

    2. Re:I enjoyed Java Puzzlers, but... by Anonymous Coward · · Score: 0

      ...directing and guiding Java into it's [sic] current incarnation as a mature, robust (Cue the laughter from the peanut gallery) programming language.

      (ROTFLMFAO) Stop it! You're killing me!
      </peanut_gallery>

    3. Re:I enjoyed Java Puzzlers, but... by chrish · · Score: 1

      The other problem was having to tell the book how many pages it would be before I opened it, but it wasn't printed with page numbers.

      Reminded me of having to tell Photoshop how big my images were going to be before I started it on old versions of Mac OS.

      --
      - chrish
  2. master of the obvious by hometoast · · Score: 2, Insightful
    byte b = -1;
    char c = (char)b;
    so c=-1, right? Wrong. Places like this are things that you could potentially knock your head against the wall trying to figure out why something doesn't do what it appears to do.
    (In this case, byte is signed, char isn't, and the widening cast fills in bits, leaving c=65535.)


    That's not expected??
    1. Re:master of the obvious by AKAImBatman · · Score: 4, Insightful

      Amen. The Java Language Specification states that char IS NOT A NUMBER. It's a character representation and should be treated as such. Thus the entire example is contrived, and makes no sense. It *might* be interesting from the perspective of loading a file (e.g. buffer.append((char)in.read());), except that the IO streams provide Integers to get around the sign problem.

      This is why in computer science they have a term for supposed "idiosyncracies" like this: "Garbage In Garbage Out" (GIGO)

    2. Re:master of the obvious by iabervon · · Score: 1

      Actually, the thing that's surprising is that (c == b) is false. You'd expect that the implicit conversion for equality testing would match the explicit one, whatever it is that it gives. Of course, the real issue is that Java really shouldn't have a "char" primitive, and certainly not one that accepts casts from numeric types.

    3. Re:master of the obvious by _xeno_ · · Score: 1

      Actually, the Java Language Specification is pretty clear that char is a number. From the spec:

      The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing Unicode characters.

      char, being a number, is subject to integer math operations. Like someone posted, 'A' + 'B' comes up with the result 131 - as an int, at that, because all integer math on types smaller than an int are promoted to ints.

      --
      You are in a maze of twisty little relative jumps, all alike.
    4. Re:master of the obvious by AKAImBatman · · Score: 1

      Char is actually implicitly cast to 'int' to perform mathematical operations. The char type itself has no bytecode support for math.

      In other words, char represents a Unicode value from '\u0 to \uffff'. The fact that it can be cast to a numerical value and operated on is secondary to the fact that it's not really a number and should not be treated as such.

    5. Re:master of the obvious by TummyX · · Score: 1


        It *might* be interesting from the perspective of loading a file (e.g. buffer.append((char)in.read());), except that the IO streams provide Integers to get around the sign problem.


      I think you mean readers provider integers to get around the problem. Streams only read bytes whereas readers read chars (which may consist of one or more bytes depending on the encoding).

  3. Re:garbage collector by Azarael · · Score: 2, Insightful

    I doubt that most experienced programmers would get hung up over the byte b example. I'm pretty sure that you'd get similar behaviour with C and a lot of other languages.

  4. Not interested by TreeHugger04 · · Score: 4, Funny

    If the title of a puzzle book does not contain the letters s,u,d,o,k and u in it, I am not interested. Sorry.

    --
    A citizen of America will cross the ocean to fight for democracy, but won't cross the street to vote in an election.
  5. at just the moment you want responsiveness by Anonymous Coward · · Score: 0

    yay. go java!!!

  6. /. is made of cheese by fohat · · Score: 4, Funny

    The problem being that Slashdot Headlines are often either: a) Dupes, b) boring, c) difficult to read, d) poorly written, or possibly: q) made of cheese

    To the moon, Java!

    --
    Is there heaven? Is there Hell? Is that a Tuna Melt I smell?-Primus
  7. is surprize good? by gtrubetskoy · · Score: 2, Informative
    There are several occurrences that really surprised me

    I'm somewhat puzzled by the premise of the book. I thought C/C++ was full of puzzlers, and that Java was supposed to fix all that. Puzzlers may be cute, but they are definitely bad (except for job security may be). BTW, my little test shows that this example also applies to C, except that it isn't as surprising since you have to specifically declare the variable as unsigned, e.g.

    int b = -1;
    unsigned char c = (unsigned char)b;

    Without "unsigned", char is -1, as expected.

    1. Re:is surprize good? by pammon · · Score: 1
      Not quite. Without "unsigned," c may or may not be -1, depending on your compiler and its settings. The C standard allows char to be signed or unsigned by default.

      NOW are you surprised? :)

    2. Re:is surprize good? by Anonymous Coward · · Score: 2, Informative

      Every language with some substance will evolve have its "puzzlers".

      By the way, here is a great online puzzlers lecture by the two same guys. Its located here: http://www.javalobby.com/av/javapolis/25/bloch-puz zlers?source=archives but unfortunately you'll need to login to see it. Enjoy!

    3. Re:is surprize good? by gtrubetskoy · · Score: 1
      Not quite. Without "unsigned," c may or may not be -1, depending on your compiler and its settings. The C standard allows char to be signed or unsigned by default.
      NOW are you surprised? :)

      Nope :)

    4. Re:is surprize good? by bunratty · · Score: 1
      I'm somewhat puzzled by the premise of the book. I thought C/C++ was full of puzzlers, and that Java was supposed to fix all that.
      Java is a quite a bit simpler than C++, but it certainly has its share of tricky corner cases and surprising features. I started reading through the first few chapters while browsing in a bookstore, and although I was quite proficient in Java years ago there were some puzzles that stumped me. It reminded me just how complicated parts of Java are. Anyone who claims to know Java well will probably be humbled just by browsing through this book for a few minutes.
      --
      What a fool believes, he sees, no wise man has the power to reason away.
    5. Re:is surprize good? by Schweg · · Score: 1

      Whether the base 'char' type is signed or unsigned in C is implementation dependent, which makes it a little more interesting.

    6. Re:is surprize good? by Anonymous Coward · · Score: 0

      You got it all wrong.

      Java "byte" is the equivalent of C "char".
      Java "char" is the equivalent of C "unsigned short".

    7. Re:is surprize good? by Anonymous Coward · · Score: 0
      Java "byte" is the equivalent of C "char"

      You mean "signed char"?

    8. Re:is surprize good? by Zwets · · Score: 1

      Not to nitpick, but "as expected" is only true if you know any of the established languages where this is true.

      A beginning programmer would not expect to be able to assign a number (a negative number, nonetheless!) to a variable that's supposed to hold a character.

      A more intuitive, less error-prone approach would be to disallow this assignment and provide a function to explicitly convert a number to an ASCII character. The fact that both are stored in the same way in hardware is irrelevant.

      --
      One of the lessons of history is that nothing is often a good thing to do and always a clever thing to say. - Will Duran
    9. Re:is surprize good? by owlstead · · Score: 1

      As any platform + language, Java tries to do a lot of things. And like everything in this world, it is not perfect. Some of the problems could have been avoided (the rather unnecessary overloading of the operator &, meaning both && with both expressions evaluated and the bitoperand AND). Others could not. Don't forget that Java is pretty old (1985 if I am not mistaken), and when it was invented people tended to scream at you when you did anything like wasting a byte or a CPU cycle. And some things (like unsigned support) were explicitly left out due to simplicity.

      Yes, Java could have been better (there *IS* a new language specification, so even Sun thought so) but there will always be corner cases enough to make puzzlers about. I thouroughly enjoyed reading it, though effective Java was even better.

    10. Re:is surprize good? by iabervon · · Score: 1

      Actually, that should be int8_t and uint16_t. A "char" in C can be signed or unsigned, and can be a platform-dependant number of bits. It's 8 bits on all current platforms, but that's just because 9- and 12-bit platforms have all died out. And a "short" in C can be any length that's no longer than an "int" and no shorter than a "char" (nothing can be shorter than a "char", because sizeof is defined in units of the size of char). Java defines bit lengths and such for all of the primitive types, and C only does this for the C99 integer types.

    11. Re:is surprize good? by dascandy · · Score: 2, Informative

      > Without "unsigned", char is -1, as expected.

      Without "unsigned", the signedness of char is undefined. See also the C standard (ISO 9899:1999).

      Which explains why in C++ (a derived language) special specializations were made from templates to include both signed char and unsigned char, with a third charT template type for internal "char"-like data.

      GCC includes a compile-time flag that allows you to make them unsigned (-funsigned-char).

    12. Re:is surprize good? by Anonymous Coward · · Score: 0

      Obligatory quote:

      "For portability, specify signed or unsigned if non-character data is to be stored in char variables." K&R p44.

    13. Re:is surprize good? by Jerry+Coffin · · Score: 1
      Without "unsigned", the signedness of char is undefined.

      Nitpick of the day: not "undefined" but "implementation defined".

      In C's version of standardese, "undefined" basically means something you shouldn't ever do, but the compiler isn't required to stop you from doing. "Implementation defined" means something that may vary in some way from one compiler to the next, but that it's still perfectly reasonable to do.

      --
      The universe is a figment of its own imagination.

      --
      The universe is a figment of its own imagination.
    14. Re:is surprize good? by Taladar · · Score: 1
      Don't forget that Java is pretty old (1985 if I am not mistaken)
      Actually it was invented in 1994 and is younger than most big scriping languages today, many of which support arbitary sized numbers automagically (using int for numbers small enough internally and a more complicated type for big ones). There is absolutely no excuse for Javas flaws through the age argument. Most other languages invented around that time even managed to make the primitives look like objects from the language user point of view.
    15. Re:is surprize good? by AuMatar · · Score: 1

      C and C++ full of puzzlers? C has no puzzlers- its the perfect WYWIWYG language (What you write is what you get). The compiler never assumes or makes a choice on anything. C++ has some, mainly around when constructors/destructors get called.

      Java has a shit ton. The Java language spec is several times the size of C++. Its larger even if you ignore the standard libraries. And 1.5 is just adding on more cruft. THe only other language even close to Java on this front is perl.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    16. Re:is surprize good? by Anonymous Coward · · Score: 0

      actually, whether char is signed or unsigned in C is unspecfied and implementation defined.

  8. Kind of by brunes69 · · Score: 1, Insightful

    See, to a C coder, this is non-obvious because both the types would be signed, and if you wanted it unsigned you would have to say so.

    It has always diven me nuts how Java forces its own signed-ness on it's primitives. The fact that you can't have an unsigned int in Java 1.5 is a huge pain, because it is not like it is simpler to just use char everywhere, since then you lose all the autoboxing capability of Integer/int. So, you have to deal with it yourself. It's a big mistake IMO.

    1. Re:Kind of by codegen · · Score: 5, Insightful
      See, to a C coder, this is non-obvious because both the types would be signed, and if you wanted it unsigned you would have to say so.

      Sigh... Not true. Wether chars default to signed or unsigned is vendor specific in the ANSI C spec. If you code depends on chars being signed or not then you have to state it explicitly if you want your code to be portable. I have been bitten by this on one important occasion when I was still in Industry and have never forgotten it.

      --
      Atlas stands on the earth and carries the celestial sphere on his shoulders.
    2. Re:Kind of by Erioll · · Score: 1
      The fact that you can't have an unsigned int in Java 1.5 is a huge pain

      Or even worse, the lack of an unsigned byte when reading in binary data structures. I don't claim to be a Java expert by any stretch (so I may be missing an obvious way to do this), but do you know how unnecessarily complex it is to convert a read-in byte to it's CORRECT unsigned value? Why isn't there an automatic way to do this at all? You can't just assign the byte to an int, as it'll still be negative (if above 127). I think in the end I just asigned the byte to an int, then did a bitwise-AND to throw out the extra sign bits it tacked on in the widening conversion so that it was back to positive.

      Still, something that would be easily alleviated by a simple unsigned type. Stupid that it's not there. I like Java, but an unsigned type would make these things so much easier, as it is in so common use in binary formats that it's an unnecessary impediment when it isn't easily read from/to in unsigned form.
    3. Re:Kind of by AKAImBatman · · Score: 0, Troll

      1. All Java primitives are unsigned.

      2. All Java I/O uses Integers instead of bytes to avoid the unsigned issue and better support Unicode.

      Thus the example is a stupid thing to do. You read in a whole integer (32 bits) then cast it to a char (16 bits unsigned). The char is treated as a unicode character at all times.

    4. Re:Kind of by AKAImBatman · · Score: 1

      #$@#%@#$%@#$!!! Number 1 should be:

      1. All Java primitives are signed.

      I *really* need to start proofreading. This is getting crazy.

    5. Re:Kind of by Erioll · · Score: 1

      Are you responding to the wrong comment? Your #2 talks about chars, but I said nothing about using chars as a datatype for numbers. If I wanted 16-bit numbers, I'd be using a "short". And add to that the fact that actually all java primitives EXCEPT chars are SIGNED, that kind of throws point 1 out the window too.

      But I will admit one point you have: reading in blocks of ints is another solution to my problem, as you could AND out each 8-bit component of what you want into another int (then shift obviously), and get the same result, though that's uselessly complex, as you usually do "block" reads anyways, in my case into a byte array.

    6. Re:Kind of by AKAImBatman · · Score: 1

      Are you responding to the wrong comment? Your #2 talks about chars, but I said nothing about using chars as a datatype for numbers.

      No, I'm responding to the right comment. I only mentioned chars in passing. I said ALL I/O uses Ints AND that this makes Unicode support easier.

      But I will admit one point you have: reading in blocks of ints is another solution to my problem

      Which was my point. :-)

      , as you could AND out each 8-bit component of what you want into another int (then shift obviously), and get the same result, though that's uselessly complex, as you usually do "block" reads anyways, in my case into a byte array.

      Java supports both cases. You can read arrays of values, OR you can read individual values. It all depends on what you're trying to do. Of course, usually you wouldn't want to bother with either. The I/O package contains the DataInput and DataOutput classes for easy binary I/O, and the Reader/Writer classes for easy character translation.

      And add to that the fact that actually all java primitives EXCEPT chars are SIGNED

      True. I was thinking of numerical types, as do most other people when they say that Java has no unsigned primitives.

      FYI, I'm not trying to get on your case. I'm just trying to help you understand how it's done in Java. Sorry if my brevity confused you. :-)

    7. Re:Kind of by Anonymous Coward · · Score: 0

      It's also quite handy that the int readByte() method call can return a negative one to signal EOF.

    8. Re:Kind of by cheezit · · Score: 1

      Read "Deep C Secrets" and learn about type promotion and automatic widening of primitives---there are some strange side effects when a compiler "invisibly" stores smaller data types in the native word size of the hardware. Signed vs. unsigned is one area you can see this, but there are others.

      --
      Premature optimization is the root of all evil
    9. Re:Kind of by MillionthMonkey · · Score: 2, Informative

      Or even worse, the lack of an unsigned byte when reading in binary data structures. I don't claim to be a Java expert by any stretch (so I may be missing an obvious way to do this), but do you know how unnecessarily complex it is to convert a read-in byte to it's CORRECT unsigned value? Why isn't there an automatic way to do this at all? You can't just assign the byte to an int, as it'll still be negative (if above 127). I think in the end I just asigned the byte to an int, then did a bitwise-AND to throw out the extra sign bits it tacked on in the widening conversion so that it was back to positive.

      InputStream.read() doesn't return a byte. It returns an int between 0 and 255 inclusive. -1 means EOF. The most common idiom is to do something like this:

      int i;
      int numRead = 0;
      while ((i=inputStream.read()) >= 0)
          someByteArray[numRead++] = (byte)i;


      For bytes with values between 128 and 255 inclusive, the values will become negative. And why do you care? As long as every single one of the eight bits in each byte is correct, signed vs. unsigned is in the eye of the beholder. It doesn't enter into anything unless you start doing arithmetic on the bytes or print their numeric values, both of which involve implicit casts to int. To do arithmetic, Java always converts a byte, char, or short to int using an automatic, implicit cast (it converts float to double as well). If the bytes have unsigned semantics in your program, then never allow the compiler to implement an implicit cast since implicit casts assume signed values. Replace them with explicit casts that mask out the top 24 bits to zero yourself, preserving the semantics with respect to sign:

      int intVal = (0xFF & byteVal)

      When evaluating this expression, byteVal will be implicitly cast to a signed int and then the & operator zeroes out the sign extension bits to preserve semantics. Is this "unnecessarily complex"? I don't think so. I rarely even need to do it.

      This seems to horrify people used to the unsigned-type train wreck in ANSI C but I would not welcome unsigned types being added to Java at all. The existing type system in Java is perfectly adequate for getting work done and you don't have to keep remembering whether variables were declared as signed or not if you know they're always signed.

    10. Re:Kind of by Anonymous Coward · · Score: 0

      How do you specify a signed char? Isn't that the same as simply declaring it a "char"?

      So a normal char is always signed. QED.

    11. Re:Kind of by rjshields · · Score: 1
      1. All Java primitives are unsigned.
      All Java primitives are signed apart from char which is unsigned.
      --
      In this world nothing is certain but death, taxes and flawed car analogies.
    12. Re:Kind of by Erioll · · Score: 1

      Just looked it up, and I can't believe I missed the readUnsignedByte() method of the DataInput interface, but I still have a question: any way to do this with large arrays that you know of? I can't think doing this in a loop, even if it IS from a buffered input stream would be efficient.

    13. Re:Kind of by AKAImBatman · · Score: 1

      There are tons of ways. Depends on what you're doing. :-)

      If you're just trying to process the data in large chunks, then wrap the InputStream in a BufferedInputStream before passing it to the DataInputStream. That will fill the buffer with size-configurable chunks of data every time it underflows rather than reading each byte individually. After that, the individual readUnsignedByte() calls don't matter. (CPU time is a few orders of magnitude cheaper than disk I/O, especially given the burst abilities of modern drives.)

      For maximum buffer performance, you can check the file size before loading and size the buffer to load the whole thing. Or you can simply pass a byte[] array of the right size to the FileInputStream, then initialize a ByteArrayInputStream wrapped in a DataInputStream object.

      If you're looking to do fast transforms on a lot of unsigned data, then what you need is ByteBuffers. These come in Byte, Short, Int, and Char form, and can be used to perform various types of SIMD instructions and/or access the data without bounds checking.

    14. Re:Kind of by Erioll · · Score: 1

      What I'm actually doing is bringing in image data in a 4:2:0 format (you probably don't know what that is unless you're in an imaging/video field). Basically it's a large block of data for one color band (YCrCb in my case), then two smaller bands, which are then re-expanded back to full size (there's only 1/4 as much data for the two C-bands as for the Y-one). But of course each data value is an unsigned 8-bit value. After they're all in int arrays, then I process them in triplets (one from each color band) to convert to an RGB-format, which I then do other things to. I'm already using NIO to read them into correct-sized bytebuffers all-3 at once (the data's in the file that way), but it's after that we get "messy" putting them into a processable form, due to the unsigned issues, moving them around into the larger int-arrays, etc.

      Your mention SIMD instructions intrigue me though. What can be done in Java on that front? Basically I AM doing exactly the same operation on these things, and so utilizing parallelism would be great if possible.

    15. Re:Kind of by AKAImBatman · · Score: 1
      What I'm actually doing is bringing in image data in a 4:2:0 format

      YUV! Gotta love that stuff. (Not.) Perfect for reducing bandwidth with only minor information loss, though. :-)

      I can see why you're looking for bitwise manipulation.

      As long as you're not looking for real-time performance, all you need to do is try this little trick:
      public class Test
      {
          public static void main(String[] args)
          {
              byte test = -20;
              int unsigned = (0xFF & test);
       
              System.out.println(unsigned);
          }
      }
      You should get 236 instead of -20. This works because the JVM implicitly casts the byte to an int by padding it to four bytes before performing the operation.

      Your mention SIMD instructions intrigue me though. What can be done in Java on that front?

      Me and my big mouth. Ok, here goes. This whole thing is a bit on the undocumented side, so you'll have to hang with me here. Basically the ByteBuffers give you a raw memory block on both the native and Java side. Now Java can't execute SIMD directly (though they are working on adding such a thing to the Math package in the future), but it can define and control such streams. So what you want is to create an SPI plugin that creates a channel that does what you want. In your channel code, you need an input buffer and an output buffer. (Or at least, I assume. You can operate on the same data if you want, but I assume you're converting to the much larger RGB format.) You can then select the processor in your code. You'll probably want a pure Java version that uses the trick above to perform the conversion to fall back on. But for systems where you have native drivers, you can use JNI to write a small bit of C/C++/Assembler to execute a bit of SIMD on the two byte buffers.

      Basically, you want to tell the SIMD instructions (be they SSE, Altivec, or Sparc SIMD) to operate on the memory block at the byte buffer location, and put the results of the operations at the second byte buffer memory location. You would then have a super-fast YUV -> RGB channel with only a minor amount of optional accelerator code.

      Now, with that out of the way, can I ask a question? Is there any chance that the ImageIO package or JMF already does what you need? (JMF has a bunch of fast YUV stuff built-in.)
    16. Re:Kind of by Erioll · · Score: 1

      Ya JMF seems like it has something: com.sun.media.codec.video.colorspace.YUVToRGB, along with other things in the package like javax.media.format.YUVFormat. Of course that means I'd need to LEARN JMF, which for what I'm doing might not be a bad thing, but still, it's another library that I don't know yet.

      And as I put in my original reply above, the bitwise-AND is what I was already doing, as I couldn't see any other way. Was hoping for some type of builtin with native methods to do it faster.

      Thanks for your help man.

    17. Re:Kind of by AKAImBatman · · Score: 1

      Of course that means I'd need to LEARN JMF, which for what I'm doing might not be a bad thing, but still, it's another library that I don't know yet.

      Can't help you there. It's been forever since I last used the bugger. :-)

      And as I put in my original reply above, the bitwise-AND is what I was already doing

      Oh, sorry. I missed that part. Well, hope some of what I said was useful, anyway.

      Thanks for your help man.

      Wish I could do more, but it sounds like you've generally got a good grasp on things. I'm not precisely sure what you're doing (PAL capture?), but the bitwise and should serve you well for most everything you'd need to do. If you really need the performance, then the SIMD route might be worth exploring. :-)

    18. Re:Kind of by codegen · · Score: 1
      How do you specify a signed char?

      signed char c;

      As I said before if you say just

      char c;

      it may be signed, it may be unsigned, it depends on the vendor of your compiler.

      --
      Atlas stands on the earth and carries the celestial sphere on his shoulders.
  9. Yikes! by Anonymous Coward · · Score: 3, Funny

    If that c != -1 example isn't obvious, it may be safe to assume that former VB programmers have started programming in Java! Run!

  10. Thats the whole point of the "puzzler" by brunes69 · · Score: 4, Insightful

    It is to expose a flaw in the language.

    Why should a primitive byte be signed, but not a primitive char?

    And why can't I have an unsigned int primitive in Java?

    Primitives in Java are a real pain to work with compared to most languages.

    1. Re:Thats the whole point of the "puzzler" by $RANDOMLUSER · · Score: 4, Insightful
      > Why should a primitive byte be signed, but not a primitive char?

      Because a byte is a numeric class, and a char is a character class? Your question is like asking why booleans can't be signed or unsigned.

      --
      No folly is more costly than the folly of intolerant idealism. - Winston Churchill
    2. Re:Thats the whole point of the "puzzler" by John+Courtland · · Score: 1

      Agreed. There is no Unicode value -1, so how does it make sense that you should be allowed to store that value in a type that represents a system where that value doesn't exist? I think it makes perfect sense, and I'm a pretty damn hardcore C fanboy. I never did like the unsigned-ness of char, I always thought there should have been a type 'byte' that represented an unsigned 8-bit value, and left char to deal with ASCII stuff.

      Off topic, but is there any C that defines sizeof(char) != 1? I'd be interested to know.

      --
      Slashdot is proof that Sturgeon's Law applies to mankind.
    3. Re:Thats the whole point of the "puzzler" by the+grace+of+R'hllor · · Score: 1

      Because a byte is simply an 8-bit value, either -127 - 128 or 0 - 255. A char represents a character, and the number is the ASCII number for that character. ASCII numbers don't run into the negative, therefore a char is always unsigned.

      Makes sense to me.

    4. Re:Thats the whole point of the "puzzler" by Surt · · Score: 1

      The rationale is that char is a type representing a character, and that in such a context a negative value doesn't make any particular kind of sense. A char is an index into unicode, nothing more. A byte is a data representation, so sign makes sense in that context.

      You can't have an unsigned int primitive because that would lead to confusion when trying to index into arrays. The type of an array index is signed int, and is that way for a bounds checking reason. If you had access to a primitive unsigned int, no doubt you'd be irritated that you couldn't use it to index an array.

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
    5. Re:Thats the whole point of the "puzzler" by Anonymous Coward · · Score: 0

      No. Byte primitives are always signed in Java. And char is unsigned 16 bit because it's not ASCII but rather Unicode. Or that was the idea anyway. Of course it's not enough to address anything but the first base plane of Unicode, but that's been sort-of fixed in the latest versions of Java.

    6. Re:Thats the whole point of the "puzzler" by helix_r · · Score: 1


      That never really stuck me as a reasonable explanation.

      I always felt it was a cop out at some level on the part of java to exclude unsigned ints. Its java, for christ's sake, can't the array bounds issue be taken care of?

    7. Re:Thats the whole point of the "puzzler" by sadr · · Score: 1

      I've worked on a C compiler for a DSP (Oak) that had sizeof(everything) == 16 bits.

      But I think sizeof(char) is by definition "1" and everything else is a multiple thereof.

    8. Re:Thats the whole point of the "puzzler" by Surt · · Score: 1

      I think the problem is that Sun is too opposed to making language level changes (anything that requires a change in the VM). They've done so much work in optimizing the performance for the existing VM, they're afraid of anything with consequences for their optimizer, and unfortunately from that perspective it seems fairly clear that allowing for unsigned ints would present a danger to the optimizer.

      Frankly, I'm with you though, I wish they would just bite the bullet and fix up the raw types to have a signed and unsigned version for every size, and then fix up the bitwise operations to allow auto casting to boolean as well. But we'll never see it.

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
    9. Re:Thats the whole point of the "puzzler" by kaffiene · · Score: 4, Insightful

      >Primitives in Java are a real pain to work with compared to most languages.

      Bullshit. I've coded through asm, c, c++, java and they all have their own ways of doing things which you need to be aware of. The language is NOT the problem.

    10. Re:Thats the whole point of the "puzzler" by stymyx · · Score: 1

      Off topic, but is there any C that defines sizeof(char) != 1? I'd be interested to know.

      By definition, in C, sizeof(char) == 1. However, theoretically, bytes don't have to be 8 bits long. Though I don't know of any modern machine with such bytes.

    11. Re:Thats the whole point of the "puzzler" by _xeno_ · · Score: 4, Informative

      What's the difference between short and char in Java?

      One is signed, the other is unsigned.

      chars are treated just like numbers in Java. You can do numeric comparisons with them, you can add them, you can subtract them, they're just numbers.

      By definition, a char in Java is a 16-bit unsigned value. It happens to represent a single UTF-16 sequence, although arguably you could have done that using a short.

      But, here, check the language spec. A char is just an unsigned short. That's it.

      --
      You are in a maze of twisty little relative jumps, all alike.
    12. Re:Thats the whole point of the "puzzler" by John+Courtland · · Score: 1

      Thanks. I have used 7-bit byte machines before, but obviously they are mostly relics now. I'm curious though, why the C drafters chose the word 'char' as the name for that type as opposed to 'byte'.

      --
      Slashdot is proof that Sturgeon's Law applies to mankind.
    13. Re:Thats the whole point of the "puzzler" by jcoleman · · Score: 1

      One generally uses Java for its excellent OO-ness, not because they want to use primitives...

    14. Re:Thats the whole point of the "puzzler" by jiushao · · Score: 1
      Why should a primitive byte be signed, but not a primitive char?

      Because all numeric types are signed in Java, whereas char is not intended as a numeric type but rather a direct mapping to UTF-16 (which uses codepoints 0 through 65535). It makes perfect sense.

      And why can't I have an unsigned int primitive in Java?

      Highly debatable issue, but I think the simplification in types is worth more than unsigned types are.

    15. Re:Thats the whole point of the "puzzler" by stymyx · · Score: 1

      I guess that when C was being designed, "character" was a more common term for the smallest data size on a computer than "byte".

      Even stranger, is that in C the type of a character literal (e.g. 'A') is int - not char!

    16. Re:Thats the whole point of the "puzzler" by micromuncher · · Score: 1

      Supposedly that was Gosling's reason: unsigned types complicate code and produce nasty logic errors.

      So, the types reflect the signedness of their use. However, I've rarely if ever used signed bytes... I have tons of (int)b&0xFF in my wire savvy code :-(

      --
      /\/\icro/\/\uncher
    17. Re:Thats the whole point of the "puzzler" by Anonymous Coward · · Score: 0

      > Your question is like asking why booleans can't be signed or unsigned.

      What about false positives?

    18. Re:Thats the whole point of the "puzzler" by AKAImBatman · · Score: 1

      By definition, a char in Java is a 16-bit unsigned value. But, here, check the language spec. A char is just an unsigned short. That's it.

      I think you misunderstand the spec. From your link:

      For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535

      Just because it's a numerical value doesn't mean that it's an actual number.

      chars are treated just like numbers in Java. You can do numeric comparisons with them, you can add them, you can subtract them, they're just numbers.

      This is incorrect. If you check the Java Virtual Machine Specification you'll find a distinct lack of numerical operations for the 'char' datatype. In order to provide you numerical functions for a char value, the value is treated as if it were an int. (i.e. An implicit cast.) From the spec:

      Conditional branches on comparisons between data of types boolean, byte, char, and short are performed using int comparison instructions (3.11.1) Note that no operations exist in the bytecode to do math on chars. Thus to get the results, the char is implicitly casted to an int, processed, then cast back to a char as necessary.

    19. Re:Thats the whole point of the "puzzler" by alw53 · · Score: 1

      Adding unsigned operators would burn a whole lot of opcode space and
      there are only 256 potential opcodes. You'd need unsigned comparisons,
      unsigned flavors of all the arithmetic operators for each data width and
      so forth. Probably have to introduce a one-byte "unsigned" prefix, and you
      might have to deal with the combination of the "unsigned" prefix and the
      "far" prefix for conditional jumps. This would slow down, complexify, and
      expand the size of the interpreter, which already takes 8 Meg to print
      "Hello World". It was much simpler to just pre-define the signedness of
      each data type rather than allow signedness to vary independently.

    20. Re:Thats the whole point of the "puzzler" by _xeno_ · · Score: 1

      And this differentiates char from short how, exactly?

      The answer? A short gets translated to an int using a signed cast, and a char gets translated to an int using an unsigned cast.

      Beyond that, the two data types are identical.

      In fact, that whole "always convert to integer" thing essentially makes the use of bytes and shorts completely worthless outside of arrays, since all math done using them is just integer math.

      --
      You are in a maze of twisty little relative jumps, all alike.
    21. Re:Thats the whole point of the "puzzler" by AKAImBatman · · Score: 1

      And this differentiates char from short how, exactly?

      That's a good point. I supposed I should have also mentioned that byte and short are really just for low-footprint memory storage. 'int' is the currency of choice in the Java language. Casting up to int ensures that all math happens in a byte aligned fashion, not to mention that reduces the amount of silicon required by an embedded Java processor.

    22. Re:Thats the whole point of the "puzzler" by TimeZone · · Score: 1
      Because a byte is a numeric class, and a char is a character class? Your question is like asking why booleans can't be signed or unsigned.

      Being a hw designer, I find it strange that a byte would be considered a numeric class. A byte is just a byte. How you treat it depends on what you want to do with it.

      TZ

    23. Re:Thats the whole point of the "puzzler" by Taladar · · Score: 1

      Excellent? I suppose you know no other OO languages, do you?

    24. Re:Thats the whole point of the "puzzler" by Profound · · Score: 1

      > Why should a primitive byte be signed, but not a primitive char?

      Because that's the way Sun defined it (duh)

      > And why can't I have an unsigned int primitive in Java?

      Because Sun doesn't think you're smart enough for it.

      > Primitives in Java are a real pain to work with compared to most languages.

      I've never had any problem with primitives as such... The thing I hate is the unnatural division between primitives and objects. Going back 50+ years, lisp-like functional languages build new definitions on top of previous ones. The answer to which of "if" or "cond" is built in, and which is defined in terms of the other is "who cares". It all looks the same.

      You can look at the whole history of computer languages as refining the idea "let the user create abstract data types that work as seamlessly in the language as the primitives".

      Except for Java.

      You can't define operators on your objects, so you end up horrific code like anything to do with BigDecimal. Centuries of refinement of arithmetic symbols and operations by mathematicians is tossed in the trash (sorry, garbage collected) with Java's .add() and .equals() which produce the ugliest code since COBOL.

      Objects are not just crippled compared to primitives, but primitives are crippled compared to Objects! You can't put them in containers!

      This has been bandaided over with autoboxing, but this comes at a cost of class hierarchies, increased compiler magic and performance (especially memory) cost. Autoboxing and the Integer/Float objects are a total hack to get around the bad decision to make primitives and objects distinct. To reduce the memory bloat Integers from -128->127 are stored in a static pool on the JVM while the others are on the heap.

      There are lots of ways to store numbers on computers. Fixed point, floating point, signed/unsigned, 2's compliment, etc, but to store them as 16+ byte lockable objects that reference static pools of "number" in the JVM is certainly be the most retarded.

      The only reason I can see for the awful primitive/object split is for those laughable tests using primitives which "prove" Java is as fast as C++. For 99% of stuff, who cares? I'd rather Java be twice as slow if it wasn't so damn ugly.

    25. Re:Thats the whole point of the "puzzler" by rjshields · · Score: 1
      Conditional branches on comparisons between data of types boolean, byte, char, and short are performed using int comparison instructions (3.11.1) Note that no operations exist in the bytecode to do math on chars. Thus to get the results, the char is implicitly casted to an int, processed, then cast back to a char as necessary.
      And the GP said: "chars are treated just like numbers in Java", to which you said: "incorrect". So by your logic, shorts are not treated like numbers in Java either... Nice work, Einstein.
      --
      In this world nothing is certain but death, taxes and flawed car analogies.
    26. Re:Thats the whole point of the "puzzler" by rjshields · · Score: 1

      The biggest joke is that in Java byte is signed and char is not. Semantically speaking, neither are numerical types. Why do I need a sign on my byte?

      --
      In this world nothing is certain but death, taxes and flawed car analogies.
  11. Re:Puzzling indeed by $RANDOMLUSER · · Score: 3, Insightful

    1) Code readability.
    2) Speed of development.
    3) Lack of "cute" features that break easily.
    4) Javadoc!!
    5) Bazillions of pre-written, pre-tested source-available library functions.

    --
    No folly is more costly than the folly of intolerant idealism. - Winston Churchill
  12. Because characters aren't numbers. by MS-06FZ · · Score: 2, Insightful

    I think the whole notion of a "character" type being assigned a numerical value is dubious in the first place. That's not to say the idea of a character coding that translates between characters and numbers isn't sensible, but the character itself is not a number - it's a character. I like Python's approach to the solution - there simply is no "atomic" character type (defining such a thing when character sets have characters that aren't uniform size is questionable anyway)

    So given that characters aren't numbers, is it really so hard to imagine that people see that code and can't readily guess what sort of number a character is? I guess one could say that the character set is indexed with non-negative integers, so the character type should be non-negative - but a logical derivation isn't the same as a plain fact, and other languages aren't so sensible in those kinds of decisions...

    --
    ---GEC
    I'm but the humble pupil, seeking to snatch the scratchbuilt pebble from the master's fully articulated hand
    1. Re:Because characters aren't numbers. by AKAImBatman · · Score: 2, Informative
      I think the whole notion of a "character" type being assigned a numerical value is dubious in the first place.

      Can't be helped. You have to give the computer a way of understanding characters. Array indexes are a natural way for computers to do that.

      That's not to say the idea of a character coding that translates between characters and numbers isn't sensible, but the character itself is not a number - it's a character.

      A character in Java *is* a character. Nothing more, nothing less. It's a character. What the author did was stupid. The only time you cast a character like that is when you're doing I/O. For example:
      InputStream in = new FileInputStream("Text File.txt");
      StringBuffer string = new StringBuffer();
      int data;
       
      while((data = in.read()) >= 0)
      {
          string.append((char)data);
      }
      Note that in.read() returns an Integer of byte data, so the sign problem never shows up.

      I like Python's approach to the solution - there simply is no "atomic" character type (defining such a thing when character sets have characters that aren't uniform size is questionable anyway)

      Java Characters *are* a uniform size. Every character is a 16 bit Unicode character. That's why you're not supposed to do what I just did in the example above (read in a byte at a time) because you may chop up the Unicode encoding. Instead you're supposed to use a Reader object, which will return 'char' values instead of 'int' values.
    2. Re:Because characters aren't numbers. by MS-06FZ · · Score: 1

      Can't be helped. You have to give the computer a way of understanding characters.

      Indeed... But why have the numeric equivalence in the programming language? 'A' is not equivalent to 65 except in the particular context of a character set that defines that equivalence. Keep characters characters and keep numbers numbers.

      Java Characters *are* a uniform size. Every character is a 16 bit Unicode character.

      But Unicode doesn't fit into 16 bits. UTF-16 is a variable-width encoding. So I guess maybe Java supports UCS-2, and the BMP subset of Unicode? Or else it supports UTF-16 and your assertion is false. But in any case my point is simply that in international character sets the idea of what constitutes a "single character" is somewhat muddled, because what may be a single glyph may be multiple data characters - I don't think intermixing the two ideas is an especially good idea in a high-level programming language.

      --
      ---GEC
      I'm but the humble pupil, seeking to snatch the scratchbuilt pebble from the master's fully articulated hand
    3. Re:Because characters aren't numbers. by AKAImBatman · · Score: 1

      Indeed... But why have the numeric equivalence in the programming language? 'A' is not equivalent to 65 except in the particular context of a character set that defines that equivalence. Keep characters characters and keep numbers numbers.

      1. Input/Output. Since you only have numbers in computers, you have to transmit the characters somehow.

      2. Logical operations. Character sets often have bit encodings or numerical spacings that easily allow for things like lower case to upper case.

      But Unicode doesn't fit into 16 bits.

      When the Java Langauge was created, it did. The Unicode spec has since change. A more complete answer can be found here. FYI, the class files encode strings in UTF-8 format for compactness, so they DO vary. However, the language itself works differently.

      But in any case my point is simply that in international character sets the idea of what constitutes a "single character" is somewhat muddled, because what may be a single glyph may be multiple data characters

      Java provides a large number of APIs (such as the Reader/Writer classes) that are intended for use rather than rolling your own. That way one can be certain that you are always correctly reading the textual data.

    4. Re:Because characters aren't numbers. by rjshields · · Score: 1

      I hope there are no double byte characters in that text file.

      --
      In this world nothing is certain but death, taxes and flawed car analogies.
    5. Re:Because characters aren't numbers. by AKAImBatman · · Score: 1
      Dude, you seem to have a serious case of "acting before you think". First you correct a mistake that I'd corrected myself (the signed/unsigned thing that everyone except you noticed), now you're correcting something I just pointed out myself. From the post you replied to:

      "Every character is a 16 bit Unicode character. That's why you're not supposed to do what I just did in the example above"

      Gee. wonder why I said that?
    6. Re:Because characters aren't numbers. by rjshields · · Score: 1

      I noticed your correction about the signed/unsigned bit, the point of my post was to point out that char is unsigned (you said all primitives are signed).

      Actually in UTF-8 some characters are single byte.

      --
      In this world nothing is certain but death, taxes and flawed car analogies.
    7. Re:Because characters aren't numbers. by AKAImBatman · · Score: 1

      I noticed your correction about the signed/unsigned bit, the point of my post was to point out that char is unsigned (you said all primitives are signed).

      Ah, ok. I see your point. Another poster and I had already discussed that in the same thread. FYI, 'char' doesn't really count because it isn't actually a number, its a binary representation of a 16-bit Unicode character. It has to be converted to an INT before any operations can be performad on it. INTs are of course, signed.

      Actually in UTF-8 some characters are single byte.

      Java Chars are not UTF-8. They're full 16 bit Unicode characters. The lower 127 values, of course, map to the ASCII character set. As for storing/transmitted values, using a Reader or Writer will properly handle the Unicode encoding whether you're using UTF-8 or UTF-16. That's why you're not supposed to load strings the way I did in my original post. ;-)

    8. Re:Because characters aren't numbers. by rjshields · · Score: 1
      FYI, 'char' doesn't really count because it isn't actually a number
      You said primitive, not number. This is /. and if you post factually incorrect stuff, expect people to correct you.
      --
      In this world nothing is certain but death, taxes and flawed car analogies.
  13. Books and Papers by NitsujTPU · · Score: 0, Offtopic

    When you have spare time and decide to do something with a book (That's like an analog webpage, for the neuronauts among us), how often do you turn to a computer related book? How often has it happened in the last year? Right. The problem being that computer books are often either: a) boring, b) difficult to read, c) poorly written, or possibly: d) made of cheese

    Being a computer science grad student... I imagine myself to be among the nerdy. Interestingly, I own an assortment of books, spend most of my time that isn't in a lab in a library, and read about 6-7 hard-copy academic papers a week, in addition to an assortment of books. When I have free time, I read books on AI.

    1. Re:Books and Papers by Anonymous Coward · · Score: 0

      Sigh. Still trying to get GirlFriend 0.9 to work, eh?

    2. Re:Books and Papers by Alphabet+Pal · · Score: 1

      Tell me about it - most wives complain about their husbands watching too much football; my wife complains about the amount of time (and money) I spend on computer books. I can't imagine wasting any of my (rarer and rarer) spare time with a book that wasn't about computers.

      --
      Because you can't spell "slaughter" without "laughter"
    3. Re:Books and Papers by NitsujTPU · · Score: 1

      "offtopic" indeed.

    4. Re:Books and Papers by rjshields · · Score: 1
      Interestingly, I own an assortment of books, spend most of my time that isn't in a lab in a library, and read about 6-7 hard-copy academic papers a week, in addition to an assortment of books.
      Interestingly? Do you really think people are interested to read you boast about how nerdy you are?

      *snore*

      Bring on the paint drying, I need some real entertainment.
      --
      In this world nothing is certain but death, taxes and flawed car analogies.
    5. Re:Books and Papers by NitsujTPU · · Score: 1

      Well, the poster had said that nobody reads computer books. My answer is that I read computer books. Not only that, but I'm surrounded by people who both read and write computer books. Not only that, but I spend, arguably, 25-50% of my time reading such literature, and a greater amount of time pursuing its authorship.

    6. Re:Books and Papers by rjshields · · Score: 1
      Well, the poster had said that nobody reads computer books.
      Sorry, I missed that. The nature of /. is that you don't always see the context of what of has been said, which is why I always include the relevant context as a quote. Sorry if my comment seemed harsh, I also spend a lot of time reading computer related material, but not quite as much as the GP.
      --
      In this world nothing is certain but death, taxes and flawed car analogies.
    7. Re:Books and Papers by NitsujTPU · · Score: 1

      Not a problem.

  14. Re:Puzzling indeed by Anonymous Coward · · Score: 0

    Ya, no kidding right? Java==(tehsuxx0rz)++; Just remember who was in charge of Java development: Eric Schmidt, uber-billionnaire CEO of Google.

  15. Java puzzles? I do them everyday by helix_r · · Score: 3, Insightful


    Unfortunately, real-life java problems are never very interesting.

    Invariably the solution consists of editing an annoying xml config file, or perhaps correcting one of my daily misconceptions about some boring detail in whatever convoluted j2ee framework I am forced to work with.

    1. Re:Java puzzles? I do them everyday by Anonymous Coward · · Score: 0

      bingo! This pretty much sums j2ee development.

    2. Re:Java puzzles? I do them everyday by Surt · · Score: 1

      Real life java challenges can be interesting. Do you live close enough to San Mateo and want to consider a new job? The company I work for provides some good challenge, doing mostly java development, and can't ever find enough qualified people. Write me back if you'd be interested in more info.

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
    3. Re:Java puzzles? I do them everyday by Decaff · · Score: 4, Insightful

      Unfortunately, real-life java problems are never very interesting.

      Virtually all real-life coding problems are uninteresting. It is nothing to do with Java.

    4. Re:Java puzzles? I do them everyday by nicklott · · Score: 1

      I wish I had mod points for you...

    5. Re:Java puzzles? I do them everyday by avalys · · Score: 1

      It sounds like you need a new job. Or a new field.

      Maybe I just haven't burnt out yet, but I find most [i]coding[/i] problems interesting.

      Editing an XML configuration file isn't that interesting, I'll grant you that, but no one calls that "coding".

      --
      This space intentionally left blank.
    6. Re:Java puzzles? I do them everyday by lowe0 · · Score: 1

      As a coder, I find that maybe 15% of my job is interesting, and I get to that part about half an hour into whatever I'm working on (after I've got the stubs laid out from UML and have started figuring out how to make everything work together).

      After that, it's all downhill. No one likes writing relational-to-object instantiation code (and yeah, I know, Hibernate. It took me a year to get real OO techniques in place around here, so convincing others of the benefits of an ORM might take a while.)

    7. Re:Java puzzles? I do them everyday by bennini · · Score: 1

      HAHHAHA. if i had mod points id give u +3! god... i couldn't have put it any better!

      the best is when u start using a framework to help with some other framework that helps you work with yet another framework....
      like AppFuse which helps you work with Spring which helps you work with J2EE....

    8. Re:Java puzzles? I do them everyday by I+Like+Pudding · · Score: 1

      I once had to make a java server support 10,000 simultaneous connections with NIO while it was still in beta. This had to scale across multiple processors/threads. The broadcaster client would upload xml diffs (which were valid xml themselves) because the DOM was too big to upload fully over a 56k line (I was getting the xml from a DOS app I couldn't alter - not my choice). The server would apply the diffs to its own DOM, XLST it into a cut down schema (like 1/3rd the size), then diff THAT and broadcast the diff to the Flash clients.

      The end result was about 5 seconds end-to-end latency. I had also been able to put 80k messages through the server in a minute with 10,000 clients active on a an ultrasparc II or III 450mHz. Did I mention this was clustered?

      That was pretty goddamn interesting.

      The current real life non-java problem I am working on involves writing arcane reporting queries for a SOX audit. This is SIGNIFICANTLY LESS INTERESTING. I'd gnaw off my own leg to run away if I had the opportunity to do something like that again in Java. There is more to the language than bloatacular J2EE bloat-enabled frameworks.

    9. Re:Java puzzles? I do them everyday by Decaff · · Score: 1

      It sounds like you need a new job. Or a new field.

      Maybe I just haven't burnt out yet, but I find most [i]coding[/i] problems interesting.


      Ah, but I said most coding jobs. I am lucky to a range of interesting coding things, but I realise I am in a minority.

  16. Re:Puzzling indeed by Anonymous Coward · · Score: 0

    Just to piss you off.

  17. Code books in general? by RingDev · · Score: 3, Insightful

    Why bother? I have 1 HTML/CSS book I keep on hand just because I've used it so much. Everything else, I use google. Its faster (for me) to find designs, references, and code samples online then it is for me to get a book, look up the index and flip through the pages. I even gave up on my old SQL bible as Google can get me syntax and samples faster then I can find them in the book.

    -Rick

    --
    "Most people in the U.S. wouldn't know they live in a tyrannical state if it walked up and grabbed their junk." - MyFirs
    1. Re:Code books in general? by ForumTroll · · Score: 2, Insightful

      The tutorials and code samples that are online are often trivial when compared to the in depth detail that you will find in a good book. Also, they're often out of date and some what misinformed. Don't get me wrong, I've done a lot of research online and lots of the information was very well presented and put together however I don't think I've ever seen a tutorial or paper that is as good or equivalent to some of the professionally written books available. I also hate reading large books or tutorials online. Perhaps, it's just a personal preference of mine.

      On a side note, if I had something that was small and lightweight I would probably start using http://safari.oreilly.com/">Safari Bookshelf. For several reasons, I just can't seem to enjoyably read an entire books worth of information sitting at my desk reading off a monitor.

      --
      "A Lisp programmer knows the value of everything, but the cost of nothing." - Alan Perlis
    2. Re:Code books in general? by ForumTroll · · Score: 1

      Bah, damn typos. I need to use preview more often.... Here's the correct link to Safari Bookshelf.

      --
      "A Lisp programmer knows the value of everything, but the cost of nothing." - Alan Perlis
    3. Re:Code books in general? by Blakey+Rat · · Score: 1

      This post is like "free karma." It shows up for every damned book review, and some moderator bumps it up every time. Like clockwork.

  18. I'm sure by jkind · · Score: 2, Funny

    I'm sure a book called C Puzzlers would sell at least twice as well as this.

    --
    ~jennifer.k~
    1. Re:I'm sure by Jerry+Coffin · · Score: 1
      I'm sure a book called C Puzzlers would sell at least twice as well as this.

      Would you settle for slightly different titles like these?
      C Traps and Pitfalls
      Enough Rope to Shoot Yourself in the Foot

      Fortunately, there's also:
      The C Answer Book
      Which obviously has all the answers. :-)

      Actually, none of these is settling at all -- all three are excellent books, at least IMO. Much of Holub's book also applies about as well to Java as to C or C++, for that matter.

      --
      The universe is a figment of its own imagination.

      --
      The universe is a figment of its own imagination.
    2. Re:I'm sure by LowneWulf · · Score: 1

      Sure, if you measure sales by mass. That would be quite the thick book!

  19. Re:Buy it here! by Anonymous Coward · · Score: 3, Informative

    I'm curious as to why this user's post was marked "informative". There are many places to buy the book, and the story provided one. In fact, the only significant difference between this link and the story is that this person has apparently posted a referral link to make some money.

  20. mmm... book made of cheese... by drmike0099 · · Score: 1

    drool...

    1. Re:mmm... book made of cheese... by Anonymous Coward · · Score: 0
      "Who ate page 9?? I said who ate my page 9??!!"

      Or worse, someone eating the ending of a novel.. that would really suck.

  21. Re:Puzzling indeed by masklinn · · Score: 1

    As far as I can tell, only 4 can qualify in favour of Java.

    1, 2, 3 and 5, on the other hand, should drive devs towards Python or Ruby.

    --
    "The way we can tell it's C# instead of Haskell is because it's nine lines instead of two." -- wadler
  22. What is better: by Anonymous Coward · · Score: 0

    The problem being that computer books are often either: a) boring, b) difficult to read, c) poorly written, d) made of cheese or possibly: e) sex with a mare?

    1. Re:What is better: by Anonymous Coward · · Score: 0

      f) Cowboy Neal

  23. Online Version? by kevin_conaway · · Score: 2

    Is there an online version? This seems like the type of thing I'd do on my lunch break or when I need a diversion. Something along the lines of the Python Challenge, would be cool. To me, it seems more natural to do these puzzles in soft form.

    1. Re:Online Version? by mysqlrocks · · Score: 1

      Is there an online version?

      Why yes there is:
      http://msdn.safaribooksonline.com/?XmlId=032133678 X

    2. Re:Online Version? by Anonymous Coward · · Score: 0

      yeah, how about a "java puzzler a day" rss feed? A title, an image, a short text description, and the answer to yesterday's puzzler. That's a good idea. Yup. I'm a freakn' genius.

  24. How many java apps are you running? by Anonymous Coward · · Score: 0

    Peoples, look at your desktop.

    How many java apps are there?

    How many C/C++/ObjectiveC are there? (hint: your browser, email, OS, shell, image editor, spreadsheet, wordprocessor are)

    Now do you get it?

    The purpose of Java is to have an object oriented version of Pascal for teaching freshmen some simple concepts. The real world doesn't use it very much.

  25. Missing Option by Anonymous Coward · · Score: 3, Insightful

    Most technical books are: ...

    E) Out of date before the ink is dry.

    1. Re:Missing Option by Miniluv · · Score: 2, Interesting

      Thats why I buy technology books instead. If I want a technical reference I use the internet, but if instead I want a book that explains the concepts and assumptions of a specific technology, and then walks through some use cases where the technology makes sense versus some where it doesn't, then it won't go out of date until that whole technology does. I've gotten a tremendous benefit from reading books like this on SANs, performance optimization, various wireless technologies, SIP, etc. All techs that have been around for years, show no signs of disappearing, and none of the books talked about how to implement them using a specific vendor solution, but instead talked about how to evaluate the overall environment and determine if the technology was right.

  26. View it here! by Anonymous Coward · · Score: 0
    And if you sign up for a free SDN account, you can view the authors' presentation on the subject at this year's JavaOne Conference in San Francisco here.

    I was there, and I found it quite entertaining and informative.

  27. Re:How many java apps are you running? by Doctor+Faustus · · Score: 1

    The purpose of Java is to have an object oriented version of Pascal for teaching freshmen some simple concepts. The real world doesn't use it very much.

    I was using an object oriented version of Pascal (Turbo Pascal 7) before Java existed. My high school didn't teach the Object Pascal features, but they were there.

    Java is being used heavily, but more for information systems work than software you'd buy at a store.

  28. Made of cheese? by Mistshadow2k4 · · Score: 1

    Ok, so where are these books that are made of cheese? I'm hungry! Are any made of sharp chedar? Monterey Jack?

    --
    I dream of a better world... one in which chickens can cross roads without their motives being questioned.
  29. disappointed -- try the java cert exam by SamSeaborn · · Score: 4, Insightful
    I was excited when I saw the "Java Puzzlers" subject heading. But that byte to char example left me under-whelmed.

    Have any other more interesting/fun examples?

    If you want some puzzlers, look for copies of the Sun Java Programmer certification exam. There's lots of "we're not testing to see if you're a good programmer, just testing to see if you can find the unexpected result in the insanity-pepper code" snippets there.

    boxlight

    1. Re:disappointed -- try the java cert exam by Anonymous Coward · · Score: 0
    2. Re:disappointed -- try the java cert exam by mmusson · · Score: 2, Insightful

      I enjoy obscure code examples as an antidote to drinking the Java is perfect Koolaid. Examples like:

         private int foo()
         {
            try
            {
               return 0;
            }
            finally
            {
               return 1;
            }
         }

      --
      SYS 49152
    3. Re:disappointed -- try the java cert exam by Anonymous Coward · · Score: 0

      I use this book to entertain the programmers at meetings.

      Here's my favorite, since it stumped the whole team:

      public class p {

              public static void main(String[] args) {
                      int i5 = 567;
                      int i4 = 456;
                      int i3 = 345;
                      int i2 = 234;
                      int i1 = 123;
                      int i0 = 012;

                      int a = i1 + i0; //System.out.println("i1=" + i1); //System.out.println("i0=" + i0);
                      System.out.println("a=" + a);
              }

      }

      Why does this print out:
      a=133

      /* comments added as a hint */

    4. Re:disappointed -- try the java cert exam by HanClinto · · Score: 1

      Took me a little while, but here's my guess (rot13 encoded)

      Vg ybbxf yvxr cersvkvat n pbafgnag ol gur ahzore 0 vf n jnl gb fcrpvsvl gung gur ahzore vf va bpgny. Gurersber, 012 vf gur fnzr nf fnlvat bpgny 12, juvpu vf, bs pbhefr, gra.

      However, I've never coded in Java, so that's just my uninformed guess. Regardless, that's a pretty good puzzler. :) Thanks!

    5. Re:disappointed -- try the java cert exam by dloose · · Score: 1

      Err... putting a zero before a number is Java's syntax for octal number entry. I thought it was annoying at first, but then I remembered that I would never, ever use leading zeros. Anyway, i1 = 123, i0 = octal 12 = 10 123 + 10 = 133

    6. Re:disappointed -- try the java cert exam by Anonymous Coward · · Score: 0

      Sometimes I want to shoot the person who thought of octal numbers :(

    7. Re:disappointed -- try the java cert exam by warriorpostman · · Score: 1

      I believe you meant "Guatemalan-insanity-pepper code".

    8. Re:disappointed -- try the java cert exam by Anonymous Coward · · Score: 0

      That wasn't even hard. I'm guessing your team doesn't have too much experience with C in UNIX land, where octal is actually used every now and then.

    9. Re:disappointed -- try the java cert exam by badbrownie · · Score: 1

      I went to see the authors give a presentation on this subject (I guess we were a last minute focus/qa group) and found it fascinating. Unfortunately I don't recall any examples well enough to include here but they relate to all sorts of java topics and their idiosynchrycies.

      One interesting point is that if you want to play with the examples in your ide, don't use Eclipse! Apparently the authors have close ties with the Eclipse folks and they got an advanced copy of the book and proceeded to code much of the potential issues as warnings in the IDE, so you won't be able to work them out for yourself. I'm going to buy the book based on the talk I attended. There's no more honest recommendation than that. It's genuinely fun casual reading for people that know java well and enjoy puzzles. And it has real world examples of why some of the Best Coding Practices are the way they are.

    10. Re:disappointed -- try the java cert exam by Anonymous Coward · · Score: 0

      Yup it was Octal.

      This is especially evil if you are loading the integers as strings from some fixed-length format, or as user data and you don't strip leading zeros.

      String s = "0123";
      int ia = Integer.parseInt(s);

      int ib = Integer.parseInt(s, 10);

      System.out.println("ia=" + ia);
      System.out.println("ib=" + a);

      ia=123
      ib=133

    11. Re:disappointed -- try the java cert exam by Anonymous Coward · · Score: 1, Insightful

      Ummm.... Fire your whole team.

    12. Re:disappointed -- try the java cert exam by Fahrenheit+450 · · Score: 1

      Yeah, but it's still a fairly sketchy bit of syntax. I much prefer an unambiguous notation, like in ocaml:

      012 = 12 (decimal)
      0o12 = 10 (decimal)
      0x12 = 18 (decimal)
      0b12 = Fry says, "Its OK Bender. There's no such thing as two."

      --
      -30-
    13. Re:disappointed -- try the java cert exam by Wizard+of+OS · · Score: 1

      I own the book (got it as a goodbye present when I left my previous job) and it is really, REALLY good. Yeah the example in the review isn't that interesting, but the other 100 or so are really amazing.

      I consider myself a somewhat experienced java developer, but they got me every single time. If you think you'r smart you certainly have to read this book, it'll slap you back to the ground.

      Example (let's hope I don't violate any copyright here, my intentions are to get more copies sold anyway ;-)

      Provide a declaration for i that turns this loop into an infinite loop:
      while (i != 0 && i == -i) {}

      Or try to do the same with this one:
      while (i != i) {}

      These are two examples of oneliners that require you to dive deep into your java knowledge. There are some more exotic examples with larger source fragments related to threading/synchronization, locking, etc. etc.

      So I can only say again: buy this book!

      --

      --
      If code was hard to write, it should be hard to read
    14. Re:disappointed -- try the java cert exam by milkchaser · · Score: 1

      That's a truly sick example. Why would anybody do that? It's like kicking puppies.

      --
      "Nothing has an uglier look to us than reason, when it is not on our side." -- Lord Halifax
    15. Re:disappointed -- try the java cert exam by Anonymous Coward · · Score: 0

      bool i = false?

      just guessing, I don't know any java at all.

    16. Re:disappointed -- try the java cert exam by Anonymous Coward · · Score: 0

      I second the motion. Fire the morans.

    17. Re:disappointed -- try the java cert exam by pclminion · · Score: 3, Informative
      At least you get a warning when compiling that code: "finally clause cannot complete normally."

      When the Java syntax was being invented (borrowed from C is more like it), this should have been addressed by disallowing return statements within finally blocks. The only way control should exit a finally clause is by falling out the end.

    18. Re:disappointed -- try the java cert exam by dubl-u · · Score: 1

      When I ran across this exact puzzle in production code, except with 50 lines of complex ifs in the try block, my solution was both simple and effective: I beat the responsible programmer with a power cord until he promised to never, ever do that again.

    19. Re:disappointed -- try the java cert exam by ipfwadm · · Score: 1

      No... Integer.parseInt(String) is exactly the same as Integer.parseInt(String, 10). It's defined that way in the Javadoc, and the source code agrees.

      Also, I don't know what code you're trying to show us in your example, but the thing that is supposedly printing out as 133 ('a') hasn't been declared or assigned to. And the thing that was supposed to prove your point that Integer.parseInt("0123") is treated as octal actually prints out as 123, whereas if it were treated as octal this would actually print out as 83.

    20. Re:disappointed -- try the java cert exam by TummyX · · Score: 1

      Interestingly, Microsoft did fix that when they designed C#.

  30. Re:Puzzling indeed by greg_barton · · Score: 5, Funny

    Why would anyone use Java?

    From now on? Just to piss you off.

  31. Re:Puzzling indeed by LDoggg_ · · Score: 1

    1, 2, 3 and 5, on the other hand, should drive devs towards Python or Ruby.

    They may be strengths of python and Ruby(i don't have much ruby experience), but can you give examples of how they do not apply to java?

    --

    "If they have both, tell them we use Linux. And if they have that, tell them the computers are down." -Dave Chapelle
  32. Re:How many java apps are you running? by masklinn · · Score: 2, Interesting
    hint: your browser, email, OS, shell, image editor, spreadsheet, wordprocessor are

    My browser and email are actually written in Javascript with a small C core.

    --
    "The way we can tell it's C# instead of Haskell is because it's nine lines instead of two." -- wadler
  33. Analog? by Doctor+Faustus · · Score: 1

    a book (That's like an analog webpage, for the neuronauts among us)
    Books are just as digital as webpages, with the possible exception of illustrations.

    1. Re:Analog? by The+Shrewd+Dude · · Score: 1

      Books are just as digital as webpages

      The first page of a book the parent poster is reading:
      01010101010001010101001010101010101001010101001010 1010101010110100101010101001101111

  34. gcc puzzlers by cerelib · · Score: 1

    I think you would have to title the book "GCC Puzzlers" or something of the sort. Different compilers give you different behavior for C. For example, how big is an int? Java is much more concrete.

  35. Re:How many java apps are you running? by Anonymous Coward · · Score: 0

    ok. it's not the new pascal. it's the new cobol.

  36. How many huge data websites are run on java? by Anonymous Coward · · Score: 0

    Let's see... ebay, autotrader, careerbuilder, cars.com and a huge chunk of newspaper classifieds just to start the list.

    OpenOffice is java.

    Why do many of the largest ecommerce sites choose Java? Because it's fast, efficient, solid and secure.

  37. 7 years with Java and... by Assmasher · · Score: 1

    "byte b = -1;
    char c = (char)b;

    so c=-1, right? Wrong." ...surprised you?

    --
    Loading...
  38. wtf? by Anonymous Coward · · Score: 0

    That's like an analog webpage, for the neuronauts among us

    wtf? neuronauts???

    made of cheese.

    wtf?? cheese??

    mature, robust (Cue the laughter from the peanut gallery) programming language.

    W..T..F..??

  39. The problem with books are the readers by Anonymous Coward · · Score: 0

    "The problem being that computer books are often either: a) boring, b) difficult to read, c) poorly written, or possibly: d) made of cheese." I think the actual problems with computer books, are the readers. Example: The Bible (written by God)

    1. Re:The problem with books are the readers by Anonymous Coward · · Score: 0

      a and b definately are reader-related. poorly written is an opinion based on b. d? Lord he must be fat.

  40. Re:Puzzling indeed by Anonymous Coward · · Score: 0

    Don't worry, no one is gonna take away your mainframe, grampa.

  41. There are some fun to read CS books. by hal2814 · · Score: 1

    Enough Rope to Shoot Yourself in the Foot is an excellent example. It's a nice book that's easy to read. I keep a copy near the throne. It can be a bit preachy and I don't always agree with the author's stance, but it's still a good read.

    The Exceptional C++ books are also easy reading.

    It really just depends on what you want. Way back when I was first moving from C to C++, I bought the book Simple C++. While it was a good book that was easy to read, it took far too long for me to gleam the information from it. It's easy-to-read and simplistic approach was a notch or two down from what I was looking for information-wise. Likewise, I imagine most of the CS books sitting out there are for reference purposes. That's not the arena for books that are fun to read.

  42. Re:Puzzling indeed by Anonymous Coward · · Score: 0

    Didn't Microsoft fucking kill that guy yet?

  43. Interesting? mod this clown down. by Anonymous Coward · · Score: 0

    Your broswer is written in C++

    You are very confused.

    1. Re:Interesting? mod this clown down. by masklinn · · Score: 2, Interesting

      Nope, Gecko is written in C++ but the whole Firefox interface, which is for all means and purposes "my browser" is written in XUL, which is nothing more than Javascript + CSS + XML.

      Which is why you can get browsers such as K-Meleon, also based on Gecko and still different browsers (K-Meleon being written in C++/Win32).

      --
      "The way we can tell it's C# instead of Haskell is because it's nine lines instead of two." -- wadler
    2. Re:Interesting? mod this clown down. by Kent+Recal · · Score: 1

      Nope, Gecko is written in C++ but the whole Firefox interface, which is for all means and purposes "my browser" is written in XUL, which is nothing more than Javascript + CSS + XML. Which is why you can get browsers such as K-Meleon, also based on Gecko and still different browsers (K-Meleon being written in C++/Win32).

      Can anyone explain to me why the firefox UI is so dog slow under linux while it's sufficiently snappy under windows?
      I'd love to use Firefox more but the tab-switching-delay alone drives me go back to opera again and again.
      Even worse is how the whole UI freezes while rendering a big (or, god forbid, multiple) pages...

  44. Re:How many java apps are you running? by EtherealStrife · · Score: 1
    The most important of all...Azureus! :)

    The real world doesn't use it very much.

    I see it most often used in combination with other languages, rather than standalone. It's more a professional language than public, you see it more for business/corporate work.

  45. Typo by vocaro · · Score: 1

    guiding Java into it's current incarnation --> guiding Java into its current incarnation

    1. Re:Typo by CmdrWass · · Score: 1

      How about this typo:

      "Anyone who has been a serious java programmer in the last several years should know the name Josh Bloch, and more importantly, should have read his book Effective Java. Josh, acting as java's platform architect has been directing and guiding Java into it's current incarnation as a mature, robust (Cue the laughter from the peanut gallery) programming language.

      The Java programming language has nothing but deteriorated under Josh Bloch's watch. It started with his introduction of "optional" methods in the collections framework, not to mention interface duplication. Then it continued through Java 1.5 as he led JSRs that included Generics (a terrible incarnation of psuedo-type saftiness) as well as the introduction of "printf". If I wanted to program in C++, I'd program in C++.

      I wonder what kind of "great innovations" he has in store for us at Google.

  46. No you don't by jpardey · · Score: 2, Funny

    Some of us don't hate gay people, while still hating the word "Neuronaut."

    --
    I have freaks! I did something right...
    1. Re:No you don't by Call+Me+Black+Cloud · · Score: 1

      Furthermore, some of us don't hate bundles of sticks either, and we still hate the word "neuronaut". We're also not fond of those who think people who use "fag" as a derogatory term hate gay people. You're such a 'tard. Oops! I guess that means I hate disabled people. Ok, well, stop whining you woman. Damn, now I'm a misogynist. Fucking geek. Crap, now I hate myself!

  47. JAVA? by VincenzoRomano · · Score: 1
    byte b = -1;
    char c = (char)b;

    so c=-1, right? Wrong.

    If I need a book to understand this (being it JAVA or SNOBOL it doesn't matter), the first 200 pages will be about information technology.
    Another 200 pages are needed for the basics of computer science and finally the remaining 200 pages are for JAVA.
    --
    Maybe Computers will never be as intelligent as Humans.
    For sure they won't ever become so stupid. [VR-1988]
    1. Re:JAVA? by owlstead · · Score: 1

      Don't worry. Normally you would use something like this:

      String s = new String(new byte[] { 0x41, 0x42, 0x43 }, "UTF-8");

      To get "ABC". I haven't got a clue why you would want to do convert characters to or from *any* integer, unless you would like to write a ROT-13 codec. I laugh at languages that use *that* as a way to show their strength (and many do).

      The book Java Puzzlers doesn't assume you would like to do something like that. The whole book is about getting a more complete understanding of the language, and not about getting better hacks for your money. That said, byte's should really have been unsigned, like this they are a pain in the back (who would use a byte to show any other value than a hexadecimal value in a program?)

  48. Puzzle book is great by Anonymous Coward · · Score: 1, Interesting

    I bought the puzzlers book on a whim. Love it.

    But the subject seems to be "computer books in general", and man is there a world of difference between computer books. Someone might pick up an Organization textbook, and come to understand twos complement numbers (and thus, not be surprised by the puzzler mentioned in the article), he might learn how a full adder can be made from NAND gates, and that might get him to the second chapter of a logic theory book.
    It may be tempting to compare "computer books" to "computer books", but "PHP in 24 Hours" is NOT on the same shelf as Cormen, Knuth, Stevens, Hopcroft, Sipser, I think you get the idea.

    A person might be very skilled and experienced in some areas, who would pick up one of these books and wonder "WTF?"

    Works both ways. I know CS academics who would be hard pressed to function in a business software environment, and experienced business software devs who would not understand the theory expression to any depth, even those who ackowledge that theory is important.

  49. Re:garbage collector by slackmaster2000 · · Score: 1

    There is no byte data type in C, only the char, which in terms of C is an integer of size depending on the most basic machine addressable unit (usually a byte). This example is probably most interesting to people who cut their teeth on C and then moved on to other C syntax style languages like Java.

    You're right though, most programmers worth a damn don't make assumptions like this when it comes to data type conversion.

    It should be at least a little bit interesting to all, however, since the code is valid and the result isn't intuitively obvious.

  50. a char with a value of 65535? by poot_rootbeer · · Score: 3, Insightful
    (In this case, byte is signed, char isn't, and the widening cast fills in bits, leaving c=65535.)
    char
    , being a character datatype, shouldn't have its value expressed as an integer.

    The correct value of
    c
    is the glyph or other character corresponding to entry 65535 in whatever character encoding Java is currently using. (Assuming UCS-2, it's an invalid codepoint and therefore undefined.)

    Yes, for purposes of demonstrating that
    int
    is stored as a signed value and
    char
    isn't the example is correct, but that's still a little more of an under-the-hood mentality that's more appropriate to C than to Java.
    1. Re:a char with a value of 65535? by Anonymous Coward · · Score: 1, Insightful

      "but that's still a little more of an under-the-hood mentality that's more appropriate to C than to Java."

      Wrong, wrong, wrong...

      This should be something all developers understand about the language they are using. Not knowing or considering it "out of scope" for the language is ridiculous and can cause some nasty logic bugs in the code.

      It appropriate for any language that supports up/down casting of primitives... (not to be confused with type conversion such as string to int and int to string in PHP or Perl)

    2. Re:a char with a value of 65535? by pclminion · · Score: 1
      char, being a character datatype, shouldn't have its value expressed as an integer. The correct value of c is the glyph or other character [...]

      Now you're confusing the issue. You have conflated three distinct concepts -- a character code, which is a value denoting a specific character within a given encoding; a character, which is the abstract identity of a specific written glyph; and the glyph itself, which is a physical realization of the character in question. So no wonder you are confused.

      A "char," in C, C++, Java, and several other languages, is a character code. That is, it is a numeric value which, when coupled with a given encoding, can be used to refer to a character.

      There is nothing particularly arcane about the concept of using a numeric value to refer to a character. And it is to be expected that a "char" type would be a numeric type. This is in fact the case, notwithstanding your bizarre confusion between a character and its character code.

    3. Re:a char with a value of 65535? by poot_rootbeer · · Score: 1

      A "char," in C, C++, Java, and several other languages, is a character code. That is, it is a numeric value

      A 'char' in Java is a primitive datatype. If it were intended to inherit behavior from a numeric primitive, it would have been implemented as such and called 'Char'.

      Or maybe I ought to say 'should have'. If Java's platform architect has claimed in the book that the 'char' primitive is actually just an unsigned int with a fancy name, who am I to argue?

      My point is, a character is not the binary representation of a text unit on disk.
      char c = 'x' should work the same way regardless of whether the character encoding is ASCII (0x78), EBCDIC (0xA7), UTF-32 (0x00000078), or any other system. Performing binary arithmetic on characters without regard to encoding does not enforce that behavior.

    4. Re:a char with a value of 65535? by pclminion · · Score: 1
      My point is, a character is not the binary representation of a text unit on disk.

      No. As I already pointed out, a character is an abstract concept. "The uppercase Latin letter 'A'" is a character. Decimal 65, a number, is the character code of that character in the ASCII and Latin1 character sets.

      You seem to be wishing for some abstract concept called "character" to exist as a concrete element in a computer language. Since it cannot, you call for arbitrarily masking the true nature of the object (which is a number) for no good reason that you've yet explained.

  51. u r still confused by Anonymous Coward · · Score: 0

    download this : http://ftp.mozilla.org/pub/mozilla.org/firefox/rel eases/1.0.7/source/firefox-1.0.7-source.tar.bz2

    (mozilla source code).

    unbzip it.

    count the *.cpp files.

    count the *.xul files.

    (whaps idiot over the head)

    Now do you get it?

  52. Re:How many java apps are you running? by Cataleptic · · Score: 1

    I've been using Eclipse as my sole IDE for at least 8 hours a day, 5 days a week, for the last 3 years. But yeah, aside from that, very little of my time is spent using Java apps.

  53. Re:master of the obvious (SPOILER) by ishepherd · · Score: 3, Informative
    The Java Language Specification states that char IS NOT A NUMBER. It's a character representation

    Well, maybe that's the intended purpose. But its semantics don't sit totally easy with that. What does this print? (from p.25)

    System.out.println('H' + 'a');

    It prints '169'. The book goes on:

    From a linguistic standpoint, the resemblance between char values and strings is illusory. As far as the language is concerned, a char is an unsigned 16-bit primitive integer - nothing more.

    Yeah, in practice this sort of thing is mainly irrelevant, because you wouldn't actually USE chars like that. Still, it's interesting stuff.

    --
    fud, notfud, yes, no, maybe
  54. Oh come on! by Xarius · · Score: 2, Insightful

    Kylar writes "When you have spare time and decide to do something with a book (That's like an analog webpage, for the neuronauts among us), how often do you turn to a computer related book? How often has it happened in the last year? Right. The problem being that computer books are often either: a) boring, b) difficult to read, c) poorly written, or possibly: d) made of cheese. Read on for the rest of Kylars' review.

    I know slashdot is hardly the pinnacle of good reporting, but that summary is bordering on the idiotic. Were those daft little bits of meaningless fluffy non-humour put in there simply to up the word count?

    --
    C17H21NO4
    1. Re:Oh come on! by Surt · · Score: 2, Funny

      Perhaps kylar has been submitting a lot of stories, gradually moving where he inserts the random garbage into the story description, to find out just how far the slashdot editors will read before posting a story. His research seems to indicate the slashdot eds give up around 350 characters.

      --
      "Who is the Journal of Quantum Physics going to believe?" --Stephen Hawking
  55. Re:master of the obvious (SPOILER) by AKAImBatman · · Score: 1
    Well, maybe that's the intended purpose. But its semantics don't sit totally easy with that. What does this print? (from p.25)

    System.out.println('H' + 'a');

    It prints '169'. The book goes on:


    The real problem is the overloading of the '+' sign. This is just more evidence that operator overloading is harmful in general purpose langauges. Sure, that '+' is convenient for putting strings together, but it does cost in clarity.

    The reason for this behavior, BTW, is do you can do things like this:
    char lowerCase = 'H' + ('a' - 'A');
    Being able to obtain mathematical deltas is extremely important when you're changing the forms of letters. Gosling wasn't looking to change those sorts of features when he created the Java language.

    At least that's a more realistic example, though. :-)
  56. Re:How many java apps are you running? by Doctor+Faustus · · Score: 1

    That's definitely closer, although VB was the new COBOL first.

  57. Re:Puzzling indeed by Anonymous Coward · · Score: 0

    5 most defintely does apply. I've downloaded the Java source code several times to dig out why something weird is happening with the Sun APIs. And then there is the Apache Foundation stuff and all the rest.

  58. Another Example by Anonymous Coward · · Score: 2, Interesting
    I've been to one of their talks -- they work at Google, and give occasional tech talks for the other engineers. Here's an example that they actually got from somebody else: it was accompanied by some general banter, and multiple options. (Disclaimer: I don't know if this is in the book.)
    public class bad {
        public static void main(String[] args) {
            bad.String s = new bad.String("hello");
            System.out.print(s + " ");
            bad.String t = new bad.String("goodbye");
            System.out.println(s);
        }
        static class String {
            java.lang.String s;
            public String(java.lang.String t) {
                s = t;
            }
            public java.lang.String toString() {
                return s;
            }
        }
    }
    What does the code above do?

    a) Print "hello hello"
    b) Print "hello goodbye"
    c) Compile error
    d) Other

    Some banter of my own, roughly:
    Well, let's see. This seems like bad code, since why would you name a class String, but sure. So each bad.String has a java.lang.String inside it, and when you construct a new bad.String you get an object that contains the java.lang.String that you constructed it with. Of course, the toString() method just returns the java.lang.String that it stores. So first we make a String with "hello" and then we print it, followed by a space, and then we make a String with "goodbye", and print "hello" again. So I think this program should print "hello hello".

    I'll post the answer later if nobody gets it, but you can always try it yourself. I do recommend thinking about it, though: it's cute. Note that everything I said in the banter, except for what I think the answer is, is true.
    1. Re:Another Example by JPrice · · Score: 1

      Haha... that's certainly tricky, but I don't think you can really fault Java for behaving that way. It's just doing exactly what you're telling it to do.

      Garbage In, Garbage Out :)

    2. Re:Another Example by MntlChaos · · Score: 1

      I didn't believe the result when I ran it until I used javap to provide the necessary insight. Nice one.

    3. Re:Another Example by pclminion · · Score: 1

      In this example, String is a static class, so the variables declared in that class are also static. The class serves merely as a namespace. So I don't see what the mystery is here -- it will print "hello goodbye" because the s variable is shared between all "instances."

    4. Re:Another Example by Anonymous Coward · · Score: 0

      Please explain...

    5. Re:Another Example by ipfwadm · · Score: 1

      In this example, String is a static class, so the variables declared in that class are also static. The class serves merely as a namespace. So I don't see what the mystery is here -- it will print "hello goodbye" because the s variable is shared between all "instances."

      Ummm... no. You really need to look up what a static class means in Java. It simply means that the inner class can exist separate from any instance of the enclosing class. The inner class's members are not automatically all static. If you were to modify the given code so that it actually runs, you'll see "hello hello" printed out.

    6. Re:Another Example by TummyX · · Score: 1

      Um no. Static in Java merely means the class doesn't have an implicit reference (and binding) to the outer instance that created it.

      Microsoft muddied the whole issue by not having inner classes (only nested classes) and then by introducing "static" classes which have a totally different meaning from Java static inner classes.

  59. Re:master of the obvious (SPOILER) by ishepherd · · Score: 1
    Hmmm, but proper (internationalized) case conversion is ridiculously more complicated than that. I guess the technique works for ROT13 encryption though :o)

    I can't really fathom the choices in Java's design. A lot of advanced-ish features like operator overloading, left out, *just in case they tempted you* to write non-obvious code. And yet it keeps lots of old C syntax which gives you plenty enough rope to hang yourself with (from which flows several of the puzzles).

    anyhow, I recommend it.

    --
    fud, notfud, yes, no, maybe
  60. Re:Puzzling indeed by mrbuckles · · Score: 3, Funny
    He'll be here all week, folks.
    Ah, there's nothing more productive than starting up the "your language sucks, you should code in [insert my language of choice here] because it's what real programmers use" argument. I've yet to meet a coder whose ability I truly respected that ever got into such an argument. But, hey, maybe this is really useful. Under that guise, let's run the entire argument here and anytime you feel like a language being discussed is for half-wits, you can reference this.

    So, here's the argument in order from first salvo to coup-de-grace

    1. [Language being discussed] is for n00bs! You should code in [language-1]
    2. Ha! You think [language-1] is great? I agree you're not as l4m3 as the n00bs who code in [language being discussed], but please -- time to go to [language-2]
    3. *Sigh* I'm so amused (not) when I come to /. and see you [language-2] coders flaming [language being discussed] coders or even [language-2] coders. It's all a bunch of crap and explains why so much money is spent tracking down buffer overflows and other security flaws. Get to machine language or get out!
    4. I use 3 keys when I program -- 0, 1 and enter. Bitches!
  61. Re:garbage collector by Heembo · · Score: 2, Insightful

    > When we moved into millions of cycles per second (big big solaris servers) we had similar problems...

    When we use big servers, Java 1.5, huge centralized clusters (offsite backup!), connection pooling, application level caching, big Oracle clusters, and pro (expensive) app servers (no tomcat) not only can we handle millions of cycles, we can handle a lot, lot, lot more at 6 sigma reliability and better.

    I'm guessing your problem is a deeper architectural issue, not a "bug with Java".

    --
    Horns are really just a broken halo.
  62. Re:master of the obvious (SPOILER) by AKAImBatman · · Score: 2, Interesting

    Hmmm, but proper (internationalized) case conversion is ridiculously more complicated than that.

    Yes it is indeed.

    The JavaDoc for the Character class actually bemoans this in detail. My only point was that the Java Language allowed the numerical operations for such purposes. Writing a proper Unicode case converter is something that Sun has already done for us. (Thank God.) :-)

    And yet it keeps lots of old C syntax which gives you plenty enough rope to hang yourself with (from which flows several of the puzzles).

    That much is easy to answer. Java started its life as a new C++ compiler that didn't require a recompile of the entire project when just one class changed. To meet that goal, Gosling turned to using bytecode. That partly solved the problem, but he found he had to make several language changes to keep classes separate. By the time he was done, a new language had emerged.

  63. Re:master of the obvious (SPOILER) by Taladar · · Score: 1

    Actually implicit casts are a bigger problem than operator overloading and less useful too.

  64. Re:Not interested...in sudoku by ehrichweiss · · Score: 1
    I guess that those of you who play that "puzzle" haven't yet realized that, no matter how hard they seem, there is a SIMPLE mathematical equation to it, huh. If they have a gameshow about that stupid thing, I'd be the grand-freakin'-master cause I can solve them in a few seconds thanks to one of my magician friends(I too am a magician) who was big into mathematical magic and that "puzzle" was one of them.

    No, I won't teach you cause if they do start a gameshow..I'M GETTIN' PAID!!

    --
    0x09F911029D74E35BD84156C5635688C0
  65. Re:Puzzling indeed by Anonymous Coward · · Score: 0

    4) Javadoc!!

    Java should be banned because of "cute" features like Javadoc that can easily be abused. For example, in the early days of Java, asshole Sun Inc. just spit out skeleton javadoc-generated API "help", like:

    class Widget
        void setDecomboobulation()
            Sets decomboobulation.

    But unless you already know what the fuck "decomboobulation" is, it doesn't fucking help!

    Another obvious example is checked exceptions, which encourage you to just write an empty one to get the compiler to just shut the fuck up for one second so that you can think, and then forget to come back later and fill it in with something meaningful.

    So, in closing, since the rule with you fucking Java airheads is that any language with easily abused "cute" features sucks, Java sucks. QED.

    Thank you. I also do weddings and barmitzvahs.

  66. Re:Puzzling indeed by Anonymous Coward · · Score: 0

    Right on, brotha, anything not made for the dumb and lazy just isn't kewl.

  67. Re:garbage collector by bryanmanwaring · · Score: 2, Insightful

    It never ceases to amaze me how naive people can be when it comes to Java. The truth is, the underlying VM is a different technology than the "Manage it yourself" tradition of C/C++. While garbage collection is an additional process that occurs in a VM environment such as Java or .NET, there are peformance advantages to using such a process. (And no, I am not refering to the programmer laziness argument about not having to manage memory in Java... I am talking about the efficiency of allocation and deallocation that a Java VM affords)

    I do not plan on engaging in any arguments back and forth about the two types of memory management... But if you are truly interested in an article that means to show the reality of the "performance characteristics" of a Java VM, please read the article listed below. It is truly a well written article and worth the read.

    http://www-128.ibm.com/developerworks/java/library /j-jtp09275.html?ca=dgr-lnxw01JavaUrbanLegends

  68. My answers by p3d0 · · Score: 1
    The first one: int i = Integer.MIN_INT;

    The second one I'm not so sure of: double i = Double.NaN;

    Disclaimer: I work on a Java JIT compiler for a living.

    --
    Patrick Doyle
    I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
    1. Re:My answers by Wizard+of+OS · · Score: 1

      Correct, but you cheated :). The second one is actually quite interesting; 'NaN' is a thing that represents the non-computable. If you compare it to anything it will always return false ... even if you compare it to itself.

      --

      --
      If code was hard to write, it should be hard to read
    2. Re:My answers by p3d0 · · Score: 1

      I cheated?

      --
      Patrick Doyle
      I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
  69. oops by p3d0 · · Score: 1

    Gah... wrong button. Meant to hit "preview". The first one should of course be Integer.MIN_VALUE;

    --
    Patrick Doyle
    I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
  70. Re:Not interested...in sudoku by simcop2387 · · Score: 1

    Are you a liscensed mathamagician? i've got a birthday party coming up and we need some entertainment.

  71. Re:I think I speak for everyone when I say by 0kComputer · · Score: 0, Troll

    "neuronauts"? You COMPLETE FAGGOT.

    I agree, that word makes me want to punch something (I was talking about "neuronauts" btw).

    --
    Top 10 Reasons To Procrastinate
    10.
  72. Exactly my point by brunes69 · · Score: 1

    If you want to use an unsigned short in Java, you need to use a char.

    Which is a PITA since Java 1.5 autoboxing is useless now, you need to cast all over the place again just like in Java 1.4.

    Which is why it is retarded. Why can't Java just have an "unsigned" keyword like in C++ and let the developer do what he/she wants?

    1. Re:Exactly my point by rjshields · · Score: 1
      Why can't Java just have an "unsigned" keyword like in C++ and let the developer do what he/she wants?
      Because some guy designed it that way back in 1994. So there.

      PS. I don't know what he was thinking either.
      --
      In this world nothing is certain but death, taxes and flawed car analogies.
  73. Lucene in Action book rocks by captainclever · · Score: 1

    I have Lucene in Action open on my desk at work at the mo. Great stuff. Other than that, i always look online.. there are few other computer books i've encountered as useful.

    --
    Last.fm - join the social music revolution
  74. Re:Not interested...in sudoku by fbjon · · Score: 1

    Of course. Generally, the requirement of a sudoku puzzle is that it can be solved using logic alone, without guessing, and that it has only one solution. It's not rocket science, it's a light brain-workout.

    --
    True confidence comes not from realising you are as good as your peers, but that your peers are as bad as you are.
  75. Re:Not interested...in sudoku by ehrichweiss · · Score: 1

    No,(and no such thing as a "licensed" one) but if you're serious, I can probably find a magician in your area. I prefer mentalism(psychic entertainment without the delusional thinking that makes someone from NYC think they have a Jamaican accent) and what they're now calling "street magic"; I also dig running "short cons" but nothing that gets me anything more than a free drink every now and again.

    --
    0x09F911029D74E35BD84156C5635688C0
  76. Re:Puzzling indeed by shutdown+-p+now · · Score: 1
    Lack of "cute" features that break easily.
    Funny, until 1.5 got released, enums and generics were usually in that category too.

    Overall, out of your list, only point 5 stands. Java is not the most readable out there (out of more or less mainstream languages, Python arguably is), not the most rapid development friendly (any scripting language beats it there), and Javadoc-like documentation system is usually the second thing after compiler/interpreter which gets written for any new language these days.

  77. Re:Puzzling indeed by Anonymous Coward · · Score: 0

    Personally, I find Python extremly difficult to read, as I do any loosly typed language. With a lot of C/C++/Java experience, I once tried porting some fairly simple algorithms from Phyton to C, and gave up becaues the code was too hard to follow due to loose typing.

    Maybe its not so bad if you are used to it but from my perspective I'm amazed how any large project written with such languages doesn't get bogged down in bugs. Perhaps its just requires a bit of disapline or something, I don't know, I am nieve on the topic.

  78. SPOILER: Re:Another Example by Q2Serpent · · Score: 2, Informative

    Since there is a String class that exists within the bad class, this prototype:

        public static void main(String[] args)

    is the same as this:

        public static void main(bad.String[] args)

    and java can't find any main to execute because it is looking for:

        public static void main(java.lang.String[] args)

    See?

    1. Re:SPOILER: Re:Another Example by Anonymous Coward · · Score: 0

      Exactly. So the answer is that it'll compile fine, and then you'll run it and it will say:

      Exception in thread "main" java.lang.NoSuchMethodError: main

      It wants public static void main(java.lang.String[] args), and you've given it public static void main(bad.String[] args).

  79. Re:Puzzling indeed by shutdown+-p+now · · Score: 1

    I'm still not sure what static typing has to do with readability, but even out of statically typed languages Java is hardly the most readable. See Eiffel for a better example. This is, of course, because Java syntax is really just C/C++ legacy.

  80. Re:master of the obvious (SPOILER) by rjshields · · Score: 1
    Yeah, in practice this sort of thing is mainly irrelevant, because you wouldn't actually USE chars like that.
    On the contrary, people use chars like that all the time.
    Imagine you want to do:
    if (c >= 'a' && c <= 'z')
    Quite useful really.
    --
    In this world nothing is certain but death, taxes and flawed car analogies.
  81. Re:master of the obvious (SPOILER) by rjshields · · Score: 1

    It seems a bit odd that they made chars behave like integers if they didn't want people to use them as integers.

    --
    In this world nothing is certain but death, taxes and flawed car analogies.
  82. The reason I picked that example... by Kylar42 · · Score: 1

    Is that I figured it would generate some discussion :)

  83. Re:Not interested...in sudoku by extremely · · Score: 2, Insightful

    If you have a super fast solution to the sudoku puzzle family you should probably write it up. Sudoku is NP-complete... if you've solved it then you've cracked every encryption protocol known to man...

    --

    $you = new YOU;
    honk() if $you->love(perl)

  84. Re:Puzzling indeed by Anonymous Coward · · Score: 0

    When jumping into the middle of a code segment of a loosly typed language, it can be extremly difficult to work out what is going on because you don't know what any of the types are. For example, if you look at a function, it can be tricky to work out what type the paramaters are. In a strongly typed language, it is obvious.

    I can't say C/C++/Java are the easiest languages to read in general for everybody, but considering they are burned in to my mind, for me any language that doesn't make excessive use of currly brackets is hard for ME to read in comparison;)

  85. Re:Puzzling indeed by shutdown+-p+now · · Score: 1
    When jumping into the middle of a code segment of a loosly typed language, it can be extremly difficult to work out what is going on because you don't know what any of the types are. For example, if you look at a function, it can be tricky to work out what type the paramaters are. In a strongly typed language, it is obvious.
    You don't usually care as much about the type of the parameters as you do about constraints on them in general. In Python, you see foo(bar); in Java, it is float foo(int bar). Neither tells you that bar should lie within [0; 100], or that the return value is in [-1.0; +1.0], which is what you need to know.

    Now, that is why one should use descriptic variable names. If you see a variable named count, you know it's a non-negative integer, and percentage is quite certainly [0; 100] (and whether it's int or float is really unimportant, if you think about it).

    But of course, for formal code review and automated verification this is not enough. Some formal way to describe the constraints on input and output data (function arguments and return values, in our case) is needed. That is what Design by Contract for; but curiously enough, it does not imply static typing, even though it originated in a statically typed language (Eiffel): dynamically typed languages such as Lisp also have successful DbC implementations.

    To sum it up: DbC covers all the readability and maintainability issues traditionally associated with lack of static typing, while peacefully co-existing with all the benefits of dynamic typing. Behold, the way of the future! ;)

  86. Re:Puzzling indeed by Anonymous Coward · · Score: 0

    I find where loose typing is most confusing when it comes to data structures, classes and arrays rather then simple inbuilt types where it isn't too bad.

    I agree, descriptive variable names are greate and I don't mind a bit of design by contract my self. I'm sure there are ways to code with loosly typed languages that are safe and readable, however, I wouldn't discribe much of the loosly typed code I have seen as such (Attmitably I havn't looked at much).

    Perhaps this is a good question, if you wanted to port code from an undisaplined, ans perhaps inexperienced team of programemrs, what language would you prefere? That would probably be a good measure of readability.

  87. Re:Puzzling indeed by shutdown+-p+now · · Score: 1
    Perhaps this is a good question, if you wanted to port code from an undisaplined, ans perhaps inexperienced team of programemrs, what language would you prefere? That would probably be a good measure of readability.
    Oh, I do not dispute that it is easier to write unreadable code in dynamic languages. Perl is probably the most prominent example, but you can do rather mind-boggling things in Python or Ruby too. Additional power always requires more experience to use properly, and to that extent I would certainly agree that for an unskilled and undisciplined coder, an overly strict language is just what is needed.

    All in all, in the situation you described, I would probably prefer it to be in Eiffel. It's pretty hard to mess Eiffel code up.