Skip to main content

Java Array, Multi Dimensional Array, Anonymous Array and Arrays Util Class

Array

  • An array is a index based container object.
  • The length of an array fixed at time of array creation.
  • An Array holds a fixed number of values of a single type.

One Dimensional Array

Array can be created by two ways.
Syntex:

//1st way
arraytype[] name = new arraytype[length];

//2nd way
arraytype name[] = new arraytype[length];

1st way is more readable.
Examples:

//charecyter Array Example:
//creating Array of char, length 5
char[] charArray = new char[5];

//Initialize array elements
charArray[0] = 'H';
charArray[1] = 'E';
charArray[2] = 'L';
charArray[3] = 'L';
charArray[4] = 'O';

//creating Array of int, length 4
int[] intArray = new int[4];

//Initialize array elements
intArray[0] = 2;
intArray[1] = 0;
intArray[2] = 1;
intArray[3] = 5;

//creating Array of string, length 7
String[] weeks = new String[7];

//Initialize array elements
weeks[0] = "mon";
weeks[1] = "tue";
weeks[2] = "wed";
weeks[3] = "thu";
weeks[4] = "fri";
weeks[5] = "sat";
weeks[6] = "sun";

Shortcut syntax to create and initialize an array:


//creating & Initialize Array
char[] charArray = {'H','E','L','L','O'};
int[] intArray = {2,1,0,5};
String[] weeks = {"mon","tue","wed","thu","fri","sat","sun"};

Accessing an Array in java


public class IntArrayTest {
 
 private void printArrayElement() {
  //creating Array of int, length 4
  int[] intArray = new int[4];

  //Initialize array elements
  intArray[0] = 2;
  intArray[1] = 0;
  intArray[2] = 1;
  intArray[3] = 5;
  
  //access array element
  System.out.println(intArray[2]);
  System.out.println(intArray[3]);
  
  //access each element of array
  for(int i=0;i<4;i++){
   System.out.println(intArray[i]);
  }
  
 }
 
 public static void main(String[] args) {
  IntArrayTest at = new IntArrayTest();
  at.printArrayElement();
 }
}

/*
output:
1
5
2
0
1
5
*/

public class StringArrayTest {
   
       private static void printArrayElement() {
  //creating & Initialize Array
  String[] days = {"mon","tue","wed","thu","fri","sat","sun"};
  
  //access array element
  System.out.println(days[2]);
  System.out.println(days[3]);
  System.out.println("------------");
  //length is attribute of Array object, in which length of array store
  //value of length is 7
  int length = days.length;

  //access each element of array
  for(String day:days){
   System.out.println(day);
  }
 }

        public static void main( String[] args ){
           printArrayElement();
        }

}


Output:
wed
thu
------------
mon
tue
wed
thu
fri
sat
sun

Multi Dimensional Array

If an array contains one or more than one arrays called Multi Dimensional Array.
An array only contains same type of data, if array element have another array objects, so that kind of structure called Multi Dimensional Array.
You can relate this with MATRIX.

Example:

public class ArrayTest {
 
 private void printArrayElement() {
  
  //Create Multi Dimensional Array
  int[][] md= new int[3][2];
  
  //Initialize Multi Dimensional Array
  md[0][0] = 1;
  md[0][1] = 2;
  
  md[1][0] = 3;
  md[1][1] = 4;
  
  md[2][0] = 5;
  md[2][1] = 6;
  
  //access multi dimensional array
  for(int i=0;i<3;i++){
   for(int j=0;j<2;j++){
    System.out.println(md[i][j]);
   }

   System.out.println("---");
  }
  
 }
 
 public static void main(String[] args) {
  ArrayTest at = new ArrayTest();
  at.printArrayElement();
 }
}
/*
output:
1
2
---
3
4
---
5
6
---
*/

public class ArrayTest {
 
 private void printArrayElement() {
  
  //Create & Initialize Multi Dimensional Array
  int[][] md= {{1,2},{3,4},{5,6}};
 
  //access multi dimensional array
  for(int i=0;i<3;i++){
   for(int j=0;j<2;j++){
    System.out.println(md[i][j]);
   }

   System.out.println("---");
  }
  
 }
 
 public static void main(String[] args) {
  ArrayTest at = new ArrayTest();
  at.printArrayElement();
 }
}
/*
output:
1
2
---
3
4
---
5
6
---
*/

Anonymous Array

 Anonymous means not identified by name
  • An array without name is known as Anonymous Array.
  • Anonymous Array use as method argument

int type anonymous array : new int[] { 1, 2, 3, 4, 5};
char type anonymous array :  new char[] {'a', 'b', 'c', 'd');
String type anonymous array : new String[] {"one", "two", "three", "four"};
Eaxmple:

public class ArrayTest {

        public static void main(String[] args) {
  ArrayTest at = new ArrayTest();
 
  at.printIntArrayElement(new int[]{1,2,3,4});
 
  at.printCharArrayElement(new char[]{'a','b','c','d'});
  
  at.printStringArrayElement(new String[]{"one", "two", "three", "four"});
 }
 
 //print int type anonymous array
 private void printIntArrayElement(int[] intArray) {
  
  int length = intArray.length; 
  //access anonymous array
  for(int i=0;i<length;i++){
        System.out.println(intArray[i]);
  }
  
 }
 
 //print char type anonymous array
    private void printCharArrayElement(char[] charArray) {
  
     int length = charArray.length; 
  //access anonymous array
  for(int i=0;i<length;i++){
        System.out.println(charArray[i]);
  }
  
 }
    
