Java Variables: Naming Rules, Type Casting and Dynamic Initialization

Java Variables

Java Variables or variables in any other programming language are containers, which hold some value. Because Java is a strongly typed language, so every variable must be declared and initialized or assigned before it is used. A variable, in the simplest way, is declared by placing a valid type followed by the variable name. And so, don't forget to place a semicolon at the end of every statement because it completes the statement. Throughout the tutorial we will use terms 'variable' and 'field' interchangeably as they refer to the same thing and there should be no confusion regarding that. Following statements demonstrate variable declaration in Java

byte age; //contains -128 to 127
long population;
float temperature;
double salary;

Java Variables - Naming Rules and Conventions

While naming Java variables we have to adhere to some naming rules. Such as:

  1. Variable names are case-sensitive.
  2. Variable name can be an unlimited-length sequence of Unicode letters and digits.
  3. Variable name must begin with either a letter or the dollar sign "$", or the underscore character "_".
  4. Characters except the dollar sign "$" and the underscore character "_" for example, '+' or '?' or '@' are invalid for a variable name.
  5. No white space is permitted in variable names.
  6. Variable name we choose must not be a keyword or reserved word.

Additional to above mentioned naming rules Java developers also adhere to some naming conventions for Java variables but these conventions are totally optional. So it is your wish if you follow them or not. However, following naming conventions is a great practice and it makes your program more readable and beautiful. Most prevalent naming conventions are as follows:

  1. Always begin your Java variable names with a letter, not "$" or "_"
  2. The dollar sign character, by convention, is never used at all in Java variables. There may be situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it
  3. It's technically legal to begin your variable's name with "_" but this practice is discouraged
  4. Choosing full words instead of cryptic abbreviations for variable names are always considered good, it makes your code easier to read and understand
  5. If chosen Java variable name consists of only one word, use all lower-case letters to spell it. If it consists of more than one word, capitalize the first letter of each subsequent word. The names firstChoice and reverseGear are good examples of this convention. For constant valued variables, such as static final int NUM_OF_CHOICES = 7, the convention changes slightly, capitalizing all letter and separating subsequent words with the underscore character. By convention, the underscore character is not used elsewhere.

As it has been said, above conventions are not rules therefore they can be compromised when needed.

Java Variable Types

Java variables are categorized in different types depending upon where are they declared? For example, in a class or in a method's body. Java defines following four types of variables.

Local Variables

As name suggests, a local Java variable is scoped to the block, which is between the opening and closing braces. Local variables are declared within a block or constructor or method's body. Local variables are created when control enters into the block or constructor of method's body and are destroyed once the control exits from the body of method or constructor or block.

Local variables are only visible to the methods or blocks or constructors in which they are declared; they are not accessible from the rest of the class. There is no designated access modifier for local variables. Also, there is no default value for local variables, therefore, local variables must be initialized or assigned some value before they are used first time.

Instance Variables or Non-Static Fields

Data members or fields or variables of a class that are declared non-static, but outside a method, constructor or any block are known as instance variables. Instance variables are created when an object of a class is created by using new keyword. Objects store their states in non-static instance variables. Instance variables are declared private or public or protected or default (no keyword). Instance variables are initialized to some default values by the compiler, in case they are not initialized by the creator of class. Instance variables are destroyed along with the object they have been created for. The following program declares some non-static instance variables:

/* */
class Book
	//instance variables
	private String title;
	private String publisher;
	private int numOfPages;
	//zero argument constructor needed when 
	//one or more argument constructors are defined
	public Book() {} 
	public Book (String title, String publisher, int numOfPages)
		this.title = title;
		this.publisher = publisher;
		this.numOfPages = numOfPages;
	public void printBookDetails()
		System.out.println("Title: " + title);
		System.out.println("Publisher: " + publisher);
		System.out.println("Num of Pages: " + numOfPages);

Class Variables or Static Fields

Class variables in Java are fields declared with static keyword. Modifier static informs the compiler that there will be only one copy of such variables created regardless of how many objects of this class are created. Static variables are created when a class is loaded into the memory by the class loader and destroyed when a class is destroyed or unloaded. Visibility of static fields will depend upon access modifiers. Default vales given to the static members will follow the same rule as it is done in instance variables.

Method Parameters

While passing values to member methods we need parameter variables. Parameters are not fields; they are always called variables and used only to copy their values into the formal parameters. Variables or values passed to a method by caller are called actual parameters, and the callee receives these values in formal parameters. Formal parameters are local variables to that particular method.

