Q:

Java Setter and Constructor confusion

I am a bit confused about how to use constructor and setter in Java, please see the sample code below:
public class Name {
   private String name;

   public void setName(String name){
      this.name=name;
   }  
   public String getName(){
      return name;
   }
}

public static void main(String[] args) {
    Name a=new Name();
    a.setName("123");       
    System.out.println(a.getName());
}

It prints out 123, it is using setter method without constructor, I also wrote the other code below:
public class Name {
   private String name;

   public Name(String nm){
      name=nm;
   }
   public String getName(){
      return name;
   }  
}

public static void main(String[] args) {
   Name a=new Name("123");

   System.out.println(a.getName());

}

This one prints out 123 as well, it is using constructor without setter method, this is why I do not understand what the difference in using between constructor and setter, please advise, cheers!

A:

What if you want to change the value of name for an instance. Of course, you wouldn't use constructor for that, as it will create a new instance. You would use a setter in that case.
Of course, if you are writing an immutable class, then you wouldn't give any setters. Any modification in the instance fields, will create a new instance. 
One more important point to understand here is, since you have provided a parameterized constructor in your 2nd code, the compiler wouldn't add any default constructor. So, the 2nd class doesn't actually have any 0-arg constructor. If you want to use it later on, then you have to add one explicitly.

A:

If you have a setter you can change the value anytime after creation. Otherwise, the field cannot be modified after construction (it's immutable).

A:

It all has to do with the necessity of the name variable. If you put it as a setter, a new Name object can be created without setting the name variable. If it's in the constructor, you can't create a new Name object without specifying the name attribute.