  //print String type anonymous array
    private void printStringArrayElement(String[] strArray) {
 
     int length = strArray.length; 
  //access anonymous array
  for(int i=0;i<length;i++){
        System.out.println(strArray[i]);
  }
  
 }

}
/*
output
1
2
3
4
a
b
c
d
one
two
three
four
 */

Arrays Util Class 

Arrays is a util class contains various methods for manipulating array objects. Some useful methods are listed below.

Compare Two Array

Arrays static method equals use for compare two arrays. It returns boolean.

Syntex:

static boolean equals(boolean[] a1, boolean[] a2)

static boolean equals(byte[] a1, byte[] a2)

static boolean equals(char[] a1, char[] a2)

static boolean equals(double[] a1, double[] a2)

static boolean equals(float[] a1, float[] a2)

static boolean equals(int[] a1, int[] a2)

static boolean equals(long[] a1, long[] a2)

static boolean equals(Object[] a1, Object[] a2)

static boolean equals(short[] a1, short[] a2)
Example

import java.util.Arrays;

public class ArraysUtilTest {
 
 public static void main(String[] args) {
  
    int[] a1 = {1,2,3,4};
    int[] a2 = {2,1,3,5};
    int[] a3 = {1,2,3,4};
    
    boolean b1 = Arrays.equals(a1, a2);
    boolean b2 = Arrays.equals(a1, a3);
    
    System.out.println("Is a1 Array equals a2::"+b1);
    System.out.println("Is a1 Array equals a3::"+b2);
 }

}
/*
output
Is a1 Array equals a2::false
Is a1 Array equals a3::true
*/

Print array as string representation

You can use toString() method to represent an array as string.

Syntax:

static String toString(boolean[] a)

static String toString(byte[] a)

static String toString(char[] a)

static String toString(double[] a)

static String toString(float[] a)

static String toString(int[] a)

static String toString(long[] a)

static String toString(Object[] a)

static String toString(short[] a)

static String toString(String[] a)
Example:

import java.util.Arrays;

public class ArraysUtilTest {
 
 public static void main(String[] args) {

  
    int[] a = {2,1,3,5};
    
    String stringRep = Arrays.toString(a);
    System.out.println(stringRep);
    
    String[] str = {"bc","mc","ac"};
    System.out.println(Arrays.toString(str));
 }

}
/*
output
[2, 1, 3, 5]
[bc, mc, ac]
*/

Sort array elements

You can sort array elements into ascending order by using static method sort() of Arrays util class.

Syntax:

static void sort(byte[] a)

static void sort(char[] a)

static void sort(double[] a)

static void sort(float[] a)

static void sort(int[] a)

static void sort(long[] a)

static void sort(Object[] a)

static void sort(short[] a)

static void sort(String[] a)
Example:

import java.util.Arrays;

public class ArraysUtilTest {
 
 public static void main(String[] args) {
 
    int[] a = {2,1,3,5};
    
    //sort int array a
    Arrays.sort(a);
    System.out.println(Arrays.toString(a));
    
    String[] str = {"bc","mc","ac"};
   
    //sort String array str
    Arrays.sort(str);
    System.out.println(Arrays.toString(str));
 }

}
/*
output
[1, 2, 3, 5]
[ac, bc, mc]
*/

Comments

Popular posts from this blog

Java Collection Framework - In 15 Mins

Collection framework is use for storing data in program. Collection framework contains most of data structure like LinkedList, Set, HashMap etc already implemented for you to direct use in program and also gives you flexibility to write own kind of data structure. Java collections framework data structure: Lists: Contains list of objects. Java provides 3 type of ready to use list. ArrayList Vector LinkedList Sets: Contains unique objects, does not allow dublicates. Java provides 3 type of sets, these are HashSet LinkedHashSet TreeSet Maps: Contain key:value data structure, value only access by key. Java provides 4 type of Map. HashMap Hashtable LinkedHashMap TreeMap Queues: Perform FIFO (first in first out) PriorityQueue Java Collection Interface And Collections Util Class Collection is an interface which is implemented by all data structure in java, except Map. Maps (HashMap, LinkedHashMap, Hashtable, TreeMap) are not define by Collection interface, th...

String - A story of very special class in java

String is most used java class in any java project. Java treated String as special class. Lets see, what so special in String. String Basics String is group of characters. char[] chrs = {'i',' ','a','m',' ','h','e','r','o','.'}; String str = new String(chrs); System.out.println(str); /* Output: i am hero. */ String is an immutable class. Immutable class:  A java class which object can not be modified if once created. Because String class is immutable, String is final in nature, its mean you can not modify string object once you created. Default value of string is null. Simplest way to initialize String is //object created in String Literal Pool String str = "hello world"; Above example known as String literal, All string literals in Java programs, such as "hello world", are object of String class. Another way to create String object is //object created in Heap m...

What is Java Serialization?

Java has classes, A class has properties. These properties with values called object or state of object. Now we want to save this state of object into file or database. With java serialization we can convert object state into data stream and this data stream would be save into file system or database or create object replica into another system. Java Serialization Covered Two Process - Serialization : Convert object state into data stream. Deserialization : Convert data stream into object state.  Simple Java Code Example:  import java.io.Serializable; public class Student implements Serializable{ private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } public void print() { System.out.println("Name:"+name+" Age:"+age); } } import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputS...