Joe Rawlings Software Engineer

26Nov/101

Java Puzzle 6

What does the program print?

public class Elementary {
  public static void main(String... args) {
    System.out.println(12345 + 5432l);
    System.out.println(01234 + 43210);
  }
}

a) 17777 44444
b) 17777 43878
c) 66666 44444
d) 66666 43878

Comments (1) Trackbacks (0)
  1. The answer is (b), 17777 and 43878. This program doesn’t say what you think it does and leading zeros can cause trouble. On line 3, the syntax highlighting gives it away that you are adding 12345 with the long 5432. On line 4, the leading 0 on ’01234′ makes it an octal literal equal to 1,234 (base 8 ) or 668 in decimal.

    The moral is to always use an uppercase el (L) for long literals and never use lowercase el as a variable name. Also, never precede an int literal with 0 unless you want to express it in octal (base 8 )


Leave a comment

(required)

No trackbacks yet.