3

I know Maximal Munch Rule isn't Java specific, but my question only concerns Java and Java compiler.

I've also read some of the related answers:

But I'm still not able to fully grasp the concept of Maximal Munch and its applications.

Like in the following code:

int i = 3;
int j = +i;
System.out.println(i); //3
System.out.println(j); //3

How is the statement int j = +i; interpreted by the Java compiler and why this works?

Another example, int j = + +i; also works, but I'm not sure how.

I tried to understand this concept on my own, but I'm not able to.

I would like to know how this works, the concept behind it and how the Java compiler treats such statements.

Community
  • 1
  • 1
thegauravmahawar
  • 2,802
  • 3
  • 14
  • 23

3 Answers3

1

The plus sign can be used as:

  • 1 + 2 binary numeric addition operator
  • "A" + "B" binary string concatenation operator
  • ++i unary increment operator
  • +i unary positive sign operator (uncommon, the -i unary negation sign operator is more common)

Since a positive sign operator doesn't actually do anything, it can be eliminated.

// All the same
int j = + +i;
int j = +i;
int j = i;
int j = +(+(i));
int j = +(i);

See here for more information: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html

Andreas
  • 154,647
  • 11
  • 152
  • 247
0

This is the unary plus operator, indicating a positive value. Frankly, it's quite pointless - +i is the same as i.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

You can have a look at this section on lexical translations from the Java Language Specification:

The longest possible translation is used at each step, even if the result does not ultimately make a correct program while another lexical translation would. There is one exception: if lexical translation occurs in a type context (§4.11) and the input stream has two or more consecutive > characters that are followed by a non-> character, then each > character must be translated to the token for the numerical comparison operator >.

The input characters a--b are tokenized (§3.5) as a, --, b, which is not part of any grammatically correct program, even though the tokenization a, -, -, b could be part of a grammatically correct program.

So in your case:

int j = +i;

is tokenized into:

  • int
  • j
  • = (the assignment operator)
  • + (the unary plus operator indicating a positive value)
  • i

int j = + +i;

is tokenized into:

  • int
  • =
  • j
  • + (the unary plus operator indicating a positive value)
  • another unary plus operator +
  • i

The two statements are therefore exactly the same as int j = i since all + operators are interpreted as the unary plus (no additive + or increment ++).

Community
  • 1
  • 1
M A
  • 71,713
  • 13
  • 134
  • 174