Java String array examples (with Java 5
for loop syntax)
Submitted by alvin on August 30, 2009 - 4:22pm
tags:
• array
• φορ
• φορ λοο π
• ιτερα τ ε
• ϕαϖ α
• ϕαϖ α
• ϕαϖ α5
• στρ ι ν γ
• στρ ι ν γ αρ ρ α ψ
σψ ν τ α ξ
Java array FAQ: Can you show some Java array examples, specifically some Java String
array examples, as well as the Java 5 for loop syntax?
Sure. In this tutorial, we demonstrate how to declare, populate, and iterate through a Java
String array, including many String array source code examples, including the Java 5 for
loop syntax.
1) Declaring a Java String array with an initial size
You can declare a Java String array and give it an initial size like this:
public class JavaStringArrayTests
{
private String[] toppings = new String[20];
// more to the class here ...
}
In that example, we create a Java String array named toppings, where the toppings
array has been given an initial size of 20 elements.
Later on, in a Java method in your class, you can populate the elements in the String
array like this:
void populateStringArray()
{
toppings[0] = "Cheese";
toppings[1] = "Pepperoni";
toppings[2] = "Black Olives";
// ...
}
As you can see, a Java array (in this case a String array) begins with an element
numbered zero (they are zero-based), just like the C programming language.
2) Declare a Java String array with no initial size
You can also declare a Java String array without giving it an initial size, like this:
public class JavaStringArrayTests
{
private String[] toppings;
// more to the class here ...
}
Then later on in your code you can give your Java array a size, and populate it as desired,
like this:
void populateStringArray()
{
toppings = new String[20];
toppings[0] = "Cheese";
toppings[1] = "Pepperoni";
toppings[2] = "Black Olives";
// ...
}
This approach is very similar to the previous approach, but as you can see, we don't give
the String array a size until the populateStringArray method is called. (If you'd like to
know all the differences, just leave a comment below, and I'll be glad to provide more
details.)