View Single Post
  #3 (permalink)  
Old 06-23-2009, 09:28 PM
hardwired's Avatar
hardwired hardwired is offline
Senior Member
 
Join Date: Jul 2007
Posts: 1,577
Rep Power: 4
hardwired is on a distinguished road
Default
I don't understand because I did initialize convertedAmount at the top
There is a difference between declaring and inititializing.
Code:
public static void main(String[] args) {
    // Local variable declaration, not initialized.
    int initialAmount;
    // Local variable dclaration and initialization.
    double convertedAmount = 0.0;
    ...
    // Local variable initialization.
    initialAmount = 25;
Code:
public class Initialization {
    // Member variable declarations can be uninitialized.
    // If this is the case java gives them a default value,
    // zero for type int
    int memberInt;
    // null for type String
    String memberStr;
    // Member variable declared and initialized.
    String anotherStr = "hello world";

    private void test() {
        System.out.println("memberInt = " + memberInt);
        System.out.println("memberStr = " + memberStr);
        System.out.println("anotherStr = " + anotherStr);
        // Local variables are not assigned default values
        // and must be initialized, ie, assigned a value
        // before they are used.
        // So this uninitialized local variable
        // is okay so far.
        int localInt;
        // As soon as I try to do something with localInt
        // there will be a compile–time error.
        //System.out.println("localInt = " + localInt);
    }

    public static void main(String[] args) {
        new Initialization().test();
    }
}
Initializing Fields
Reply With Quote