Skip to content Skip to navigation


You are here: Home » Content » Jb0200: Java OOP: Variables


Recently Viewed

This feature requires Javascript to be enabled.

Jb0200: Java OOP: Variables

Module by: R.G. (Dick) Baldwin. E-mail the author

Summary: Earlier modules have touched briefly on the topic of variables. This module discusses Java variables in depth.


Earlier modules have touched briefly on the topic of variables. This module discusses Java variables in depth.

Viewing tip

I recommend that you open another copy of this module in a separate browser window and use the following links to easily find and view the images and listings while you are reading about them.




The first step

The first step in learning to use a new programming language is usually to learn the foundation concepts such as

  • variables
  • types
  • expressions
  • flow-of-control, etc.

This and several future modules concentrate on that foundation.

A sample program

The module begins with a sample Java program named simple1 . The user is asked to enter some text and to terminate with the # character.

(This program contains a lot of code that you are not yet prepared to understand. For the time being, just concentrate on the use of variables in the program. You will learn about the other aspects of the program in future modules.)

The program loops, saving individual characters until encountering the # character. When it encounters the # character, it terminates and displays the character entered immediately prior to the # character.

Sample program named simple1

A complete listing of the program named simple1 is provided in Listing 1 . Discussions of selected portions of the program are presented later in the module.

Listing 1: Source code for the program named simple1.

