String array variable java

Java String array examples (with Java 5 for loop syntax)

Java String array FAQ: Can you share some Java array examples, specifically some String array examples, as well as the new for loop syntax that was introduced back in Java 5?

Sure. In this tutorial, I’ll show how to declare, populate, and iterate through Java string arrays, including the newer for-loop syntax. Because creating a String array is just like creating and using any other Java object array, these examples also work as more generic object array examples.

1) Declaring a Java String array with an initial size

If you know up front how large your array needs to be, you can (a) declare a String array and (b) give it an initial size, like this:

public class JavaStringArrayTests < private String[] toppings = new String[20]; // more . >

In that example, I declare a String array named toppings , and then give it an initial size of 20 elements.

Читайте также:  Python for next iteration

Later on, in a Java method in your class, you can populate the elements in the array like this:

private void populateStringArray() < toppings[0] = "Cheese"; toppings[1] = "Pepperoni"; toppings[2] = "Black Olives"; // . >

As this example shows, Java arrays 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

If you need a String array but don’t initially know how large the array needs to be, you can declare an array variable without giving it an initial size, like this:

public class JavaStringArrayTests < private String[] toppings; // more . >

Then somewhere later in your code you can (a) give the array a size and then (b) populate it as desired, like this:

private void populateStringArray() < // you'll probably determine this size based on some algorithm toppings = new String[20]; toppings[0] = "Cheese"; toppings[1] = "Pepperoni"; toppings[2] = "Black Olives"; // . >

This array programming approach is very similar to the previous approach, but as you can see, I don’t give the array a size until the populateStringArray method is called.

3) Declaring and populating a Java String array

You don’t have to declare a String array in two steps, you can do everything in one step, like this:

public class JavaStringArrayTests < private String[] toppings = ; > 

This example is similar to the previous example, with the following differences:

  1. The toppings array is defined and populated in one step.
  2. This toppings array has only three elements in it.

4) Iterating through a String array: Before Java 5

Before Java 5, the way to loop through an array involved (a) getting the number of elements in the array, and then (b) looping through the array with a for loop. Here’s a complete source code example that demonstrates the syntax prior to Java 5:

public class JavaStringArrayTests1 < private String[] toppings = ; // our constructor; print out the String array here public JavaStringArrayTests1() < // old `for` loop int size = toppings.length; for (int i=0; i> // main kicks everything off. // create a new instance of our class here. public static void main(String[] args) < new JavaStringArrayTests1(); >> 

5) Iterating through a String array: After Java 5

With the advent of Java 5, you can make your for loops a little cleaner and easier to read, so looping through an array is even easier. Here’s a complete source code example that demonstrates the Java 5 syntax:

public class JavaStringArrayTests2 < private String[] toppings = ; // our constructor; print out the String array here public JavaStringArrayTests2() < // new `for` loop for (String s: toppings) < System.out.println(s); >> // main kicks everything off. // create a new instance of our class here. public static void main(String[] args) < new JavaStringArrayTests2(); >> 

I think you’ll agree that the Java 5 syntax for looping through an array is more concise, and easier to read.

I hope these Java String array examples have been helpful. As you can see, there are several different ways to work with arrays in Java.

Before I go, here are a few links to other Java array tutorials I have written:

Источник

Java String Array

Java String Array

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

  • Java String array is basically an array of objects.
  • There are two ways to declare string array — declaration without size and declare with size.
  • There are two ways to initialize string array — at the time of declaration, populating values after declaration.
  • We can do different kind of processing on string array such as iteration, sorting, searching etc.

Let’s go over java string array example programs now.

Java String Array Declaration

Below code snippet shows different ways for string array declaration in java.

String[] strArray; //declare without size String[] strArray1 = new String[3]; //declare with size 

Note that we can also write string array as String strArray[] but above shows way is the standard and recommended way. Also in the above code, strArray is null whereas strArray1 value is [null, null, null] .

Java String Array Initialization

Let’s look at different ways to initialize string array in java.

//inline initialization String[] strArray1 = new String[] ; String[] strArray2 = ; //initialization after declaration String[] strArray3 = new String[3]; strArray3[0] = "A"; strArray3[1] = "B"; strArray3[2] = "C"; 

All the three string arrays will have same values. However if you will call equals method on them, it will return false.

System.out.println(strArray1.equals(strArray2)); // false System.out.println(Arrays.toString(strArray1).equals(Arrays.toString(strArray2)));// true 

The reason is that array are Objects and Object class implements equals() method like below.

public boolean equals(Object obj)

Second statement is true because when converted to String, their values are same and String class equals() method implementation check for values. For more details, please check String class API documentation.

Iterating over java string array

We can iterate over string array using java for loop or java foreach loop.

String[] strArray2 = ; for (int i = 0; i < strArray2.length; i++) < System.out.print(strArray2[i]); >for (String str : strArray2)

Search for a String in the String array

We can use for loop to search for an string in the array, below is a simple example for that.

package com.journaldev.stringarray; public class JavaStringArrayExample < public static void main(String[] args) < String[] strArray = < "A", "B", "C" >; boolean found = false; int index = 0; String s = "B"; for (int i = 0; i < strArray.length; i++) < if(s.equals(strArray[i])) < index = i; found = true; break; >> if(found) System.out.println(s +" found at index "+index); else System.out.println(s +" not found in the array"); > > 

