Page 288 - Cs_withBlue_J_C11_Flipbook
P. 288
There can be two ways to declare an array which are static declaration and dynamic declaration. Let us understand
these declarations in detail.
11.3.1 Static Declaration
In this type of array declaration, the size of the array is fixed and the memory is allocated at compile time. In this
declaration, we need to specify the values or the elements of the array in the program itself. Let us see some examples
in which both the length of the array and the values are declared. These examples also demonstrate different data
types used with an array.
int array[ ]={1,2,3,4,5};
The above statement creates an integer array of size 5 and stores 5 integer elements in the array at compile time.
Other data types also have a similar type of declaration.
double array[ ]={1.2,3.4,1.5,76.4,55.5};
The above statement creates a double-type array of size 5 and stores 5 double-type values in the array at compile time.
char array[ ]={'a','B','2','5',':'};
The above statement creates a character type array of size 5 and stores alphanumeric elements in it at compile time.
The character array elements are enclosed within single quotes.
String array[ ]={"Joy","Gopal"};
The above statement creates a string type array of size 2 and stores two strings at compile time. The string array
elements are enclosed within double quotes.
The below program helps understand the different types used in an array and explains the logic.
Program 3 Write a program in Java to print the names and roll numbers of the following students.
Name: Ajoy, Amit, Baban, Raj, Satyaki and Roll numbers: 1, 2, 3, 4, 5.
1 import java.util.*;
2 class name_roll
3 {
4 public static void main() {
5 String name[ ]={"Ajoy", "Amit", "Baban", "Raj", "Satyaki"};
6 int roll[ ]={1,2,3,4,5};
7 int i;
8 for(i=0; i<5; i++) {
9 System.out.println(name[i] + "\t" + roll[i]);
10 }
11 }
12 }
The output of the preceding program is as follows:
Ajoy 1
Amit 2
Baban 3
Raj 4
Satyaki 5
286286 Touchpad Computer Science-XI

