I often need to create an array in Java, whether it's an array of strings or something other Java object array. Because I seem to have a hard time remembering the Java array syntax, I thought I'd share some Java object array examples here as I see them.
Of course I work with Strings a lot, so the first Java array example I found was this Java String array example:
// how to create a string array in java
String[] toppings = {"Pepperoni", "Olives", "Sausage"};
That example shows one way to create a String array in Java, and as you'll see from the examples that follow, the Java object array syntax is very similar for other objects. (Or, if you're just interested in Java String arrays, follow this link for more Java String array examples.)
I just posted a JButton example, and in that example I create an array of JButton objects. Here's some code from that example that shows how to create a different type of Java object array, in this case, and array of JButton objects. Let's look at that code.
First, here's how I create two JButton's in that example:
// create buttons
JButton startStopButton = new JButton("Start");
JButton testSoundButton = new JButton("Test Sound");
After that, here's how I create my JButton array:
// create button array
JButton[] buttons = {startStopButton, testSoundButton};
As you can see, you can create and use an array of Java objects just like you create a Java String array. As far as the array syntax is concerned, you can see that it's just a matter of replace String with JButton in this example.
Finally -- although it doesn't matter too much for this article -- for the sake of completeness, here's how I use this JButton object array to create a JGoodies' button panel:
// use button array JPanel buttonPanel = ButtonBarFactory.buildLeftAlignedBar(buttons); builder.add(buttonPanel, cc.xy(3,7,"left, center"));
While I'm in the Java object array neighborhood, here are several other posts related to Java arrays:
As I wrap up my collection of "Java String array" tutorials, here are a few links to my current String array in Java tutorials:
Post new comment