Tuesday, July 8, 2014

Arrays in java

//By Vadivelan.U (Vadivelan Udayakumar)

import java.io.*;
import java.util.*;//for using scanner class

class array
{
public static void main(String[] args)
{
int[] a=new int[10];//now a is an integer array of size 10

int[] c;//no memory is still allocated for c array

c=new int[50];//memory gets allocated for c array

int[] b=a;//now a and b have same memory and they have samelengths....any changes done over array b affects a array..

int[] d={10,20,30};//declaration allowed

int[] m=new int[]{5,10,15};//declaration allowed

int[] e;//no memory allocated

//By Vadivelan.U (Vadivelan Udayakumar)

System.out.println("Enter the array size of e array:");
Scanner s=new Scanner(System.in);
int n=s.nextInt();
e=new int[n];//memorysize gets allocated as per the user needs


//By Vadivelan.U (Vadivelan Udayakumar)

for(int i=0;i<10;i++)
a[i]=i;//array initialization

for(int i=0;i<10;i++)
System.out.println("a["+i+"] = "+a[i]);

fun(a);//passing array as a parameter => pass by reference

System.out.println("\n\n\n\n");

for(int i=0;i<10;i++)
System.out.println("a["+i+"] = "+a[i]);//array a values changes based on the changes done in the formal parameters..

int[] b1=fun2();//a function can return an array

for(int i=0;i<b1.length;i++)
System.out.println("b1["+i+"] = "+b1[i]);//the returned array gets printed..

//By Vadivelan.U (Vadivelan Udayakumar)

int[] d1=new int[20];
d1=a;//now implicitly d1 gets converted to an array of length 10 and has the same address of that of a array

System.out.println("\n\n\n\n");

for(int i=0;i<10;i++)
System.out.println("d1["+i+"] = "+d1[i]);

}

//By Vadivelan.U (Vadivelan Udayakumar)



static void fun(int[] x)//a function which accepts array as a parameter...now x array and a array have same memory address
{
for(int i=1;i<=10;x[i-1]=i,i++);
}





static int[] fun2()//a function which is gona return an array..
{
int[] a={10,20,30};
return a;// the address of a array is now passed to b1......so if b1 is already allocated with memory also its a waste..coz anyways b1 is gona work in the memory of a after the function call.......
}


//By Vadivelan.U (Vadivelan Udayakumar)


}  

No comments:

Post a Comment