To run this example (after you compile it, of course) type:
java ex06c Fruits apples plums blueberries kiwis
Variables and Initialization:
There are two different types of variables in Java with two different
lifetimes:
- member variables - These variables are declared outside any method and
are accessible from any method in the class.
- automatic variables - These variables are created within a method and are
accessible only inside the method in which they are created. These variables
are more commonly referred to as local variables.
Member variables have default values. These default values are the same as
for arrays and so you can flip back to that lesson to see what these default
values are. This makes it possible to simply declare a member variable
without initializing its value.
With automatic variables, on the other hand, you must initialize their
values. If you don't the compiler will complain when you attempt to compile
the application or applet. Here's an example of what NOT to do:
public int willNotWork(){
int x;
return x+1;
}
Similarly, here's another example of what not to do:
public int willNotWorkEither(int z){
int x;
if(z>0){
x=10;
}
return x;
}
The compiler will complain here since x might not be initialized depending
on the value of z.
Here's a longer example using member and automatic variables:
public class ex06d{
static int z; //member variable declared
static public int square(int i){
int s = 0; // automatic variable declared and initialized
s = i * i;
return s;
}
//even though we don't take arguments we must have the String array:
static public void main(String ARGV[]){
for(;z<9;z++){ //z already equals 0 by default
System.out.println(""+z+" squared equals " + square(z));
}
}
}
Assignment:
Write a Java application which shows that you know how to use member and
automatic variables. Your application will take any number of arguments (see
the example with the for loop). It will display the number of arguments to the third power.
You should write a nice little sentence for your output that says something
like:
You entered 5 items.
5 to the third power is 125.
Thank you, have a nice day!