558

I want to use regions for code folding in Eclipse; how can that be done in Java?

An example usage in C#:

#region name
//code
#endregion
5

23 Answers 23

556

Code-folding regions

IntelliJ IDEA by JetBrains has this feature.

Either type comments yourself, or use hotkey for "surround with":

  • Windows OS: Ctrl + Alt + T
  • macOS: Command ⌘ + Option ⌥ + T

Regions look like the following.

public class Person
{
    //region Fields
    private String firstName;
    private String lastName;
    //endregion

    //region Constructors
    public Person ( final String firstName , final String lastName )
    {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    //endregion

    //region Accessors
    public String getFirstName ( ) { return firstName; }

    public String getLastName ( ) { return lastName; }
    //endregion
}

Notice:

  • No SPACE character after slashes.
  • Optional group name follows, as seen here with Fields, Constructors, and Accessors.

Arrows appear in the code-editor’s gutter. Click to collapse/expand each region.

Conveniently, your groups appear in the File Structure tool.

screenshot of Structure tool pane listing region groups of methods

See article, company blog post, and documentation.


On a related note, IntelliJ can draw a line above each method.

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for that! Works perfectly on Android Studio.
The question clearly requests a solution for Eclipse.
@Duncan 1. Nothing wrong to show people there are alternatives. 2. I google for regions under Intellij and found it.
On Linux, that hotkey runs terminal
On a mac, select block you want in region, then shortcut is: option + command + T
|
231

There's no such standard equivalent. Some IDEs - Intellij, for instance, or Eclipse - can fold depending on the code types involved (constructors, imports etc.), but there's nothing quite like #region.

12 Comments

Actually this can be achieved. If you scroll down on this post "Yaqub Ahmad" explains how to get this functionality. Also here is a link (kosiara87.blogspot.com/2011/12/…) that shows you how to add it to your existing eclipse environment...extremely useful!
Sure. But there's nothing standard. It's performed in IDEs rather than having a language (or text) construct
@lKashef - so what's the standard equivalent then ? Everything noted below relates to a particular IDE, doesn't it ?
@BrianAgnew, The OP didn't mention anything about standards instead he just want to be able to have regions-like blocks in his code. For instance you said "but there's nothing quite like #region." in IDEA for example //region .. //endregion works exactly like #region. There's no standard way of doing this at all in the first place since it depends on the IDE itself or a plugin. Developers with microsoft backgrounds will always see MS Visual Studio as "The" IDE but in fact it's just one of the options and another IDE might or might not implement such functionality.
@BrianAgnew, I almost gave up until I saw other people's answers which helped more than yours. Seriously no hard feeling here, We are all here to learn and share our knowledge and am stating the fact that I was mislead by your answer, maybe it was a good one back in 2010 but not today. I hope you get my point.
|
218

With Android Studio, try this:

//region VARIABLES
private String _sMyVar1;
private String _sMyVar2;
//endregion

Careful : no blank line after //region ...

And you will get:

8 Comments

was going through all answers and figured since Android Studio is based on IntelliJ then this must be supported. good thing to point it out though!
bummi, I did try it in 0.4.2 with a blank line and still works
Just a comment/advice (and by no means an answer to your question). It is a widespread opinion that regions should be avoided, since they let you hide class complexity instead of working on your coding style. Instead of huge classes, where each class is responsible for a lot of functionality, work on breaking down your code into smaller classes instead. It will make your code easier to manage over time. Read more here: blog.codinghorror.com/the-problem-with-code-folding
@DanielSaidi oh, the horror! :) the guy in the article "I can't see anything! I have to manually expand those sections to browse any of the code in this class." ... so because he's too lazy to press a key (that woulld expand all sections in the file), the feature must not be used - it's a super wonderful feature. Right now I'm using it to one by one hide the methods I've verified are thread safe in the class I'm working one, it really helps to keep organized.Sure once in a while I've wondered where something is that I thought was there, but that is a small price to pay...
@DanielSaidi It's not about hiding complexity but hiding mundane code such as variable declarations, getters, initialization code and so on. Also note that you DO NOT require #regions to collapse the "complex code" found in functions and classes. The beef with programmers using a tool incorrectly does not amount to "the tool is bad".
|
101

No equivalent in the language... Based on IDEs...

For example in netbeans:

NetBeans/Creator supports this syntax:

// <editor-fold defaultstate="collapsed" desc="Your Fold Comment">
...
// </editor-fold>

http://forums.java.net/jive/thread.jspa?threadID=1311

4 Comments

Even though it's not a language specific folding but still helped me in NetBeans. Exactly what I wanted to achieve. Just want my code to be more handy and organized for me.
Is there any shortcut that can auto fill this line?
@pini-cheyni - ui.netbeans.org/docs/ui/code_folding/cf_uispec.html has shortcuts available for folding....
@JadChahine: The OP asked about Eclipse, but agree this works well for NetBeans. Syntax is a slightly clumsy but copy-paste makes it easy enough.
53

Custom code folding feature can be added to eclipse using CoffeeScript code folding plugin.

This is tested to work with eclipse Luna and Juno. Here are the steps

  1. Download the plugin from here

  2. Extract the contents of archive

  3. Copy paste the contents of plugin and features folder to the same named folder inside eclipse installation directory
  4. Restart the eclipse
  5. Navigate Window >Preferences >Java >Editor >Folding >Select folding to use: Coffee Bytes Java >General tab >Tick checkboxes in front of User Defined Fold

    enter image description here

  6. Create new region as shown:

    enter image description here

  7. Restart the Eclipse.

  8. Try out if folding works with comments prefixed with specified starting and ending identifiers

    enter image description here

    enter image description here

You can download archive and find steps at this Blog also.

2 Comments

not working for me on eclipse neon: copy and paste did nothing: the only thing that changed was under marketplace >> installed plugins >>update. I updated the coffeeScript plugin, but I didn't get the option "Select folding to use" under java>> editor >> folding
It worked in the Eclipse Oxygen, however you need to restart the eclipse again. The icon displayed to me was a red icon so I changed in the configuration, Window → Preference → Java → Editor → Folding click at Advanced tab and change the Icon theme set to Modern
51

For Eclipse IDE the Coffee-Bytes plugin can do it, download link is here.

EDIT:

Latest information about Coffee-Bytes is here.

3 Comments

+1 thanks for this info. Since the original website of the developper of the plugin is no longer available in 2012 - i found a short desctription for installation and usage.
anyone found an intelliJ alternative?
The download link does no longer exist.
38

This is more of an IDE feature than a language feature. Netbeans allows you to define your own folding definitions using the following definition:

// <editor-fold defaultstate="collapsed" desc="user-description">
  ...any code...
// </editor-fold>

As noted in the article, this may be supported by other editors too, but there are no guarantees.

1 Comment

In Android studio, at least, you cannot fold part of a block. If the fold spec starts outside of a block, and ends inside a block, it will not activate.
32

the fastest way in Android Studio (or IntelliJ IDEA)

  1. highlight the code you want to surround it
  2. press ctrl + alt + t
  3. press c ==> then enter the description
  4. enjoy

1 Comment

// region <name> Your code... // endregion Is more efficient and simple! hehe ;P
30

AndroidStudio region
Create region

First, find (and define short cut if need) for Surround With menu enter image description here

Then, select the code, press Ctrl+Alt+Semicolon -> choose region..endregion...
enter image description here

Go to region

First, find Custom Folding short cut
enter image description here Second, from anywhere in your code, press Ctrl+Alt+Period('>' on keyboard) enter image description here

Comments

19

Contrary to what most are posting, this is NOT an IDE thing. It is a language thing. The #region is a C# statement.

4 Comments

What most are posting is that IN JAVA this is an IDE feature.
I do see the 2 most popular answers saying there is no such language feature. -1.
In C# it is partly IDE, partly language. The language supports the preprocessor directives, but the preprocessor simply ignores them (the same way processor ignores comments). The IDE (Visual Studio) uses them to do code folding.
Java doesn't has specified code folding only the IDE (Netbeans) has, Netbeans has more special comments like "TODO" and more. They are very useful to track your progress through SW project development process
19

I were coming from C# to java and had the same problem and the best and exact alternative for region is something like below (working in Android Studio, dont know about intelliJ):

 //region [Description]
 int a;
 int b;
 int c;
//endregion

the shortcut is like below:

1- select the code

2- press ctrl + alt + t

3- press c and write your description

3 Comments

In AndroidStudio version 2.3.1 it folds. I don't know when it started to fold.
Thanks. Works perfectly in Android Studio 3.0 beta 2. By curiosity I tried in Eclipse Oxygen, it doesn't work by default but didn't search further.
Worked in IntelliJ as well!
17

The best way

//region DESCRIPTION_REGION
int x = 22;
// Comments
String s = "SomeString";
//endregion;

Tip: Put ";" at the end of the "endregion"

2 Comments

eclipse do not fold the code, what IDE are u using?
It works with Android Studio and IntelliJ IDEA (both are made from same codebase by JetBrains)
12

If anyone is interested, in Eclipse you can collapse all your methods etc in one go, just right click when you'd normally insert a break point, click 'Folding' > 'Collapse all'. It know it's not an answer to the question, but just providing an alternative to quick code folding.

3 Comments

You can also have Eclipse auto-collapse everything when opening a source code file. Preferences > Java > Editor > Folding > "Initially fold these elements" (check all in the list). I find it convenient to focus on only what I need especially in long source code files.
@ADTC - Thanks - so many hundreds of times I've done it manually every time I open a file - never again!!
@ToolmakerSteve If you can do anything repetitive manually on a computer, there just has to be a way to automate it. =D
12

here is an example:

//region regionName
//code
//endregion

100% works in Android studio

1 Comment

I don't know why you have been downvoted, this actually works in Android Studio without any configuration needed!
10
#region

// code

#endregion

Really only gets you any benefit in the IDE. With Java, there's no set standard in IDE, so there's really no standard parallel to #region.

2 Comments

Well if there's a standard to region, then we can be sure that java IDE's will support it isn't it?
@Pacerier if they support that standard, yes. I think #region is more an IDE feature than a standard. In theory the java IDE's could implement this behavior and make it a de-facto standard
3

vscode

I use vscode for java and it works pretty much the same as visual studio except you use comments:

//#region name

//code

//#endregion

enter image description here

Comments

2

I usually need this for commented code so I use curly brackets at start and end of that.

{
// Code
// Code
// Code
// Code
}

It could be used for code snippets but can create problems in some code because it changes the scope of variable.

Comments

2

Meet custom folding regions ⌥⌘T

demo

Comments

2

In Visual Studio Code, try this:

//region Variables
// Code you need
//endregion

Comments

1

Actually johann, the # indicates that it's a preprocessor directive, which basically means it tells the IDE what to do.

In the case of using #region and #endregion in your code, it makes NO difference in the final code whether it's there or not. Can you really call it a language element if using it changes nothing?

Apart from that, java doesn't have preprocessor directives, which means the option of code folding is defined on a per-ide basis, in netbeans for example with a //< code-fold> statement

2 Comments

can you really call it a language element if using it changes nothing? - how about comments ?!
I've hear the argument before that it isn't a function of the language. And this question "Can you really call it a language element if using it changes nothing?" is ridiculous. A lot of time refactoring is making the code easier to read for humans and does nothing (hopefully) to impact the function of the code.
1

On Mac and Android Studio follow this sequence:

  1. Highlight the source code to fold
  2. Press Alt+Command+t
  3. Select <editor-fold>

Also you can select other options:

enter image description here

Comments

-1

In Eclipse you can collapse the brackets wrapping variable region block. The closest is to do something like this:

public class counter_class 
{ 

    { // Region

        int variable = 0;

    }
}

2 Comments

This is useless. It doesn't work inside a method, plus it BREAKS CODE! (Private variables will complain they want to be final. Variable with no scope definition will not be accessible outside the inner brackets!)
I don't like this method, adds too many curly braces. This can lead to confusing code :(
-3

Just intall and enable Coffee-Bytes plugin (Eclipse)

1 Comment

Not only is this mentioned in an earlier answer, but you didn't even provide any useful information about it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.