Array – Java

Very basic way to use java array –

  1. You can either use array declaration or array literal (but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array).For primitive types:
    int[] myIntArray = new int[3];
    int[] myIntArray = {1,2,3};
    int[] myIntArray = new int[]{1,2,3};

    For classes, for example String, it’s the same:

    String[] myStringArray = new String[3];
    String[] myStringArray = {"a","b","c"};
    String[] myStringArray = new String[]{"a","b","c"};
  2. Array length –
  3. Looping an array
    for(int k =0; k <myIntArray.length; k++) {
    for(int value:myIntArray) {
  4. Copy an array
    int[] B = Arrays.copyOf(A, j + 1);
    – copy array element from 0 to j+1
  5. ArrayList
    List<Integer> b = new ArrayList<Integer>();
    if (s.contains(value)) {
    } else {
  6.  // Sort array elements
  7. Boolean[] vis = new Boolean[n];
    Arrays.fill(vis, false);
  8. If an array or list collection has only primitive type then we can directly print it like-
    System.out.println( list);
    No need to use toString method.
    If we have a list of custom class then we need to override toString method in that class like here
  9. Create an ArrayList from another ArrayList. SO
    myObject = new ArrayList<Object>(myTempObject);
  10. Copy an array and convert it to String –
    messageChars = Arrays.copyOf(messageChars, messageChars.length – spaceCount);
    return new String(messageChars);



Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s