Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the Java semantics of an escaped number in a character literal, e.g. '\15' ?

Please explain what, exactly, happens when the following sections of code are executed:

int a='\15'; System.out.println(a); 

this prints out 13;

int a='\25'; System.out.println(a); 

this prints out 21;

int a='\100'; System.out.println(a); 

this prints out 64.

like image 314
VAr Avatar asked Oct 01 '13 04:10

VAr


People also ask

What is character literal in Java with example?

Char Literal: Java literal is specified as an integer literal representing the Unicode value of a char. This integer can be specified in octal, decimal, and hexadecimal, ranging from 0 to 65535. For example, char ch = 062; Escape Sequence: Every escape char can be specified as char literal.

What are character literals enclosed in Java?

Character literals are enclosed in single quotation marks. Any printable character, other than a backslash (\), can be specified as the single character itself enclosed in single quotes. Some examples of these literals are 'a', 'A', '9', '+', '_', and '~'.


1 Answers

You have assigned a character literal, which is delimited by single quotes, eg 'a' (as distinct from a String literal, which is delimited by double quotes, eg "a") to an int variable. Java does an automatic widening cast from the 16-bit unsigned char to the 32-bit signed int.

However, when a character literal is a backslash followed by 1-3 digits, it is an octal (base/radix 8) representation of the character. Thus:

  • \15 = 1×8 + 5 = 13 (a carriage return; same as '\r')
  • \25 = 2×8 + 5 = 21 (a NAK char - negative acknowledgement)
  • \100 = 1×64 + 0×8 + 0 = 64 (the @ symbol; same as '@')

For more info on character literals and escape sequences, see JLS sections:

  • 3.10.4: Character Literals
  • 3.10.6: Escape Sequences for Character and String Literals

Quoting the BNF from 3.10.6:

OctalEscape:     \ OctalDigit     \ OctalDigit OctalDigit     \ ZeroToThree OctalDigit OctalDigit  OctalDigit: one of     0 1 2 3 4 5 6 7  ZeroToThree: one of     0 1 2 3 
like image 91
Bohemian Avatar answered Oct 12 '22 17:10

Bohemian