Will Java ever allow comments to nest?

Stuart Marks stuart.marks at oracle.com
Tue Jul 7 01:10:28 UTC 2020

On 7/1/20 1:49 PM, Pavel Rappo wrote:
> Some modern languages allow comments to nest. For example, Swift, F#, and Haskell do that. Why doesn't Java do that? Will Java ever do that?

Why doesn't Java do that? I'd guess, since Java is a descendant of C, and C 
doesn't allow comment nesting. Why doesn't C allow nesting? I'm not entirely 
sure, but I believe it could make lexical analysis easier. If you're in a 
comment, then the only thing you have to do is look for the */ comment 
terminator. Sure, you could write a bit more code to track nesting, but if 
you're running on a 24KB PDP-11, every bit counts. [1]

> I can see cases where nesting would be useful:
> 1. Commenting out long blocks of code that possibly contain `/* ... */` comments.
> 2. Having a character sequence resembling a comment terminator `*/`, for example, in a regex or a glob pattern.
> 3. Having a `/* ... */` comment within a doc comment `/** ... */`. This is typically used in doc comments of language modeling APIs and, admittedly, is a niche case.
> All of the above can be done today, albeit with much friction.

The best way to comment out a long block of code in Java is to prefix every line 
with //. This "nests" properly in that it handles complete /**/ blocks as well 
as blocks of //-commented lines. (Of course it won't work if you comment out an 
unpaired /* or */ token.)

This is easily accomplished in NetBeans with a couple buttons dedicated to this 
task. I'm sure other IDEs have equivalent commands. In vi,


will comment and uncomment a block of lines. In Emacs, you can use 
replace-regexp in a similar fashion.


[1] https://www.bell-labs.com/usr/dmr/www/chist.html

More information about the discuss mailing list