Java Variables - Dynamic Initialization

Initialization is the process of providing value to a variable at declaration time. A variable is initialized once in its life time. Any attempt of setting a variable's value after its declaration is called assignment. To use a local variable you have to either initialize or assign it before the variable is first used. But for class members, the compulsion is not so strict. If you don't initialize them then compiler takes care of the initialization process and set class members to default values.

Java allows its programmers to initialize a variable at run time also. Initializing a variable at run time is called dynamic initialization. The following piece of code ( demonstrates it.

/* */
public class DynamicInitializationDemo
    public static void main(String[] args) 
        //dynSqrt will be initialized when Math.sqrt
        //will be executed at run time
        double dynSqrt = Math.sqrt (16);
        System.out.println("sqrt of 16 is : " + dynSqrt);
sqrt of 16 is : 4.0

Java Variables - Intermediate Type Promotion

In some situations intermediate result of an expression is out of range of the variable to which the final result has to be assigned, while the final result is in variable's range? Let's consider an example where we have to compute average age of three octogenarians. Suppose we store individual's and average age in byte variables. The ages of all three are 82, 87, and 89 years respectively. Now to compute the average of their age you first have to add all three ages together and then divide it by 3. But, if you see, as soon as you add all three ages you will get 258 that is beyond the range of byte (127 is the largest positive value a byte can store), while the final averaged age 86 that is in the range of byte.

Java handles this situation very smartly by promoting intermediate results to integer. But it imposes an extra overhead on programmers to cast results back to the resultant type, byte in our case. See the following piece of code.

/* */
public class TypePromotionDemo
    public static void main(String[] args) 
        byte age1 = 82, age2 = 87, age3 = 89;
        byte avgAge = (byte) ((age1 + age2 + age3) / 3); //cast int to byte
        System.out.println("Average age is : " + avgAge);
Average age is : 86

In addition to the elevation of byte to int, Java defines several type promotion rules that apply to expressions. First, all byte and short values are promoted to int, as just described. Then, if one operand is a long, the whole expression is promoted to long. If one operand is a float, the entire expression is promoted to float. If any of the operands is double, the result is double.

Java Variables - Type Conversion and Type Casting

When value of one variable is assigned to another or a literal is assigned to a variable then either automatic type conversion takes place or we have to type cast explicitly. Automatic type conversion is done when either both sides (left and right) are of same type or the left hand (destination) side is larger in size. The latter is called widening. For example, assigning byte to short or int to long.

If we wish to assign incompatible types then we will have to type cast at our own and according to the problem for example, int to short conversion will not be done automatically, because short is smaller than int. In this case we will have to explicitly cast it and this conversion is called narrowing.

Java is Statically Typed Language

Note that Java is a statically-typed language that means the type of a variable must be known at compile time, as type checking is done during compilation of the code. The main advantage static typing offers is that type checking is done by the compiler before the program is executed. The compiler can therefore deduce whether or not a given variable is capable of performing actions requested of it. For example, the following piece of code will result into compilation error.

/* */
public class StaticTypedDemo
    public static void main(String[] args) 
        byte s = 90;
        s = s + 2; // Type mismatch: cannot convert from int to byte

Because, in statement s = s + 2; the intermediate term s + 2 is automatically promoted to int and therefore, cannot be assigned to a byte without the use of a cast. The same example also illustrates the strong type checking that Java places severe restrictions on the intermixing of operations that is permitted to occur.

Last Word

In this tutorial we talked of Java variable types, their naming rules and conventions, dynamic initialization of Java variables, automatic and explicit type casting of variables, and how Java is a strongly typed language. Hope you have enjoyed reading this tutorial. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!


Get Free Tutorials by Email

About the Author

is the main author for He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.

Today's Tech News

Facebook to exclude billions from European privacy lawsPosted on Thursday April 19, 2018

A total of 1.5 billion international Facebook users will not be protected under GDPR.

TalkTalk and Vodafone top complaints chart againPosted on Thursday April 19, 2018

TalkTalk, Vodafone and BT drew the most complaints for their services, the regulator says.

Ikea's TaskRabbit app back online after data breachPosted on Thursday April 19, 2018

The odd jobs marketplace has been investigating a "cyber-security incident".

Courtesy BBC News


Advertisements help running this site for free.

To view the content please disable AdBlocker and refresh the page.