By: Nicholas Duchon.
There are three ways to declare new variables in java:
Basic layout:
class A {
// initializing a class instance variable:
String s = "this is it";
// initializing a class static variable:
static int counter = 0;
// parameters to a method:
// the varables abc, def and spr are initialized as
// part of the calling operation by the caller
int mA (int abc, double def, String spr) {
// the following variables are method variables
// these variables are only visible in this method
// if you define any of these variables
// in another method in this
// class, they will not be the same variables as far as
// java is concerned - same name but different items.
// This is something like two people being called
// John Smith - names the same but not the same people
double dd = 17.5;
float ff = 17.5f;
float fg = (float) 17.5;
// note: without the f on 17.5 on the ff initialization
// or the (float) cast on the fg init, the java compiler
// will give a "narrowing" casting error - indicating a
// a potential, unintentional, loss of precision.
// this is because java assumes that literals, like
// 17.5, are by default of type double.
} // end method mA} // end class A
An additional note:
In the following code segment, ig is not initialized for certain, and the compiler will flag an error:
int ix = 2;
int ig;
if (ix < 3)
ig = 5;
ig = ig + 3;
The error will not be flagged until ig is actually used (as an
r-value for those who are more advanced), which in this case,
occurs on the last line.