Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Maximal Munch in Java?

Tags:

java

javac

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:

  • Why doesn't a+++++b work in C?
  • Why does “a + + b” work, but “a++b” doesn't?

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.

like image 754
thegauravmahawar Avatar asked Jul 24 '26 02:07

thegauravmahawar


1 Answers

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

like image 156
Andreas Avatar answered Jul 25 '26 16:07

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!