Way2Java

String Array Object String Array

String Array Object String Array

Summary: By the end of this tutorial "String Array Object String Array", you will come to know how to create string array and converting object array to string array.

String arrays play very important role in any language coding. In the following program, string arrays are created in three ways.

1. Declaration and assignment
2. Initialization
3. Object array to string array

public class StringArrays
{
  public static void main(String args[])
  {
                                                    // string array declaration and assignment
    String sarray1[] = new String[3];
    sarray1[0] = "way";
    sarray1[1] = "2";
    sarray1[2] = "java";
    
    System.out.print("sarray1 elements: ");
    for(int i = 0; i < sarray1.length; i++)
       System.out.print(sarray1[i] + ",  ");
                                                    // string array initialization
    String sarray2[] = { "Todays", "wastage", "tomorrows", "shortage" };
    System.out.print("\nsarray2 elements: ");
    for(String st : sarray2)                         // new type of array
       System.out.print(st + ",  ");

                     // object array to string array
    Object obj[] = { "avoid", "gizmos", "carrying", "to", "workstation" };
    String sarray3[] = new String[obj.length];
    for(int i = 0; i < sarray3.length; i++)          
    {
      sarray3[i] = (String) obj[i];
    }
    System.out.print("\nsarray3 elements: ");
    for(int i = 0; i < sarray3.length; i++)
       System.out.print(sarray3[i] + ",  ");
  }
}



Output screen of StringArrays of String Array Object String Array
       for(String st : sarray2)

It is a special type of for loop known as enhanced for loop, introduced with JDK 1.5 to iterate string and datastructure elements.

      Object obj[] = { "avoid", "gizmos", "carrying", "to", "workstation" };
      for(int i = 0; i < sarray3.length; i++)          
      {
        sarray3[i] = (String) obj[i];
      }

An object array obj containing some string elements is created and in the for loop each object element is type casted to string element.

Array related topics that increase array manipulation techniques

Topics related to In and Outs of interfaces