digrach

Object Array syntax

Apr 7th, 2014
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.61 KB | None | 0 0
  1. public class StartMain {
  2.  
  3.     public static void main(String[] args) {
  4.  
  5.         System.out.println("2 identical arrays of Widget are created using 2 different techniques.\n");
  6.  
  7.         initialiseArrayExample1();
  8.         initialiseArrayExample2();
  9.  
  10.     }
  11.  
  12.     public static void initialiseArrayExample1() {
  13.         System.out.println("The first technique is suitable for a small number of new objects./n");
  14.  
  15.         // Instantiate the array of type Widget.
  16.         Widget widgetArray[] = new Widget[5];
  17.  
  18.         // Widgets are instantiated directly into the array
  19.         widgetArray[0] = new Widget(1);
  20.         widgetArray[1] = new Widget(2);
  21.         widgetArray[2] = new Widget(3);
  22.         widgetArray[3] = new Widget(4);
  23.         widgetArray[4] = new Widget(5);
  24.  
  25.         System.out.println("Print from example 1");
  26.         printWidgetArray(widgetArray);
  27.  
  28.     }
  29.  
  30.     public static void initialiseArrayExample2() {
  31.  
  32.         System.out.println("The second technique is suitable for existing objects./n");
  33.  
  34.         // Instantiate individual widget objects.
  35.         Widget w1 = new Widget(1);
  36.         Widget w2 = new Widget(2);
  37.         Widget w3 = new Widget(3);
  38.         Widget w4 = new Widget(4);
  39.         Widget w5 = new Widget(5);
  40.  
  41.         // Instantiate the array of type Widget.
  42.         Widget widgetArray[] = new Widget[5];
  43.  
  44.         // place each widget into the array.
  45.         widgetArray[0] = w1;
  46.         widgetArray[1] = w2;
  47.         widgetArray[2] = w3;
  48.         widgetArray[3] = w4;
  49.         widgetArray[4] = w5;
  50.  
  51.         System.out.println("Print from example 2");
  52.         printWidgetArray(widgetArray);
  53.  
  54.     }
  55.  
  56.     public static void printWidgetArray(Widget[] widgetArray) {
  57.  
  58.         for (int x = 0; x < widgetArray.length; x++) {
  59.             System.out.println(widgetArray[x].getId());
  60.         }
  61.  
  62.     }
  63.  
  64. }
Advertisement
Add Comment
Please, Sign In to add comment