Sunday, April 5, 2015

Java learning, if you know C : Part-3, Array

Learning Java

2. Difference in array declaration C and Java.

 > Unlike C, Java doesn't have pointers. So we cannot define dynamic array in Java. For it we have to use a different data type/object like
 
   Below code tells about the difference in C and Java
 
  ********************************************************* JAVA PROGRAM *********************************************************

public class twodarray{

public static void main(String args[])
{
int[][] arra;
arra = new int[3][4];

int[][] array = new int[3][]; // One way to define array when number of column elements might change. But can't define dynamic array like C
array[0] = new int[3];

int aRray[][] = new int[2][5];

}
}

********************************************************* JAVA PROGRAM *********************************************************

********************************************************* C PROGRAM *********************************************************
#include
#include

int main()
{
int twoD[2][3];

/* Below one throws error
int twod[][3];
int twoDd[2][];
int Twod[][];
Below one throws error */

int *twod[2];
int **TWOD;

twod[0] = (int *) malloc(sizeof(int)*3);
twod[1] = (int *) malloc(sizeof(int)*4);


TWOD = (int **) malloc(sizeof(int*)*4);

TWOD[0]=(int*) malloc (sizeof(int) *5);

return 0;
}



********************************************************* C PROGRAM *********************************************************

No comments:

Post a Comment