Variables in Java

Today let's talk about variables in Java. In Java mainly we can have four different variable types.

1. Instance Variables (Non-Static Fields)
    Instance variables are used to refer the objects(instances) of classes.

2. Class Variables (Static Fields)
    Here we use static modifier in front of the variable name and this tells the compiler that there is           exactly one copy of this variable in existence. If we use the keyword final also then that would           indicate that the value of the variable will never change.

3. Local Variables
    These variables are declared inside a method and they are only visible within that particular                  method and not accessible from the rest of the class. 

4. Parameters
    Let's take the main method as an example, public static void main(String [] args){ } ,here args            variable is the parameter to this method. And constructors also take parameter variables as                   arguments.

You may be confused by the words 'variable' and 'fields'. Local variables and Parameters are not called fields. An object stores its state in fields.

Java Variable Naming Rules

  • A variable name can begin with a letter, dollar sign ($) or underscore( _ ) . But it is better not to begin with a $ or _ because some auto-generated names start with a $ sign.
  • A variable name cannot begin with a digit.
  • White spaces are not allowed in a variable name.
  • We cannot use key words in Java as variable names.
abstractcontinuefornewswitch
assertdefaultgotopackagesynchronized
booleandoifprivatethis
breakdoubleimplementsprotectedthrow
byteelseimportpublicthrows
caseenuminstanceofreturntransient
catchextendsintshorttry
charfinalinterfacestaticvoid
classfinallylongstrictfpvolatile
const*floatnativesuperwhile

When you are declaring a non-static variable it is better to use Lower CamelCase Notation for it. Start the variable name with a lower case letter and then if it consists of more than one word, capitalize the first letter of each subsequent word.

 ex: thisIsLowerCamelCase 

Constant Variable Declaration

When declaring a constant variable, the standard is to use upper case for every letter, and if it consists  of more than one word, separate them with underscore ( _ ) character.

ex: static final int START_POINT = 10 ;

Comments

Popular posts from this blog

UML - Use Case Diagrams

How I faced to OCJP exam...

My Experience at Women Techmakers Leads Mini-summit APAC at Google Singapore