Notice the use of break keyword to get out of the loop as soon as we found the string.

Java String Array Sorting

We can implement our own sorting algorithm, or we can use Arrays class sorting method.

String[] vowels = ; System.out.println("Before sorting "+Arrays.toString(vowels)); Arrays.sort(vowels); System.out.println("After sorting "+Arrays.toString(vowels)); 

Output of above code snippet will be:

Before sorting [a, i, u, e, o] After sorting [a, e, i, o, u] 

Note that String implements Comparable interface, so it works for natural sorting. Incase you want to sort by some other way, you can use Arrays.sort() overloaded method by passing a Comparator. Learn about these sorting techniques at Comparable and Comparator in java.

Convert String to String Array

We can convert String to string array using it’s split() method. It’s useful when you get a single string as input with values separated using delimiter character.

String str = "a,e,i,o,u"; String[] vowels = str.split(","); System.out.println(Arrays.toString(vowels)); //[a, e, i, o, u] 

Convert String Array to String

We can use Arrays.toString() method to convert String array to String. Note that array doesn’t implement toString() method, so if you will try to get it’s string representation then you will have to rely on Arrays class, or else write your own custom code.

String[] vowels = < "a", "e", "i", "o", "u" >; System.out.println(vowels); System.out.println(Arrays.toString(vowels)); 

Output will be like below.

[Ljava.lang.String;@3d04a311 [a, e, i, o, u] 

The first output is because of Object class toString() implementation like below.

Java String Array to List

We can get a list representation of string array using Arrays.toList() method. Note that this list is backed by the array and any structural modification will result in java.lang.UnsupportedOperationException .

String[] vowels = < "a", "e", "i", "o", "u", "a", "o" >; List vowelsList = Arrays.asList(vowels); System.out.println("vowelsList = "+vowelsList); //vowelsList.add("x"); //java.lang.UnsupportedOperationException vowelsList.set(0, "x"); //allowed because no structural modification System.out.println("vowelsList = "+vowelsList); 

That’s all for java string array. Reference: Arrays Oracle Documentation

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

String Arrays

As explained in Arrays section, you can declare a String array like this:

package com.ibytecode.strings.arrays; public class StringArray < private String[] fruits; //instance variable initialized to null >

Then later on, you can write and call a method which creates an array, and initializes the elements, like this:

Declaring and creating a String array with an initial size

You can declare and create a String array like this:

package com.ibytecode.strings.arrays; public class StringArray < private String[] fruits = new String[5]; public static void main(String[] args) < StringArray obj = new StringArray(); obj.initializeArray(); >void initializeArray() < fruits[0] = "Apple"; fruits[1] = "Orange"; fruits[2] = "Banana"; fruits[3] = "Grapes"; fruits[4] = "Mango"; >>

In the above example, we created a String array named fruits with an initial size 5.
Later, in a method initializeArray() we initialized the array elements.

This picture demonstrates the result of line 4.

When a String array is declared and created, its element gets default value ‘null’.

Declaring, creating and initializing a String array

You can declare, create and initialize a String array in one step.

String fruit = "Pineapple"; String[] fruits = ;

How this works?

  • Creates a String object “Pineapple” in the memory and fruit referencing to it.
  • Declares a String array reference variable fruits.
  • Creates a String array object in the memory with a length of five.
    • Size of an array is determined by the number of comma-separated elements between the curly braces.

    Creating an anonymous String array

    You can declare, create and initialize a String array object in one line.

    String fruit = "Pineapple"; String[] fruits = new String[];

    This is similar to the previous method but this method is useful when you want to create a just-in-time String array to use as an argument to a method that takes a String array parameter.
    Example

    package com.ibytecode.strings.parampassing; public class StringArray < public static void main(String[] args) < method(new String[]); > static void method(String[] fruits) < //Use String[] array here. >>

    When you use this method size should not be specified.
    String[] fruits = new String[2] ; //ERROR

    Iterating through a String array

    Using length variable

    You can use any loop (for, while, do-while) to iterate through a String array starting from first element till array’s length which you will get by using arrayName.length

    package com.ibytecode.strings.arrays; public class IteratingStringArray < public static void main(String[] args) < String fruit = "Pineapple"; String[] fruits = ; //for loop for(int i = 0; i < fruits.length; i++) System.out.println("Fruit at index " + i + ": " + fruits[i]); //while loop int i = 0; while(i < fruits.length) < System.out.println("Fruit at index " + i + ": " + fruits[i]); i++; >> >

    Fruit at index 0: Apple
    Fruit at index 1: Orange
    Fruit at index 2: Banana
    Fruit at index 3: Pineapple
    Fruit at index 4: Strawberry

    Enhanced for loop

    This is a specialized for loop introduced in Java SE 6 to loop through an array or collection.
    It has two parts for(declaration : expression)

    declaration newly declared variable of type String.
    expression this should be an array or collection variable name or a method call that returns a String array.

    Syntax:
    for(type variable : arrayReferenceName)
    //Use variable
    >
    where, type of the variable should be the type of the array.

    package com.ibytecode.strings.arrays; public class IteratingStringArray < public static void main(String[] args) < String fruit = "Pineapple"; String[] fruits = ; for(String s: fruits) System.out.print(s + “ ”); > >

    Apple Orange Banana Pineapple Strawberry

    Источник

Оцените статью