Page 289 - Cs_withBlue_J_C11_Flipbook
P. 289
11.3.2 Dynamic Declaration
In this type of array declaration, the size of the array may or may not be fixed and the memory is allocated at run
time. In this declaration, we need not specify the values or the elements of the array in the program itself. It takes the
values from the user at run time or the values are received from some execution. The table given below demonstrates
different data types used in the dynamic declaration of an array.
Array Types Data Types Format
Byte byte ar[ ]=new byte[10];
Short short ar[ ]=new short[10];
Integer array
Int int ar[ ]=new int[10];
Long long ar[ ]=new long[10];
Float float ar[ ]=new float[10];
Real numeric array
Double double ar[ ]=new double[10];
Char char ar[ ]=new char[10];
Character array
String String ar[ ]=new String[10];
As seen in the above table, to create a dynamic array, the ‘new’ keyword is used. The number of values to be allocated,
to the array is defined in the square brackets and their data type is written just before the brackets. Of course, we can
also summarise that the number of values (for the array) will have to be taken from the user with a prompting message.
For each of the data types, as seen in the table, we can thus declare an array with the required size, dynamically, using
the keyword ‘new’ with each of them.
Hence, it is also clear that the user is able to enter any number of values for the array at run time and thus resize the
array.
11.3.3 Taking Dynamic Data in an Array
There are two different ways to input data or values during run time. They are as follows:
• Using Scanner class
• Using InputStreamReader class
Using Scanner Class
To take values in a dynamic format, we have to use a loop to access the index position of the array. Here, to input the
data from the user, the Scanner class is used. The below program explains the logic.
Program 4 Write a program in Java to input the name, section and roll number of n number of students
in a class and print them column-wise.
1 import java.util.*;
2 class array_student
3 {
4 public static void main()
5 {
6 Scanner sc= new Scanner(System.in);
7 int n;
287
Arrays 287

