43

Why do we add an _ (underscore) before a variable name in Java while variable declaration?

I have tried on Google Search, but I actually couldn't find the exact answer for it.

Is it just a type of declaration as the user wants or is there any proper mechanism and reason to do so?

8
  • 25
    Well, usually we don't. Commented Dec 19, 2013 at 9:02
  • I've seen such practice for private variables in flex/action script. But not in Java. Commented Dec 19, 2013 at 9:03
  • 1
    @AmanArora - that i also know, I want reason. I am beginner so I am asking, I am not expecting this answer. Commented Dec 19, 2013 at 9:07
  • To distinguish between Static variables and instance variables,maybe ! Commented Dec 19, 2013 at 9:08
  • As Maroun mentioned its to distinguish between these 2 variables. At my university I actually learned to do it like that in C#, but never saw it in Java... dont know if this is just a microsoft thing or at least more often used there Commented Dec 19, 2013 at 9:12

4 Answers 4

59

Sometimes it is used in order to distinguish class members from local variables:

public class MyClass {
   private int _salary;

   public MyClass(int salary) {
       _salary = salary
   }
} 

However, you should follow Java Naming Conventions that doesn't recommend using that. You can simply name the class member without the leading _ and do:

this.salary = salary;
Sign up to request clarification or add additional context in comments.

3 Comments

This is enforced by Resharper. So it's maybe part of IntelliJ IDE.
That page is not maintained anymore and may no longer be valid... April 20, 1999!
@Yousha Aleayoub: Yes, indeed: "The information on this page is for archive purposes only. This page is not being actively maintained. Links within the documentation may not work and the information itself may no longer be valid. The last revision to this document was made on April 20, 1999"
5

The use of "_" (underscore) must be evaluated carefully.

Use "_" to indicate class attributes is used a lot in C++.

In Java, it is not necessary, because the language has the keyword this.

1 Comment

C++ has this too, and the underscore has no more or less meaning in C++ than in Java (none, it's just a matter of coding conventions)
3

This should be an idiomatic usage, and describe it is a private variable.

Also, this is a way to define a private method in Python to add the "_" as the method prefix like def _privateMethodName(self):.

1 Comment

But this is about Java, not Python(?).
3

An underscore in front usually indicates an instance variable as opposed to a local variable. It's merely a coding style that can be omitted in favor of "speaking" variable names and small classes that don't do too many things.

Comments