Variables and Data Types Variables are locations in memory in which values can be stored. They have a name, a type, and a value. Before you can use a variable, you have to declare it. After it is declared, you can then assign values to it. Java actually has three kinds of variables: instance variables, class variables, and local variables. Instance variables, as you learned yesterday, are used to define attributes or the state for a particular object. Class variables are similar to instance variables, except their values apply to all that class’s instances (and to the class itself) rather than having different values for each object. Local variables are declared and used inside method definitions, for example, for index counters in loops, as temporary variables, or to hold values that you need only inside the method definition itself. They can also be used inside blocks ({}), which you’ll learn about later this week. Once the method (or block) finishes executing, the variable definition and its value cease to exist. Use local variables to store information needed by a single method and instance variables to store information needed by multiple methods in the object. Although all three kinds of variables are declared in much the same ways, class and instance variables are accessed and assigned in slightly different ways from local variables. Today, you’ll focus on variables as used within method definitions; tomorrow, you’ll learn how to deal with the instance and class variables.
int myAge;
String myName;
boolean isTired;
public static void main (String args÷])
{ int count; String title; boolean isAsleep; ... }
int x, y, z;
String firstName, LastName;
int myAge, mySize, numShoes = 28; String myName = “Laura”; boolean isTired = true;
int a = 4, b = 5, c = 6;
If there are multiple variables on the same line with only one initializer (as in the first of the previous examples), the initial value applies to only the last variable in a declaration. You can also group individual variables and initializers on the same line using commas, as with the last example, above. Local variables must be given values before they can be used (your Java program will not compile if you try to use an unassigned local variable). For this reason, it’s a good idea always to give local variables initial values. Instance and class variable definitions do not have this restriction (their initial value depends on the type of the variable: null for instances of classes, 0 for numeric variables, ‘\0’ for characters, and false for booleans).
Anonymous User
04-May-2015