7

Please explain the below code

public class Example{
   public static void main(String[] args)
   {
      int i[]={9};
       System.out.println("\700");
   }
}

Please don't say me that the octal value should be less than 377. I know it already but when I run the above program, I get the output as 80. I want to know why its happening so?

Please give a clear explanation. Thank you

prathapa reddy
  • 321
  • 1
  • 4
  • 17

1 Answers1

9

Basically, you've got two characters there: '\70' and '0'.

The escape sequence for octals is documented in the JLS as:

OctalEscape:
\ OctalDigit 
\ OctalDigit OctalDigit 
\ ZeroToThree OctalDigit OctalDigit 

The last of these doesn't apply in your case, as '7' isn't in ZeroToThree, but both '7' and '0' are octal digits, so it matches the second pattern.

So, now we just need to know why '\70' is '8'... and that's because octal 70 is decimal 56 or hex 38, which is the UTF-16 code unit for '8'.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Just one minor nitpick, Jon, I'd say it's less the UTF-16 code point than the _Unicode_ code point. UTF-16 is just an encoding method for Unicode code points. – paxdiablo Mar 25 '15 at 14:38
  • 1
    @paxdiablo: I meant UTF-16 code unit, actually (fixed in the answer) - which is more relevant than a Unicode code point, as a `char` is a UTF-16 code unit. (In particular, a string should be considered as a sequence of UTF-16 code units, in terms of things like `charAt`, `length` etc. There can be fewer code points than code units...) – Jon Skeet Mar 25 '15 at 14:42