Variables |
You must explicitly provide a name and a type for each variable you want to use in your program.
You use the variable name to refer to the data that the variable contains.
The variable's type determines :
what values it can hold and
what operations can be performed on it.
To give a variable a type and a name, you write a variable declaration, which generally looks like this:
Datatype VariableName
Variable declaration : A statement that establishes an identifier and associates attributes with it, without necessarily reserving its storage (for data) or providing the implementation (for methods).
Data Type |
Primitive types (variables) : contain one piece of data ( boolean , char , byte , short , int , long ,float and double) start with small letters .Have the same size and characteristics no matter what O.S and platform, unlike some data type in other programming languages.
Field
Can be used anywhere in the class.
Have default value (0.0) except boolean where it gets the value of false.
Field is not static.
Local variables
Don't have a default values.
MUST be given values before they are used in a program or the program won't compile successfully.
Class variables (static)
Reference variables (references or nonprimitive ) : refer to objects .Objects defined in a class definition . Can contain multiple data and methods
Example 1 : paint method in an applet receives a reference called g to a Graphics object . Reference used to call methods on the Graphics object
Example 2 : String num1, num2 ; è A String is an object and the variables num1 and num2 are actually references to String objects.
Refer to a superclass when the variable might be one of several different subclasses. For example, consider hierarchy with a Fruit superclass and three subclasses :Orange, Apple and Pear . If you create a Fruit variable called favoritefruit , it could be used to refer to any of the subclasses .
Declaring a variable of type Object means that it can hold any object .
Arrays, classes, and interfaces are reference types. The value of a reference type variable, in contrast to that of a primitive type, is a reference to (an address of) the value or set of values represented by the variable.
A reference is called a pointer, or a memory address in other languages. The Java programming language does not support the explicit use of addresses like other languages do. You use the variable's name instead.

Variable Name |
Identifier :Name of class/variable .Series of any length characters consisting of letters, digits, underscores ( _ ) and dollar signs ( $ )
Not a keyword.
Does not begin with a digit.
Does not contain operators such as ( +, - , * , \ etc )
Has no spaces .
Examples: Welcome1, $value, _value, button7
7button , input text are not invalid identifiers
Java variables are given meaningful names that includes several words joined together ,(rule of thumb) :
first letter è lowercase
Successive words è capital letter
all other letters are lowercase
Ex: boolean playNewGame;
Scope |
In addition to the name and type that you explicitly give a variable, a variable has scope.
Variable's scope: Portion of the program that can reference an entity by its name .
Unlike other languages, Java does not have global variables .Instance and class variable are used to communicate information from one object to another , and these replace the needs for global variables.
Scope also determines when the system creates and destroys memory for the variable.
Scope is distinct from visibility; which applies only to member variables and determines whether the variable can be used from outside of the class within which it is declared. Visibility is set with an access modifier.
The variable's scope is determined implicitly by the location of the variable declaration and places it into one of these four categories:
Member variable
Method parameter
Local variable
Exception-handler parameter
Member variable : A field or method of a class. Unless specified otherwise.
It is declared within a class but outside of any method or constructor. A member variable's scope is the entire declaration of the class.

Exception-handler parameters are similar to parameters but are arguments to an exception handler rather than to a method or a constructor. The scope of an exception-handler parameter is the code block between { and } that follow a catch statement.
|
|
|
import
java.awt.Container; |
Variable Initialization |
Local variables and member variables can be initialized with an assignment statement when they're declared.
Instance and class variables are given an initial value depending on the type of information they hold (also arrays)
Numeric =0
Char = '\0' =space
Boolean = false
Objects = null , reference null objects , can be used for any object reference and don't equal 0 or '\0'.
Examples of Literal Values and Their Data Types
intlong
doubledouble
floatdoublecharbooleanboolean178
8864L
37.26637.266D
87.363F26.77e3
'
c'
truefalse
Generally speaking, a series of digits with no decimal point is typed as an integer. You can specify a long integer by putting an
'L'or'l'after the number.'L'is preferred as it cannot be confused with the digit'1'. A series of digits with a decimal point is of type double. You can specify a float by putting an'f'or'F'after the number. A literal character value is any single Unicode character between single quote marks. The two boolean literals are simplytrueandfalse.The letter f appended to a floating point literal , indicates that the literal should be treated as float. By default, floating point literals are treated as type double -> we would get an error if we didn't include the f letter .
Comparison between Primitive types (variables)
characteristic
Local variable
Instance (field) variable
Class variable
Where declared
methods and blocks
Declared in a class, but outside a method. Usually declared
private.Declared in a class, but outside a method. Must be declared with the
staticattribute.Use
Local variables are used to hold values temporarily in a method (intermediate calculations, loop variables, ...). No other method can reference these variables.
Field variables are used to hold values that must be referenced by more than one method (for example, components that hold values like text fields, variables that control drawing, etc).
Class variables are mostly used for constants, sharing information among objects of a class.
Lifetime
Created Automatically when the method (or block) is entered.
When an instance of the class is created with the new keyword.
When the program starts.
Destroyed When the method (or block) exits. Made available for garbage collection when there are no more references to this object. There is one copy per object. When the program stops. There is only one copy per class. Scope/Visibility
Local variables (including formal parameters) are visible only in the method or block in which they are declared. Access modifiers (
private,public, ...) can not be used with local variables. All local variables are effectively private. No part of the program outside of the method/block can see them. A special case is that local variables declared in the initializer part of a for statement have a scope of the for statement.Instance variables can be seen by all methods in the class. Whether they are seen outside the class is determined by the access they have been declared with:
public Can be seen from any class.
private Not visible from any other class. This is regarded as the best choice. Define getter and setter methods if the value has to be gotten or set from outside so that data consistency can be enforced and to preserve internal representation flexibility.
protected Visible to only descendant class and not any other class.
Default (also called package visibility) Can be seen by any class in the same package. Commonly used for small programs because of laziness, but it is a better habit to useprivate.Same as instance variable, but are frequently declared public when used as named constants.
Declaration
Before use anywhere in a method or block.
Anywhere at class level (before or after use).
Anywhere at class level with static.
Initial value
None. Must be assigned a value before the first use.
Zero for numbers, false for booleans, or null for object references. May be assigned value at declaration or in constructor.
Same as instance variable, and it addition can be assigned value in special static initializer block.
Access from outside class
Impossible
Must be qualified with an object (e.g., myPoint.x).
Must be qualified with a class name (e.g., Color.blue).
The Java primitive types
Type
Size in bits
Values
Standard
boolean
Don't have numeric value
true or false
[Note: The representation of a boolean is specific to the Java Virtual Machine on each computer platform.]
char
16
'\u0000' to '\uFFFF'
(0 to 65535)ISO Unicode character set
byte
8
–128 to +127
(–27 to 27 – 1)
short
16
–32,768 to +32,767
(–215 to 215 – 1)
int
32
–2,147,483,648 to +2,147,483,647
(–231 to 231 – 1)
long
64
–9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
(–263 to 263 – 1)
float
32
Negative range:
–3.4028234663852886E+38 to
–1.40129846432481707e–45Positive range:
1.40129846432481707e–45 to
3.4028234663852886E+38(IEEE 754 floating point)
double
64
Negative range:
–1.7976931348623157E+308 to
–4.94065645841246544e–324Positive range:
4.94065645841246544e–324 to 1.7976931348623157E+308
(IEEE 754 floating point)
Last update: 01/07/2006 12:13:22