Arrays for data structure which acts as a containers that holds collections of variables of same type, in other words ,size collection of elements of the same data type. Variables stored in arrays are in continues memory locations.Before the advent of arraylists , arrays were used by programmers to store huge amount of variables
Let us first see the differences between array lists and arrays :
new int[6] //here type of array is int and size is 6.
Let us first see the differences between array lists and arrays :
- Arraylists are dynamic in size where the size of an arraylist can grow when new elements are added while arrays are fixed in size.
- Arrays contains both objects as well as primitives whereas array list contains only objects.
- Loops such as For loops are used iterate elements and iterators can be used in arralylists.
- Arraylists ensures type safety through generics whereas arrays are homogeneous.
- Elements are added by assignment operators and add() method is used in Arraylists to add elements.
- Arrays are mutli-dimensional where as Arraylists are single dimensional.
new int[6] //here type of array is int and size is 6.
Now let us see the different ways to print int array,byte array,array of strings,two dimensional array and also array of array.
- Printing int array :
We can use Arrays.toString(int array), for example :
int [] odd = {3,5,7};
System.out.printing("odd numbers are"+Arrays.toString(odd));
- Printing byte array :
String example="hello";
bytes[] bytes = example.getBytes();
String s = new String(bytes);
System.out.println("text decrypted:"+s);
- Print an array of strings :
String [] cars=new Strings[3];
cars[0]="Ferrari";
cars[1]="maruthi";
cars[2]="Datsun";
for(int i=0;i<cars.length;i++)
{
System.out.println(cars[i]);
Another way is to use Arrays.toString().
- Printing two dimensional array:
String [][] greetings={{"hi","good morning "},{"hello"," good evening "}};
System.out.println(" planets"+Arrays.deepToString);
- Printing array of array:
String []arr1=new String [] {"hi","hello"};
String []arr2=new String [] {"how are you"};
String [][] arrayOfArray=new String[][]{arr1,arr2};
System.out.println(Arrays.deepToString));
No comments:
Post a Comment