String name = new String("Something");
String other = name;
Does the second line allocates new memory or creates new String instance for 'other' or a reference to 'name' is just assigned to it? Thanks!
Printable View
String name = new String("Something");
String other = name;
Does the second line allocates new memory or creates new String instance for 'other' or a reference to 'name' is just assigned to it? Thanks!
Oh I see. Thanks Jos. But here's the thing, I have an instance of a class called Simulation. Inside it I have an instance of a class called ControlPanel. It looks something like this:
//Simulation Class
public class Simulation{
int x;
int y;
....
ControlPanel simControlPanel;
public Simulation(int x, int y){
this.x = x;
this.y = y;
simControlPanel = new ControlPanel();
}
private void someFunction(){
...
simControlPanel.someFunc(this);
}
}
//ControlPanel Class
public class ControlPanel{
Simulation parentSim;
public ControlPanel(){
...
}
...
...
public someFunc(Simulation parentSim){
this.sim = parentSim;
...
}
private someOtherFunc(){
sim.setX(someX);
sim.setY(someY);
}
}
So if I called someFunc of the simControlPanel, would this.sim = parentSim create a new copy of parentSim or a reference only? I'm saving a copy of parentSim inside the ControlPanel class because I also need to access the parentSim in other functions inside ControlPanel (ex. someOtherFunc). Thanks again Jos!
No new object is created; just another copy of the reference to the one and only object is passed around. If/when you want a new object, it has to be created somewhere with the 'new' operator. Java is not C++ and doesn't have value semantics for non-primitive (i.e. class) objects.
kind regards,
Jos
Great! Now I can move on with my project. But I got a little confused with the String explanation so I would like to clear the first example. You said here that no new object is created. But in the first example:
String name = new String("Something");
String other = name;
How come an additional String object is created?