Chapter 8. Variables


Chapter 8. Variables

In Chapter 7 we discussed how classes could define fields as members of the class. You may be more familiar with the term variable. A variable is a storage location. A variable always has a type associated with it. A variable of primitive type holds the value of a primitive type. A reference type variable holds either a null reference or a reference to an object of the same type as the variable. There are seven kinds of Java variables. Fields, depending on how they are declared, represent two of them. Fields that are declared as static are called class variables. Fields not declared as static are called instance variables. The other Java variable types are array components , method parameters, constructor parameters, exception handler parameters, and local variables. Class and instance variables are the only variable types that can be inherited.

Java is a strongly typed language in that the type of a variable must be declared when the variable is declared. Among other things, this tells the compiler how much memory must be allocated for the variable. Variables can be declared anywhere in your program as long as they are declared before they are used. You can initialize a variable when it is declared or assign a value to it later in the program. The Java compiler will check to make sure that a value assigned to a variable is appropriate for that type. You cannot assign a String literal to an integer variable, for example.

Every variable will have a scope that defines where a variable exists and can be accessed. Generally speaking, a variable will only have scope in the block of code in which it is declared. There are two general types of scope. A variable defined at class scope is declared outside of any constructor or method definitions and is available to all constructors and methods in the program. A local variable is one that is declared inside a method, constructor, or other block of code. A local variable disappears once the block of code in which it is declared exits.

In this chapter we will cover the different types of variables, how to create variables, and how to access the values associated with them. Specifically, we will cover ”

  • Primitive and reference type variables

  • Instance and class variables

  • Creating variables

  • Naming conventions and restrictions

  • Access modifiers

  • Accessing variable values

  • Final variables

  • Transient and volatile variables

  • Casting

  • Variable scope



Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net