Skip to Content

Java String Array Example

  1. /*
  2.         Java String Array Example.
  3.         This Java String Array example how to create and use String array or array of Strings in Java.
  4.  
  5.  */
  6.  
  7. public class JavaStringArray {
  8.         public static void main(String args[]){
  9.                
  10.                 /*
  11.                  * Java String array can be created in below given ways.
  12.                  */
  13.                
  14.                 /*
  15.                  * Declare and initialize String array in single statement as given below.
  16.                  * This method is particularly useful when we are dealing with very small size array.
  17.                  */
  18.                 String[] myFirstStringArray = new String[]{"String 1", "String 2", "String 3"};
  19.                
  20.                 /*
  21.                  * Declaration and assignment can be done separately as given below.
  22.                  */
  23.                
  24.                 //first declare String array
  25.                 String[] mySecondStringArray = new String[3];
  26.                
  27.                 //Observe that giving size is mandatory here. While there was no size given in the first method.
  28.                
  29.                 //Now Assign individual String array elements
  30.                 mySecondStringArray[0] = "String 1";
  31.                 mySecondStringArray[1] = "String 2";
  32.                 mySecondStringArray[2] = "String 3";
  33.                
  34.                 //Note that, like every other arrays, String array starts with index 0 and not index 1.
  35.                
  36.                 /*
  37.                  * Retrieve values from String Array:            *
  38.                  * String array elements can be retrieved by directly accessing using index. You may also iterate
  39.                  * String array using loop.
  40.                  */
  41.                
  42.                 //this will retrieve second element of first String array
  43.                 System.out.println(myFirstStringArray[1]);
  44.                
  45.                 //iterate the String array using loop
  46.                 for(int i=0; i < mySecondStringArray.length; i++){
  47.                         System.out.println(mySecondStringArray[i]);
  48.                 }
  49.         }
  50. }
  51.  
  52. /*
  53. Output of the above Java String Array Example program would be
  54. String 2
  55. String 1
  56. String 2
  57. String 3
  58. */