Java string examples array strings

Java Array of Strings

Java String Array is a Java Array that contains strings as its elements. Elements of no other datatype are allowed in this array.

In this tutorial, we will learn how to declare a Java String Array, how to initialize a Java String Array, how to access elements, etc.

How to declare a String Array?

Following is the syntax to declare an Array of Strings in Java.

You can use any of these two notations.

How to initialize a String Array?

To initialize a string array, you can assign the array variable with new string array of specific size as shown below.

arrayName = new string[size];

You have to mention the size of array during initialization. This will create a string array in memory, with all elements initialized to their corresponding static default value.

Читайте также:  Css да ж мыс істеу негіздері

The default value for a string is empty string “”.

Following is an example program to initialize a string array of size 10.

Java Program

public class ArrayExample < public static void main(String[] args) < String names[]; names = new String[10]; >>

We have declared and initialized the string array in two different statements. But you can combine the declaration and initialization, to form the definition of string array, as shown below.

Java Program

public class ArrayExample < public static void main(String[] args) < String names[] = new String[10]; >>

In the above example, we have created a string array named names, and initialized it to a string array of size 10 with default values of empty strings.

You can also assign strings directly to the string array when declaring it.

In the following example, we have declared and initialized string array with elements.

Java Program

public class ArrayExample < public static void main(String[] args) < String names[] = ; > >

Now names is a String array with size of 4, because there are four elements in the array we assigned.

How to access String Array Elements?

Following is the syntax to access an element of an array using index.

The above statement can be used either to read an element at given index, or set an element at given index. The read or write operation depends on which side of assignment operator you are placing this.

For example, in the following program, we are reading the element of string array at index 2.

Java Program

public class ArrayExample < public static void main(String[] args) < String names[] = ; String name = names[2]; System.out.println(name); > >

And in the following example, we are updating the element of string array at index 2 to “lychee”.

Java Program

public class ArrayExample < public static void main(String[] args) < String names[] = ; names[2] = "lychee"; System.out.println(names[2]); > >

How to iterate over array elements?

We can use any of these looping statements like For Loop or While Loop to iterate over elements of a Java Array.

In the following example, iterate over elements of String Array using Java While Loop.

Java Program

public class ArrayExample < public static void main(String[] args) < String names[] = ; int index = 0; while (index < names.length) < System.out.println(names[index]); index++; >> >
apple banana cherry orange mango

In the following example, we will iterate over elements of String Array using Java For Loop.

Java Program

public class ArrayExample < public static void main(String[] args) < String names[] = ; for (int index = 0; index < names.length; index++) < System.out.println(names[index]); >> >
apple banana cherry orange mango

And in the following example, we will use Java for-each loop, to iterate over elements of string array. For each loop can be used to execute a set of statements for each string in string array.

Java Program

public class ArrayExample < public static void main(String[] args) < String names[] = ; for (String name: names) < System.out.println(name); >> >
apple banana cherry orange mango

Conclusion

In this Java Tutorial, we learned about String Array in specific: how to declare a string array, how to initialize it, how to access elements, etc.

Источник

String Array in Java

In this guide, you will learn about string array in java, how to use them and various operations that you can perform on string array in java.

String array is a collection of strings, stored in contiguous memory locations.

For example: The following string array contains four elements. These elements are stored in contiguous memory locations and can be accessed using array index such as: names[0] represents first element «Chaitanya» . Similarly names[1] represents second element «Ajeet» , names[2] represents third element «Hari ” and so on.

String Array Declaration

There are two ways to declare a String array in Java.

1. Without specifying the array size:

2. Array size is specified: The following array can hold upto 5 strings.

String[] strArray = new String[5];

String Array Initialization

1. Inline Initialization:

String[] names = new String[] ; OR String[] names = ;

2. Normal Initialization after declaration:
Here, we have declared an array names with the fixed size of 4 and initialized the array later.

String[] names= new String[4]; names[0]= "Chaitanya"; //first element names[1]= "Ajeet"; //second element names[2]= "Hari"; //third element names[3]= "Rahul"; //last element

Simple String Array Example in Java

In this example, we have a string array fruits . This array contains three elements (strings). We are displaying the elements of string array using for loop. The length property of array ( fruits.length ) returns the number of elements in an array, in this case its 3.

public class JavaExample < public static void main(String a[])< //declared and initialized a string array String[] fruits = new String[]; for (int i=0; i > >

