Search code examples
javaoctal

Printing Octal characters in java using escape sequences


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


Solution

  • 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'.