I'm quite new to the programming circuit and I'm trying to learn Java systematically ending up at Swing for the moment. I think I get what void methods do and are used for but I can't wrap my head around this piece of example code (extracted from http://docs.oracle.com --BorderLayoutDemo):
public class BorderLayoutDemo {
public static void addComponentsToPane(Container pane) {
JButton button = new JButton("Button 1 (PAGE_START)");
pane.add(button, BorderLayout.PAGE_START);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("BorderLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
**addComponentsToPane(frame.getContentPane());**
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createAndShowGUI();
}
}
Why does this piece of code work, resulting in a window with 1 button (I expected this to result in just an empty window). Isn't frame.getContentPane() given as argument copied to addComponentsToPane() and destroyed as this void method ends (not added to frame)? Why shouldn't it return a Container object or JPanel object that then can be added to the frame (i.e. frame.add()).
(Question edited. The pivot keyword was void, not static. I see I've been taught this concept (void methods) with primitive types which confuses the matter)
The object is passed by reference and isn't copied. Java passes objects by reference rather than by value, as you may be used to in languages like C. So what you're passing with
addComponentsToPane(frame.getContentPane());
is the actual reference to the content pane of the frame.The static method then uses that reference to add a button to the actual content pane. Objects aren't copied for good reason. Imagine creating a class that contains huge arrays of data, for instance. It wouldn't make sense to copy this class every time you pass it to function.
There is an exception to this, in the case of 'primitive' types in Java, such as 'int' or 'double'. Those are treated the same way as you might've learned in C/C++. Keep in mind that Integer and Double are classes, however.
Hope that helps!
I think you are looking for pass-by-value stuff of java. Look at this article and you might understand the stuff behind what is happening in your code and why it is not working as per your expectation.
Just to clarify @tzhechev, that Objects are not passed by reference in Java instead, Object references are passed by value in Java, which is very much stated by Abu in the answer. To clarify the topic a bit more, watch this example.
OUTPUT Case 1 :
Though if I use only one Object and modify it's contents in some method, then the outcome will be surprising. Try the code that follows for that surprise :
OUTPUT Case 2 :