Java String Array

String array ArrayIndexOutOfBoundsException

If the specified index is beyond the size of the array then the compiler throws ArrayIndexOutOfBoundsException .

public class JavaExample < public static void main(String a[])< //declared and initialized a string array String[] fruits = new String[]; //We are trying to print 11th element of the array //but the array contains only 3 elements. This will //throw ArrayIndexOutOfBoundsException System.out.println(fruits[10]); > >

Java string array exception

Iterating a String Array

Let’s see how to iterate a string array. We can iterate using normal for loop or enhanced for loop (for each loop).

public class JavaExample < public static void main(String a[])< //declared and initialized a string array String[] fruits = new String[]; //iterating using normal for loop System.out.println("Iterating using for loop:"); for (int i=0; i //iterating using for-each loop System.out.print("Iterating using foreach loop: "); for (String str: fruits) < System.out.print(str+ " "); >> >

Iterating String array in Java

Adding elements to String array

You already learned that the size of the array is fixed, which means if it is full, you cannot add any more elements to it. However there are two ways, you can add elements to an array. Technically it’s not adding the elements to the existing array, rather a new array with all the elements of previous array along with the new elements.
1. Creating a new array
2. Using ArrayList

1. Adding elements to an array by creating new array

Steps followed in this program are:
1. Create a new array with the larger size to accommodate new elements.
2. Copy all elements from old array to new array.
3. Add new elements to new array.
4. Print new array

public class JavaExample < public static void main(String a[])< //declared and initialized a string array String[] fruits = new String[]; //we want to add two more elements to the fruits array so let's //create a new array with the size of 5 String[] newFruits = new String[fruits.length+2]; //copying elements from old array to new array for (int i=0; i //Adding new elements newFruits[newFruits.length-2]= "Mango"; //second last element newFruits[newFruits.length-1]= "Kiwi"; //last element //print new array for (String str: newFruits) < System.out.println(str); >> >
Apple Orange Banana Mango Kiwi

2. Adding elements to an array using ArrayList

Steps followed in this program are:
1. Convert array to ArrayList.
2. Add as many elements as you like in ArrayList as ArrayList is dynamic and can grow and shrink automatically.
3. Once addition is done, convert back the ArrayList to an Array.
4. Print the array.

import java.util.*; public class JavaExample < public static void main(String a[])< //declared and initialized a string array String[] fruits = new String[]; //Convert the array "fruits" to an ArrayList ArrayList fruitList = new ArrayList(Arrays.asList(fruits)); //Adding elements to ArrayList fruitList.add("Mango"); fruitList.add("Kiwi"); //Convert the ArrayList to array String[] newFruits = fruitList.toArray(new String[fruitList.size()]); //print new array for (String str: newFruits) < System.out.println(str); >> >
Apple Orange Banana Mango Kiwi

Sorting string array

Here, we are demonstrating how to sort a string array. It is simple, just import java.util.Arrays package to use the sort() method of Arrays class. The array passed in the sort() method is sorted in ascending order.

import java.util.Arrays; public class JavaExample < public static void main(String a[])< String[] names = new String[]; //print array before sorting System.out.println("Array before sorting: "); for (String str: names) < System.out.print(str+ " "); >//sorting array Arrays.sort(names); //new line System.out.println(); //print array after sorting System.out.println("Array after sorting: "); for (String str: names) < System.out.print(str+ " "); >> >

Sorting String Array

Search an element in a String array

Here, we are searching an element in string array. We are iterating the whole array and matching every element with the searchItem , if a match is found, we are storing the index and setting the foundFlag to true . If the whole array is traversed and no match is found then the if-else statement after for loop, prints the message that “String is not found”.

public class JavaExample < public static void main(String a[])< String[] names = new String[]; //this will represent the index of search element when it is found int index=0; //This will set to true, if element is found in array, else it //will remain false. boolean foundFlag = false; //This is the search element, we are searching for this element in array String searchItem ="Rob"; for (int i = 0; i < names.length; i++) < if(searchItem.equals(names[i])) < //if element found, get index, set flag to true and break the loop index = i; foundFlag = true; break; >> if(foundFlag) System.out.println("String "+searchItem +" is found at index: "+index); else System.out.println("String "+searchItem +" is not found"); > >
String Rob is found at index: 2

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Источник

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.

Источник

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