How to auto-format code in Eclipse?
On Windows and Linux : Ctrl + Shift + F
On Mac : ⌘ + ⇧ + F
(Alternatively you can press Format
in Main Menu > Source)
Another option is to go to Window->Preferences->Java->Editor->SaveActions and check the Format source code option. Then your source code will be formatted truly automatically each time you save it.
CTRL + SHIFT + F will auto format your code (whether it is highlighted or non highlighted).
This can also be done at the Project Level: In the Package Explorer, right-click on the project > Properties > Java Editor > Save Actions
This might be preferable when working as a team so that everyone's code is saved with the same format settings.
Notice: It did not format the document unless I corrected all mistakes. Check your file before pressing CTRL + SHIFT + F.