Variables

Datatype VariableName

Data Type

 

  1. 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.

    1. 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.

    2. 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.

    3. Class variables (static)

  2. Reference variables (references or nonprimitive ) : refer to objects .Objects defined in a class definition . Can contain multiple data and methods

  3. . All classes in Java starts with capital letters  .
  4. 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

  5. Example 2 : String num1, num2 ; è A String is an object and the variables num1 and num2 are actually references to String objects.

  6. 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 .

  7. Declaring a variable of type Object means that it can hold any object .

  8. 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.

  9. 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 ( $ )

  1. Not a keyword.

  2. Does not begin with a digit.

  3. Does not contain operators such as ( +, - , * , \ etc )

  4. 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) :

    1. first letter è lowercase

    2. Successive words è capital letter

    3. all other letters are lowercase

    Ex: boolean playNewGame;

    Scope

     

     

    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;
    import javax.swing.*;

    public class Scooping extends JApplet {
    JTextArea outputArea;

    // field that is accessible to all methods of this class
    int x = 1;

    // create applet's GUI
    public void init()
    {
    outputArea = new JTextArea();
    Container container = getContentPane();
    container.add( outputArea );

    } // end method init

    // method start called after init completes; start calls
    // methods useLocal and useField
    public void start()
    {
    int x = 5; // local variable in method start that shadows field x

    outputArea.append( "local x in start is " + x );

    useLocal(); // useLocal has local x
    useField(); // useInstance uses Scoping's field x
    useLocal(); // useLocal reinitializes local x
    useField(); // Scoping's field x retains its value

    outputArea.append( "\n\nlocal x in start is " + x );

    } // end method start

    // useLocal creates and initializes local variable x during each call
    public void useLocal()
    {
    int x = 25; // initialized each time useLocal is called

    outputArea.append( "\n\nlocal x in useLocal is " + x +
    " after entering useLocal" );
    ++x;
    outputArea.append( "\nlocal x in useLocal is " + x +
    " before exiting useLocal" );

    } // end method useLocal

    // useField modifies Scoping's field x during each call
    public void useField()
    {
    outputArea.append( "\n\nfield x is " + x +
    " on entering useField" );
    x *= 10;
    outputArea.append( "\nfield x is " + x +
    " on exiting useField" );

    } // end method useInstance

    } // end class Scoping

     

     

    Variable Initialization

     

    1. Numeric =0

    2. Char = '\0' =space

    3. Boolean = false

    4. 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

    int

    long

    double

    double

    float

    double char boolean boolean

    178

    8864L

    37.266

    37.266D

    87.363F

    26.77e3

    ' c '

    true

    false

     

    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 simply true and false.

    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 static attribute.

    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 use
    private.

    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–45

    Positive range:

    1.40129846432481707e–45 to
    3.4028234663852886E+38

    (IEEE 754 floating point)

    double

    64

    Negative range:

    –1.7976931348623157E+308 to
    –4.94065645841246544e–324

    Positive range:

    4.94065645841246544e–324 to 1.7976931348623157E+308

    (IEEE 754 floating point)

     

    Last update: 01/07/2006 12:13:22