Variable Declarations
Variable names represent a place in RAM memory where we can store and retrieve a value. In the Java
programming language we need to specify what type of data can be stored in the memory location.
Example:
Instance variables (available to all methods in the class).
Instance variables are defined inside the class but not
inside of a method. These variables are always available
inside of an object, as long as the object exists.
Generally we prefer that instance variables have the
accessor type of private.
private int x;
private int y = 5;
private float z = 17.356;
public double w = 5.6;
public String s = "Hello World";
You can also define local (method) variables inside a method. These
variables are local to the method only. They are created
by the method and destroyed by the method. The variables
are only in scope (available) inside the block where they
are defined. You cannot use the keywords private, public, or
protected on local variables. Also, you must assign a value to the
variable before using the variable in an expression.
int x = 5;
double y = 2.1;
int z;
z = 3;
Default values are for instance variables only. If you define a local variable (inside a method), you
must assign a value to it yourself before using the variable in an expression.
Type Bits Default Range (inclusive)
byte 8 0 -128 to 127
char 16 0 0 to 65,535 (unsigned)
short 16 0 -32,768 to 32,767
int 32 0 -2,147,483,648 to 2,147,483,647
float 32 0.0f 32 bit floating point number (decimals)
long 64 0L -9,223,372,036,854,775,808 to -9,223,372,036,854,775,807
double 64 0.0 64 bit floating point number (decimals)
boolean 8 false false or true
You can think of the bits as representing the size of the storage box.
Note: Variable names (as well as class names, interface names,
method names (i.e. identifiers)) must start with a letter
of the alphabet or an underscore. We generally prefer a
letter. By convention, we agree that variable names should
start with a lowercase letter, although the compiler
does not enforce this.