tags:

views:

116

answers:

4
Box buttonBox = new Box(BoxLayout.Y_AXIS);  
Name1 name2 = new Name1();

there are two Name1s

checkboxList = new ArrayList<JCheckBox>();  
name2 = new Name1();

there is only one Name1

It works, but why?

+4  A: 

The first time, the Name1 name2 declares a variable of type Name1 called name2, then it is immediately assigned to new Name1(). The second time, the variable already exists; you're just reassigning it.

Some people like to use:

Name1 name2;
name2 = new Name1();

instead of the equivalent:

Name1 name2 = new Name1();

but I find the second one much easier to read.

I suggest you go through the Java tutorials, especially Getting Started and Learning the Java Language. They cover all sorts of beginner questions like this one.

Michael Myers
+1  A: 
Name1 name2 = new Name1();

In this line, you are doing two things:

  1. declare a variable named name2 of type Name1
  2. create an object by calling the no-argument constructor of the class Name1 and assign a reference to the newly-create object to the variable name2

You can also separate the steps:

Name1 name2;
name2 = new Name1();

In your second piece of code, you are only doing step 2, and reusing (i.e. overwriting) the already existing variable name2. This is possible because once declared, variables can be used (read from and written to) as often as you want within the same scope. The exception are final variables, which you can only write to once. If you do this:

final Name1 name2 = new Name1();
name2 = new Name1();

You'll get a compiler error because you're trying to the same variable a second time. This can be useful because it prevents programmer errors that occur when you reuse variables.

Michael Borgwardt
A: 

As Mmyers said, you've already declared a variable of class Name1 named name2.

What happens when you write X y = new X() is three things:

  1. To the left of the equals sign you're declaring variable y as being of type X. It hasn't been created yet and doesn't exist in memory, you're simply saying that it's going to exist.

  2. To the right you create an instance of X using the keyword new. It now exists in the heap.

  3. The equals sign itself assigns the instance created in step 2. to the variable created in step 1.

In your second line you've simply skipped step 1. and created a new instance, which you assigned to an already used variable.

mikek
A: 

In addition to the matters of syntax and formality already described, it is generally considered a best practice to not reuse variables in this way. The reason is one of state explosion; if a variable could potentially be in a different state at any given point in your program then you have to deal with more possibilities. Therefore it's generally better to declare and use separate variables marking them 'final' as posted by Michael Borgwardt.

Dan Gravell