How to create array in Java 

Joined:
03/07/2011
Posts:
57

April 11, 2011 21:17:11    Last update: April 11, 2011 21:17:11
Some methods to create an array in Java:
  1. With literal initialization.
    // array of strings
    String[] dogs = { "Chihuahua", "Dalmatian", "German Shepherd", "Hungarian Hound" };
    
    // array of ints
    int[] primes = { 2, 3, 5, 7, 11 };
    

  2. With array constructor (array allocated by not the elements).
    // create a byte array
    byte[] buffer = new byte[4096];
    
    // create an object array - array of 100 object references created, but objs[0], objs[1]..., are null
    Object[] objs = new Object[100];
    

  3. Anonymous array to be used as a parameter in method invocation
    String.format("Hello %s, %s, %s!", new Object[] { "Moe", "Larry", "Curly"});
    

Share |
| Comment  | Tags