/*File Copyright 1997, R.G.Baldwin
This Java application reads bytes from the keyboard until
encountering the integer representation of '#'.  At 
the end of each iteration, it saves the byte received and 
goes back to get the next byte.

When the '#' is entered, the program terminates input and
displays the character which was entered before the #.

class simple1 { //define the controlling class

  //It is necessary to declare that this method 
  // can throw the exception shown below (or catch it).
  public static void main(String[] args) //define main 
                        throws {

    //It is necessary to initialize ch2 to avoid a compiler
    // error (possibly unitialized variable) at the 
    // statement which displays ch2.
    int ch1, ch2 = '0';

                      "Enter some text, terminate with #");

    //Get and save individual bytes
    while( (ch1 = ) != '#') 
      ch2 = ch1;

    //Display the character immediately before the #
          "The char before the # was " + (char)ch2);
  }//end main
}//End simple1 class.

Program output

The output produced by compiling and running this program is shown in Image 1 . The second line of text in Image 1 ending with the # character was typed by the user.

Image 1: Screen output from the program named simple1.

Enter some text, terminate with #
The char before the # was e

Discussion of the simple1 program


I will use the program shown in Listing 1 to discuss several important aspects of the structure of a Java program. I will also provide two additional sample programs that illustrate specific points not illustrated in the above program later in this module.



What is a variable?

Variables are used in a Java program to contain data that changes during the execution of the program.

Declaring a variable

To use a variable, you must first notify the compiler of the name and the type of the variable. This is known as declaring a variable .

The syntax for declaring a variable is to precede the name of the variable with the name of the type of the variable as shown in Listing 2 . It is also possible (but not required) to initialize a variable in Java when it is declared as shown in Listing 2 .

Listing 2: Declaring and initializing two variables named ch1 and ch2.

int ch1, ch2 = '0';

The statement in Listing 2 declares two variables of type int , initializing the second variable (ch2) to the value of the zero character (0). (Note that I didn't say initialized to the value zero.)


Difference between zero and '0' - Unicode characters

The value of the zero character is not the same as the numeric value of zero, but hopefully you already knew that.

As an aside, characters in Java are 16-bit entities called Unicode characters instead of 8-bit entities as is the case with many programming languages. The purpose is to provide many more possible characters including characters used in alphabets other than the one used in the United States.

Initialization of the variable

Initialization of the variable named ch2 in this case was necessary to prevent a compiler error. Without initialization of this variable, the compiler would recognize and balk at the possibility that an attempt might be made to execute the statement shown in Listing 3 with a variable named ch2 that had not been initialized

Listing 3: Display the character.

System.out.println("The char before the # was " 
                                       + (char)ch2);

Error checking by the compiler

The strong error-checking capability of the Java compiler would refuse to compile this program until that possibility was eliminated by initializing the variable.

Using the cast operator

You should also note that the contents of the variable ch2 is being cast as type char in Listing 3 .

(A cast is used to change the type of something to a different type.)

Recall that ch2 is a variable of type int , containing the numeric value that represents a character.

We want to display the character that the numeric value represents and not the numeric value itself. Therefore, we must cast it (purposely change its type for the evaluation of the expression) . Otherwise, we would not see the character on the screen. Rather, we would see the numeric value that represents that character.


Initialization of instance variables and local variables:

As another aside, member variables in Java are automatically initialized to zero or the equivalent of zero. However, local variables , of which ch2 is an example, are not automatically initialized.

Why declare the variables as type int?

It was necessary to declare these variables as type int becausethe statement in Listing 4 (more specifically, the call to the method) returns a value of type int .

Listing 4: Beginning of a while loop.

while( (ch1 = ) != '#') ch2 = ch1;

Java provides very strict type checking and generally refuses to compile statements with type mismatches.

(There is a lot of complicated code in Listing 4 that I haven't previously explained. I will explain that code later in this and future modules.)

Another variable declaration

The program in Listing 1 also makes another variable declaration shown by the statement in Listing 5 .

Listing 5: Beginning of the main method.

public static void main(String[] args) //define main method

An array of String references

In Listing 5 , the formal argument list of the main method declares an argument named args (first cousin to a variable) as a reference to an array object of type String .

Capturing command-line arguments in Java

As you learned in an earlier module, this is the feature of Java that is used to capture arguments entered on the command line, and is required whether arguments are entered or not. In this case, no command-line arguments were entered, and the variable named args is simply ignored by the remainder of the program.

The purpose of the type of a variable


All variables must have a declared type

The type determines the set of values that can be stored in the variable and the operations that can be performed on the variable.

For example, the int type can only contain whole numbers (integers) . A whole host of operations are possible with an int variable including add, subtract, divide, etc.

Signed vs. unsigned variables

Unlike C++, all variables of type int in Java contain signed values. In fact, with the exception of type char , all primitive numeric types in Java contain signed values.

Platform independence

At this point in the history of Java, a variable of a specified type is represented exactly the same way regardless of the platform on which the application or applet is being executed.

This is one of the features that causes compiled Java programs to be platform-independent.

Primitive types

In Java, there are two major categories of data types:

  • primitive types
  • reference (or object) types.

Primitive variables contain a single value of one of the eight primitive types shown in Listing 2 .

Reference variables contain references to objects (or null, meaning that they don't refer to anything) .

The eight primitive types in Java?

The table in Image 2 lists all of the primitive types in Java along with their size and format, and a brief description of each.

Image 2: Information about the primitive types in Java.

Type       Size/Format                 Description
byte      8-bit two's complement     Byte-length integer
short    16-bit two's complement     Short integer
int      32-bit two's complement     Integer               
long     64-bit two's complement     Long Integer
float    32-bit IEEE 754 format      Single-precision 
                                     floating point
double   64-bit IEEE 754 format      Double-precision 
                                     floating point
char     16-bit Unicode character    Single character
boolean  true or false               True or False

The char type

The char type is a 16-bit Unicode character value that has the possibility of representing more than 65,000 different characters.

Evaluating a primitive variable

A reference to the name of a primitive variable in program code evaluates to the value stored in the variable. In other words, when you call out the name of a primitive variable in your code, what you get back is the value stored in the variable.

Object-oriented wrappers for primitive types

Primitive types are not objects

Primitive data types in Java (int, double, etc.) are not objects. This has some ramifications as to how they can be used (passing to methods, returning from methods, etc.) .

The generic Object type

Later on in this course of study, you will learn that much of the power of Java derives from the ability to deal with objects of any type as the generic type Object . For example, several of the standard classes in the API (such as the powerful Vector class) are designed to work only with objects of type Object .

(Note that this document was originally published prior to the introduction of generics in Java. The introduction of generics makes it possible to cause the Vector class to deal with objects of types other than Object . However, that doesn't eliminate the need for wrapper classes.)

Converting primitives to objects

Because it is sometimes necessary to deal with a primitive value as though it were an object, Java provides wrapper classes that support object-oriented functionality for Java's primitive data types.

The Double wrapper class

This is illustrated in the program shown in Listing 6 that deals with a double type as an object of the class Double .

(Remember, Java is a case-sensitive language. Note the difference between the primitive double type and the class named Double .)

Listing 6: The program named wrapper1.

/*File Copyright 1997, R.G.Baldwin
This Java application illustrates the use of wrappers 
for the primitive types.

This program produces the following output:

My wrapped double is 5.5
My primitive double is 10.5

class wrapper1 { //define the controlling class
  public static void main(String[] args){//define main

    //The following is the declaration and instantiation of 
    // a Double object, or a double value wrapped in an 
    // object. Note the use of the upper-case D.
    Double myWrappedData = new Double(5.5);

    //The following is the declaration and initialization 
    // of a primitive double variable. Note the use of the
    // lower-case d.
    double myPrimitiveData = 10.5;

    //Note the call to the doubleValue() method to obtain 
    // the value of the double wrapped in the Double 
    // object.
      "My wrapped double is " + myWrappedData.doubleValue());
             "My primitive double is " + myPrimitiveData );
  }//end main
}//End wrapper1 class.

The operation of this program is explained in the comments, and the output from the program is shown in the comments at the beginning.

Reference types

Once again, what is a primitive type?

Primitive types are types where the name of the variable evaluates to the value stored in the variable.

What is a reference type?

Reference types in Java are types where the name of the variable evaluates to the address of the location in memory where the object referenced by the variable is stored.


The above statement may not really be true?

However, we can think of it that way. Depending on the particular JVM in use, the reference variable may refer to a table in memory where the address of the object is stored. In that case the second level of indirection is handled behind the scenes and we don't have to worry about it.

Why would a JVM elect to implement another level of indirection? Wouldn't that make programs run more slowly?

One reason has to do with the need to compact memory when it becomes highly fragmented. If the reference variables all refer directly to memory locations containing the objects, there may be many reference variables that refer to the same object. If that object is moved for compaction purposes, then the values stored in every one of those reference variables would have to be modified.

However, if those reference variables all refer to a table that has one entry that specifies where the object is stored, then when the object is moved, only the value of that one entry in the table must be modified.

Fortunately, that all takes place behind the scenes and we as programmers don't need to worry about it.

Primitive vs. reference variables

We will discuss this in more detail in a future module. For now, suffice it to say that in Java, a variable is either a primitive type or a reference type, and cannot be both.

Declaring, instantiating, initializing, and manipulating a reference variable

The fragment of code shown in Listing 7 , (which was taken from the program shown in Listing 6 that deals with wrappers) does the following. It

  • declares,
  • instantiates,
  • initializes, and
  • manipulates a variable of a reference type named myWrappedData .

In Listing 7 , the variable named myWrappedData contains a reference to an object of type Double .

Listing 7: Aspects of using a wrapper class.

Double myWrappedData = new Double(5.5);

//Code deleted for brevity

//Note the use of the doubleValue() method to obtain the
// value of the double wrapped in the Double object.
  ("My wrapped double is " + myWrappedData.doubleValue() );

Variable names

The rules for naming variables are shown in Image 3 .

Image 3: Rules for naming variables.
  • Must be a legal Java identifier (see below) consisting of a series of Unicode characters. Unicode characters are stored in sixteen bits, allowing for a very large number of different characters. A subset of the possible character values matches the 127 possible characters in the ASCII character set, and the extended 8-bit character set, ISO-Latin-1 (The Java Handbook, page 60, by Patrick Naughton).
  • Must not be the same as a Java keyword and must not be true or false.
  • Must not be the same as another variable whose declaration appears in the same scope.

The rules for legal identifiers are shown in Image 4 .

Image 4: Rules for legal identifiers.
  • In Java, a legal identifier is a sequence of Unicode letters and digits of unlimited length.
  • The first character must be a letter.
  • All subsequent characters must be letters or numerals from any alphabet that Unicode supports.
  • In addition, the underscore character (_) and the dollar sign ($) are considered letters and may be used as any character including the first one.


What is the scope of a Java variable?

The scope of a Java variable is defined by the block of code within which the variable is accessible.

(Briefly, a block of code consists of none, one, or more statements enclosed by a pair of matching curly brackets.)

The scope also determines when the variable is created (memory set aside to contain the data stored in the variable) and when it possibly becomes a candidate for destruction (memory returned to the operating system for recycling and re-use) .

Scope categories

The scope of a variable places it in one of the four categories shown in Image 5 .

Image 5: Scope categories.
  • member variable
  • local variable
  • method parameter
  • exception handler parameter

Member variable

A member variable is a member of a class (class variable) or a member of an object instantiated from that class (instance variable) . It must be declared within a class, but not within the body of a method or constructor of the class.

Local variable

A local variable is a variable declared within the body of a method or constructor or within a block of code contained within the body of a method or constructor.

Method parameters

Method parameters are the formal arguments of a method. Method parameters are used to pass values into and out of methods. The scope of a method parameter is the entire method for which it is a parameter.

Exception handler parameters

Exception handler parameters are arguments to exception handlers. Exception handlers will be discussed in a future module.

Illustrating different types of variables in Java

The Java program shown in Listing 8 illustrates

  • member variables (class and instance) ,
  • local variables, and
  • method parameters.

An illustration of exception handler parameters will be deferred until exception handlers are discussed in a future module.

Listing 8: The program named member1.

/*File Copyright 1997, R.G.Baldwin
Illustrates class variables, instance
variables, local variables, and method parameters.

Output from this program is:

Class variable is 5
Instance variable is 6
Method parameter is 7
Local variable is 8

class member1 { //define the controlling class
  //declare and initialize class variable
  static int classVariable = 5;
  //declare and initialize instance variable
  int instanceVariable = 6;

  public static void main(String[] args){ //main method
    System.out.println("Class variable is "
                                          + classVariable);

    //Instantiate an object of the class to allow for
    // access to instance variable and method.
    member1 obj = new member1();
    System.out.println("Instance variable is "
                                   + obj.instanceVariable);
    obj.myMethod(7); //call the method

    //declare and intitialize a local variable
    int localVariable = 8;
    System.out.println("Local variable is "
                                          + localVariable);

  }//end main

  void myMethod(int methodParameter){
    System.out.println("Method parameter is "
                                        + methodParameter);
  }//end myMethod
}//End member1 class.

Declaration of local variables

In Java, local variables are declared within the body of a method or within a block of code contained within the body of a method.

Scope of local variables

The scope of a local variable extends from the point at which it is declared to the end of the block of code in which it is declared.

What is a "block" of code?

A block of code is defined by enclosing it within curly brackets as in { ... }.

Therefore, the scope of a local variable can be the entire method, or can reduced by declaring it within a block of code within the method.


Special case, scope within a for loop

Java treats the scope of a variable declared within the initialization clause of a for statement to be limited to the total extent of the for statement.

A future module will explain what is meant by a for statement or a for loop.

Initialization of variables

Initializing primitive local variables

Local variables of primitive types can be initialized when they are declared using statements such the one shown in Listing 9 .

Listing 9: Initialization of variables.

int MyVar, UrVar = 6, HisVar;

Initializing member variables

Member variables can also be initialized when they are declared.

In both cases, the type of the value used to initialize the variable must match the type of the variable.

Initializing method parameters and exception handler parameters

Method parameters and exception handler parameters are initialized by the values passed to the method or exception handler by the calling program.

Run the programs

I encourage you to copy the code from Listing 1 , Listing 6 , and Listing 8 . Compile the code and execute it. Experiment with the code, making changes, and observing the results of your changes. Make certain that you can explain why your changes behave as they do.


This section contains a variety of miscellaneous information.


Housekeeping material
  • Module name: Jb0200: Java OOP: Variables
  • File: Jb0200.htm
  • Originally published: 1997
  • Published at 11/18/12
  • Revised: 01/02/13



Financial : Although the Connexions site makes it possible for you to download a PDF file for this module at no charge, and also makes it possible for you to purchase a pre-printed version of the PDF file, you should be aware that some of the HTML elements in this module may not translate well into PDF.

I also want you to know that, I receive no financial compensation from the Connexions website even if you purchase the PDF version of the module.

In the past, unknown individuals have copied my modules from, converted them to Kindle books, and placed them for sale on showing me as the author. I neither receive compensation for those sales nor do I know who does receive compensation. If you purchase such a book, please be aware that it is a copy of a module that is freely available on and that it was made and published without my prior knowledge.

Affiliation : I am a professor of Computer Information Technology at Austin Community College in Austin, TX.


Content actions

Download module as:

PDF | EPUB (?)

What is an EPUB file?

EPUB is an electronic book format that can be read on a variety of mobile devices.

Downloading to a reading device

For detailed instructions on how to download this content's EPUB to your specific device, click the "(?)" link.

| More downloads ...

Add module to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

Definition of a lens


A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks