Home » Java Basics » arrays » Java String Array Example

About Konstantina Dimtsa

Konstantina Dimtsa
Konstantina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she is currently pursuing M.Sc studies in Advanced Information Systems at the same department. She is also working as a research associate for NKUA in the field of telecommunications. Her main interests lie in software engineering, web applications, databases and telecommunications.

Java String Array Example

Last updated Jan. 14, 2019

In this example we will show how to declare and populate a Java String Array as well as how to iterate through all its elements.

1. Example of Java String Array

Create a java class named JavaStringArrayExample.java with the following code:

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

JavaStringArrayExample.java

package com.javacodegeeks.javabasics.stringarray;

public class JavaStringArrayExample {

 public static void main(String args[]) {

 // declare a string array with initial size
 String[] schoolbag = new String[4];

 // add elements to the array
 schoolbag[0] = "Books";
 schoolbag[1] = "Pens";
 schoolbag[2] = "Pencils";
 schoolbag[3] = "Notebooks";

 // this will cause ArrayIndexOutOfBoundsException
 // schoolbag[4] = "Notebooks";
 }
}

Let’s give a short explanation of the above code. First, we declare a string array with an initial size of 4 elements and then add 4 elements. If you try to add one more element, you will have java.lang.ArrayIndexOutOfBoundsException, as the capacity of the array is fixed and cannot be resized once created. If you want a dynamically sized array where you can add and remove the objects and the size is adjusted accordingly, you should use an ArrayList. You can have a look at How to use ArrayList example.

package com.javacodegeeks.javabasics.stringarray;

public class JavaStringArrayExample {

 public static void main(String args[]) {
 // declare a string array with no initial size
 // String[] schoolbag;

 // declare string array and initialize with values in one step
 String[] schoolbag = { "Books", "Pens", "Pencils", "Notebooks" };

 // print the third element of the string array
 System.out.println("The third element is: " + schoolbag2[2]);
 }
}

Next, we defined another string array named schoolbag2 as it is more common to declare and populate a string array in one step.

Output:

The third element is: Pencils

Now, we will show two ways of iterating through all the elements of the array.

The first one is a more “traditional way”, by using the standard for loop mechanism and the size of the array.

package com.javacodegeeks.javabasics.stringarray;

public class JavaStringArrayExample {

 public static void main(String args[]) {

  String[] schoolbag = { "Books", "Pens", "Pencils", "Notebooks" };

  // iterate all the elements of the array
  int size = schoolbag.length;
  System.out.println("The size of array is: " + size);

  for (int i = 0; i < size; i++) {
   System.out.println("Index[" + i + "] = " + schoolbag[i]);
  }
 }
}

Output:

The size of array is: 4
Index[0] = Books
Index[1] = Pens
Index[2] = Pencils
Index[3] = Notebooks

The second way uses the enhanced for loop example, which was introduced in Java 5.

package com.javacodegeeks.javabasics.stringarray;

public class JavaStringArrayExample {

 public static void main(String args[]) {

  String[] schoolbag = { "Books", "Pens", "Pencils", "Notebooks" };

  // iteration provided by Java 5 or later
  for (String str : schoolbag) {
   System.out.println(str);
 }
}

Output:

Books
Pens
Pencils
Notebooks

Let’s now test if a string array contains a value.

package com.javacodegeeks.javabasics.stringarray;

public class JavaStringArrayExample {

 public static void main(String args[]) {

  String[] schoolbag = { "Books", "Pens", "Pencils", "Notebooks" };

  String findString = "Pens";
  boolean found = false;
  for (String element:schoolbag) {
      if (element.equals(findString)) {
          found = true;
  break;
      }
  }
  if (found) {
     System.out.println("The array contains the string: " + findString);
  } 
  else {
      System.out.println("The array does not contain the string: " + findString);
   }
 }
}

Next let’s see how to sort a string array.

package com.javacodegeeks.javabasics.stringarray;

public class JavaStringArrayExample {

 public static void main(String args[]) {

  String[] schoolbag = { "Books", "Pens", "Pencils", "Notebooks" }; 

  Arrays.sort(schoolbag);
  for (String element : schoolbag) {
       System.out.println(element);
  }
 }
}

Output:

Books
Notebooks
Pencils
Pens

Now we are going to convert a string array into a string.

package com.javacodegeeks.javabasics.stringarray;

public class JavaStringArrayExample {

 public static void main(String args[]) {

  String[] schoolbag = { "Books", "Pens", "Pencils", "Notebooks" };

  String s = Arrays.toString(schoolbag);
  System.out.println(s);
 }
}

Output:

[Books, Pens, Pencils, Notebooks]

Let’s see how to convert a string array into a set.

package com.javacodegeeks.javabasics.stringarray;

public class JavaStringArrayExample {

 public static void main(String args[]) {

  String[] schoolbag = {"Books", "Pens", "Pens"}; 
  List<string> stringList = Arrays.asList(schoolbag);
  Set<string> stringSet = new HashSet<string>(stringList);
  System.out.println("Size of the list is: " + stringList.size());
  System.out.println("Size of the set is: " + stringSet.size());
 }
}

Output:

Size of the list is: 3
Size of the set is: 2

So now we will see how to convert a list into a string array.

package com.javacodegeeks.javabasics.stringarray;

public class JavaStringArrayExample {

 public static void main(String args[]) {

  List<string> stringList = new ArrayList();
  stringList.add("Books");
  stringList.add("Pens");
  stringList.add("Pencils");
  stringList.add("Notebooks");

  String[] schoolbag = stringList.toArray( new String[] {} );

  for (String element : schoolbag) 
  {
    System.out.println(element);
  }
 }
}

Output:

Books
Pens
Pencils
Notebooks

Finally, let’s see the two-dimensional string array.

package com.javacodegeeks.javabasics.stringarray;

public class JavaStringArrayExample {

 public static void main(String args[]) {
 
  String[][] schoolbagArray = new String[4][2];
  schoolbagArray[0] = new String[] {"Pens", "Pencils"};
  schoolbagArray[1] = new String[] {"Books", "Notebooks"};
  System.out.println( schoolbagArray [1][0] );
 }
}

Output:

Books

2. Download the source code

This was an example of Java String Array. You can download the source code from here: StringArrayExample.zip

(+1 rating, 1 votes)
4 Comments Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

4
Leave a Reply

avatar
2 Comment threads
2 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
3 Comment authors
sagarHanumandlaraj jadav Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
raj jadav
Guest
raj jadav

can u tell me how to insert string in string array in java using for loop by scanning input from user.

sagar
Guest
sagar

import java.util.Scanner; public class ArrayOfStrings { public static void main(String[] args) { String[] names = new String[5]; Scanner keyboard = new Scanner(System.in); System.out.println(“Enter 5 names of your friends “); for (int index = 0 ;index < 5; index++){ names[index] = keyboard.nextLine(); } System.out.println(" the names of your friends are "); for (int index = 0 ;index < 5; index++){ System.out.print(names[index]+" "); } } }

sagar
Guest
sagar

enter all the strings in new line only.

Hanumandla
Guest
Hanumandla

// declare string array and initialize with values in one step
String[] schoolbag = { “Books”, “Pens”, “Pencils”, “Notebooks” };

This has to be changed to schoolbag2