Java variables, pretty much like variables in any programming language are a name for a memory location. They are used to refer to a chunk of memory. Sometimes (and it is getting increasingly scarce) variables are referred to as fields or properties. Variable is the correct nomenclature and is widely used in literature.
Java is a strongly typed language. Every Java variable is associated with a data type. We will examine data types in the next section. For the moment, remember that not all programming languages have their variables associated with types. For example, a Python variable can have a integer value in one statement and a string value in the next statement.
Four Kinds of Java Variables
Instance Variables
These variables are the cornerstone of object oriented programming. They store the state of an object. Since their main goal is to capture the state of an object, they are obviously unique to every object.
You define an instance variable when you a declare variable in class but outside of methods and constructors. Since instance variables are part of the object, they too are stored in Java heap.
1 2 3 4 | public class Politician { // numberOfFelonies is an instance variable int numberOfFelonies = 18; // more code and more exposure.... |
Instance variables can be used before they are declared. Though archaic practice now, in the initial years Java developers had the habit of declaring the instance variable right at the end of the Class. This is not very reader friendly and should be avoided. Declare an instance variable before using it for the sake of the one who will maintain your code.
Instance variables have default value. If you don’t specify a value, the JVM does it for you. Booleans are initialized to false, integers to zero and so on. An instance variable of reference type is initialized to null.
You can associate visibilty with instance variables by declaring them public, private or protected. It is never a good idea to make instance variables public because this would vioate the encapsulation priniciple of object oriented programming. More often than not, instance variables must be private.
Lastly, instance variables are extremely useful because they are shared between all the methods and constructors of the class. This allows sharing of data between methods, which otherwise would have been very complicated.
If you try writing code that passes state around various methods using parameters, you will realize how much extra code you need to write. Most of that code would be boilerplate.
Instance variables save you from such hassles and capture the state of objects.
Local Variables
Local variables are pretty much like instance variables with the difference that they are declared inside a method, a method or a code block. A code block may be created using statements such as if, while, for, switch. In Java, it is safe to assume that ‘{‘ marks the beginning of a code block.
Local variables don’t exist outside the scope in which they are defined and used. Since the lifetime of local variables is governed by the scope of the block they are contained in, you cannot associate an access modifiers with local variables. Further, there is no default initializtion of local variables.
1234567891011 | public class Politician { public void robPeople() { boolean hellFreezesOver = true; int liesTold = 1000; String myTrap = “I serve people.”; while(hellFreezesOver) { System.out.println(myTrap); liesTold++; …. // more crimes and lies |
In the above example liesTold, hellFreezesOver and myTrap are local variables. You have to explicity initalize them. They go out of scope when the execution of robPeople() terminates. (Phew! I am waiting for that day.)
Since number of lies told and trap of a politician are his/her traits, it would have made more sense to make these instance variables. We postpone this discussion for the lesson OOP.
Static or Class-level Variables
Class level variables are different from other variables by the very fact that they are instantiated on per-class basis. Whereas every object has its own copy of instance variables in the heap, all objects share the static variable. There is only one copy of static variable.
This can come in very handy when objects need to inter communicate. The static variable can act like a blackboard where an object writes some value and other objects are able to read it. This is made possible because all the objects try to read the same variable.
Carrying the above blackboard logic forward, static variables can also be used to define constants. Constants are declared by making variable public static final. public ensures that everybody can access it. final ensures that nobody else tries to change it. static of course makes sure that there is only one copy. This again acts like a blackboard. A class writes a final variable on the blackboard for everyone to read. As a matter of convention constants in Java are all capitals.
1 | public static final String PITCH = “I serve people out of compassion!”; |
Like instance variables, static variables are also initialized to default value and can be associated with access modifiers.
Parameters
Parameters are variables that capture the value passed to a Java method or constructor. These variables should be limited to this task only. Unless the parameters are declared final, Java allows you to reassign value to a parameter. This is never recommended as it reduces the code readability.
Variable Naming Conventions
Java gives you a lot of flexibility in terms of what you choose to call your variable. Still, there are some rules and some widely followed conventions that you must know –
- Variable names are case sensitive.
- Variable names must start with letter, $ or _. But you should always use letter as the first name of the variable. A word of caution for PHP programmers – it may be tempting to use $ as the first character of variable name. Don’t do that, it is considered awkward in Java world.
- After the first character, variable names may containg letter, number, $ or _ . Again, by convention $ and _ are not favored.
- Variables must not be either overly long or short. “int x” does not say much about the purpose of the variable x. “int myBankBalanceAsOnTuesdayMayTheTwentyThird” is not recommended either. It is truly a typing and coding horror.
- Java variables use camelCase and typically begin with small letter. So, if you want to have a variable for bank balance, it should be bankBalance rather than bank_balance or BankBalance. Class names also use CamelCase but begin with capital letter.