Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures


Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips


Submit News
Search the site here...
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

Easy Java Lecture 5: Variables. Teach/learn online

JavaFAQ Home » Java Lectures by Anatoliy Malyarenko Go to all tips in Java Lectures by Anatoliy Malyarenko

Bookmark and Share


by: Anatoliy Malyarenko


  • Contents of the lecture.
  • What is a variable?
  • Data types.
  • Scope.
  • Variable initialisation.
  • Final variables.
  • Summary of variables.

What is a variable?

An object stores its state in variables.

Definition 1. A variable is an item of data named by an identifier.

You must explicitly provide a name and a type for each variable you want to use in your program. The variable's name must be a legal identifier -- an unlimited series of Unicode characters that begins with a letter. You use the variable name to refer to the data that the
variable contains. The variable's type determines what values it can hold and what operations can be performed on it. To give a variable a type and a name, you write a variable declaration, which generally looks like this:

type name

In addition to the name and type that you explicitly give a variable, a variable has scope. The section of code where the variable's simple name can be used is the variable's scope. The variable's scope is determined implicitly by the location of the variable declaration, that is,
where the declaration appears in relation to other code elements.

The MaxVariablesDemo program, shown below, declares eight variables of different types within its main method.


public class MaxVariablesDemo {
   public static void main(String args[]) {
      // integers
      byte largestByte = Byte.MAX_VALUE;
      short largestShort = Short.MAX_VALUE;
      int largestInteger = Integer.MAX_VALUE;
      long largestLong = Long.MAX_VALUE;
      // real numbers
      float largestFloat = Float.MAX_VALUE;
      double largestDouble = Double.MAX_VALUE;

      // other primitive types
      char aChar = ā€™Sā€™;
      boolean aBoolean = true;

      // display them all
      System.out.println("The largest byte value is "
                                       + largestByte);
      System.out.println("The largest short value is "
                                       + largestShort);
      System.out.println("The largest integer value is "
                                       + largestInteger);
      System.out.println("The largest long value is "
                                       + largestLong);
      System.out.println("The largest float value is "
                                       + largestFloat);
      System.out.println("The largest double value is "
                                       + largestDouble);
      if (Character.isUpperCase(aChar)) {
         System.out.println("The character " + aChar
                                    + " is upper case.");
      } else {
         System.out.println("The character " + aChar
                                    + " is lower case.");
         System.out.println("The value of aBoolean is "
                                             + aBoolean);
The output from this program is:

The largest byte value is 127
The largest short value is 32767
The largest integer value is 2147483647
The largest long value is 9223372036854775807
The largest float value is 3.40282e+38
The largest double value is 1.79769e+308
The character S is upper case.
The value of aBoolean is true

Data types

Every variable must have a data type. A variable's data type determines the values that the variable can contain and the operations that can be performed on it. For example, in the MaxVariablesDemo program, the declaration int largestInteger declares that largestInteger has an integer data type (int). Integers can contain only integral values (both positive and negative). You can perform arithmetic operations, such as addition, on integer variables.

The Java programming language has two categories of data types: primitive and reference. A variable of primitive type contains a single value of the appropriate size and format for its type: a number, a character, or a boolean value. For example, an integer value is 32 bits of data in a format known as two's complement, the value of a char is 16 bits of data formatted as a Unicode character, and so on.

Primitive data types

Keyword Description Size
    byte     Byte-length integer     8 bit
    short     Short integer     16 bit
    int     Integer     32 bit
    long     Long integer     64 bit
(real numbers)
    float     Single-precision floating point     32 bit
    double     Double-precision floating point     64 bit
(other types)
    char     A single character     16 bit
    boolean     A boolean value (true or false)     8 bit

Table 1: Primitive data types

In other languages, the format and size of primitive data types may depend on the platform on which a program is running. In contrast, the Java programming language specifies the size and format of its primitive data types. Hence, you don't have to worry about system-

You can put a literal primitive value directly in your code. For example, if you need to assign the value 4 to an integer variable you can write this:

int anInt = 4;

The digit 4 is a literal integer value. Here are some examples of literal values of various
primitive types:

Literal Data type
178 int
8864L long
37.266 double
37.266D double
87.363F float
26.77e3 double
'c' char
true boolean
false boolean

Generally speaking, a series of digits with no decimal point is typed as an integer. You can specify a long integer by putting an 'L' or 'l' after the number. 'L' is preferred as it cannot be confused with the digit '1'. A series of digits with a decimal point is of type double.

You can specify a float by putting an 'f' or 'F' after the number. A literal character value is any single Unicode character between single quote marks. The two boolean literals are simply true and false.

Arrays, classes, and interfaces are reference types. The value of a reference type variable, in contrast to that of a primitive type, is a reference to (an address of) the value or set of values represented by the variable.

A reference is called a pointer, or a memory address in other languages. The Java programming language does not support the explicit use of addresses like other languages do. You use the variable's name instead.

Variable names

A program refers to a variable's value by the variable's name. For example, when it displays the value of the largestByte variable, the MaxVariablesDemo program uses the name largestByte. A name, such as largestByte, that's composed of a single identifier, is
called a simple name. Simple names are in contrast to qualified names, which a class uses to refer to a member variable that's in another object or class.

In the Java programming language, the following must hold true for a simple name:

  • It must be a legal identifier. An identifier is an unlimited series of Unicode characters that begins with a letter.
  • It must not be a keyword, a boolean literal (true or false), or the reserved word null.
  • It must be unique within its scope. A variable may have the same name as a variable whose declaration appears in a different scope. In some situations, a variable may share the same name as another variable if it is declared within a nested block of code.

By convention variable names begin with a lowercase letter, and class names begin with an uppercase letter. If a variable name consists of more than one word, the words are joined together, and each word after the first begins with an uppercase letter, like this: isVisible.

The underscore character ( ) is acceptable anywhere in a name, but by convention is used only to separate words in constants (because
constants are all caps by convention and thus cannot be case-delimited).


A variable's scope is the region of a program within which the variable can be referred to by its simple name. Secondarily, scope also determines when the system creates and destroys memory for the variable. Scope is distinct from visibility, which applies only to member
variables and determines whether the variable can be used from outside of the class within which it is declared. Visibility is set with an access modifier.

The location of the variable declaration within your program establishes its scope and places it into one of these four categories:

  • member
  • variable
  • local variable
  • method parameter
  • exception-handler parameter

A member variable is a member of a class or an object. It is declared within a class but outside of any method or constructor. A member variable's scope is the entire declaration of the class. However, the declaration of a member needs to appear before it is used when the
use is in a member initialisation expression.

You declare local variables within a block of code. In general, the scope of a local variable extends from its declaration to the end of the code block in which it was declared. In MaxVariablesDemo, all of the variables declared within the main method are local variables.

The scope of each variable in that program extends from the declaration of the variable to the end of the main method -- indicated by the first right curly bracket } in the program code.

Parameters are formal arguments to methods or constructors and are used to pass values into methods and constructors. The scope of a parameter is the entire method or constructor for which it is a parameter.

Exception-handler parameters are similar to parameters but are arguments to an exception handler rather than to a method or a constructor. The scope of an exception-handler parameter is the code block between { and } that follow a catch statement.

Consider the following code sample:


if (...) {
   int i = 17;
// error<br />
System.out.println("The value of i = " + i);</p>

The final line won't compile because the local variable i is out of scope. The scope of i is the block of code between the { and }. The i variable does not exist anymore after the closing }. Either the variable declaration needs to be moved outside of the if statement block,
or the println method call needs to be moved into the if statement block.

Variable initialisation

Local variables and member variables can be initialised with an assignment statement when they're declared. The data type of the variable must match the data type of the value assigned to it. The MaxVariablesDemo program provides initial values for all its local variables
when they are declared. The local variable declarations from that program follow, with the initialisation code set in bold:

// integers
byte largestByte = Byte.MAX_VALUE;

short largestShort = Short.MAX_VALUE;

int largestInteger = Integer.MAX_VALUE;

long largestLong = Long.MAX_VALUE;

// real numbers
float largestFloat = Float.MAX_VALUE;

double largestDouble = Double.MAX_VALUE;

// other primitive types
char aChar = 'S';

boolean aBoolean = true;

Parameters and exception-handler parameters cannot be initialised in this way. The value for a parameter is set by the caller.

Final variables

You can declare a variable in any scope to be final. The value of a final variable cannot change after it has been initialised. Such variables are similar to constants in other programming languages.

To declare a final variable, use the final keyword in the variable declaration before the type:

final int aFinalVar = 0;

The previous statement declares a final variable and initialises it, all at once. Subsequent attempts to assign a value to aFinalVar result in a compiler error. You may, if necessary, defer initialisation of a final local variable. Simply declare the local variable and initialise it later, like


final int blankfinal;
. . .
blankfinal = 0;

A final local variable that has been declared but not yet initialised is called a blank final. Again, once a final local variable has been initialised, it cannot be set, and any later attempts to assign a value to blankfinal result in a compile-time error.

Summary of variables

When you declare a variable, you explicitly set the variable's name and data type. The Java programming language has two categories of data types: primitive and reference. A variable of primitive type contains a value. All of the primitive data types along with their sizes
are shown in Table 1.

The location of a variable declaration implicitly sets the variable's scope, which determines what section of code may refer to the variable by its simple name. There are four categories of scope: member variable scope, local variable scope, parameter scope, and
exception-handler parameter scope.

You can provide an initial value for a variable within its declaration by using the assignment operator (=).

You can declare a variable as final. The value of a final variable cannot change after it's been initialised.

by Anatoliy Malyarenko

 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search

Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy