I got confused with the (naming convention) use of underscore _
in variable names and method names as their starting letter. For example, _sampleVariable
and _getUserContext()
. When should I use it?

- 30,738
- 21
- 105
- 131

- 2,081
- 7
- 35
- 58
-
go through this http://stackoverflow.com/questions/150192/using-underscores-in-java-variables-and-method-names – Rishikesh Dhokare May 28 '13 at 06:32
-
1Its simply a coding style to identity `member variables.` But i suggest use `camelCase`, not underscores. [**Oracle PDF for naming conventions**](http://www.oracle.com/technetwork/java/codeconventions-150003.pdf) – Suresh Atta May 28 '13 at 06:27
5 Answers
See the Java Naming Conventions
Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed.
The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_"). (ANSI constants should be avoided, for ease of debugging.)

- 30,738
- 21
- 105
- 131
Sometimes people use underscores to indicate that their variable or method is private. I do not like this way of doing it. I suggest you to use lower camel case too.

- 30,738
- 21
- 105
- 131

- 447
- 1
- 3
- 11
-
1Re *"too"*: Do you mean *"[instead](https://en.wiktionary.org/wiki/instead#Adverb)"*? – Peter Mortensen May 16 '22 at 14:21
Quoting the book Clean Code by Robert C. Martin,
Sometimes it is useful to warn other programmers about certain consequences.
Example
// Don't run unless you // have some time to kill. public void _testWithReallyBigFile() { writeLinesToFile(10000000); response.setBody(testFile); response.readyToSend(this); String responseString = output.toString(); assertSubString("Content-Length: 1000000000", responseString); assertTrue(bytesSent > 1000000000); }
Nowadays, of course, we’d turn off the test case by using the @Ignore attribute with an appropriate explanatory string. @Ignore("Takes too long to run"). But back in the days before JUnit 4, putting an underscore in front of the method name was a common convention.

- 30,738
- 21
- 105
- 131

- 2,159
- 23
- 39
Normally it should not be used, except as a separator in all uppercase constants that are usually final (allStars but ALL_STARS).
Exactly because normally not expected, the underscore is abundant in generated code. It may also be found in some older code, but this is not the reason to continue using it.

- 30,738
- 21
- 105
- 131

- 20,936
- 12
- 75
- 93
Usually _ is used in variables to represent them as class level private variables.

- 30,738
- 21
- 105
- 131

- 1,360
- 9
- 11