Java Arrays

Published by Admin on

In Java, Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

If we do not assign values to array elements, and try to access them, the compiler does not generate an error in the case of ordinary variables. Instead it assigns default values which aren’t garbage.

Default assigned values following:-

  • boolean : false
  • int : 0
  • double : 0.0
  • String : null

Syntax

Data_Type[] variable_Name;
or 
Data_Type variable_Name[];

Example

String[] myList;
or
String myList[];

Create an java array by using the new operator

Syntax

Data_Type[] variable_Name = new Data_Type[array_Size];

Example

String[] myList = new String[10];

Multidimensional Arrays / two-dimensional array

In java, a multidimensional / two-dimensional array is an array containing one or more arrays
The Syntax of creating a 2D array is

Datatype arr_name[][]=new Datatype[rows][cols];
OR
Datatype arr_name[][];
arr_name[][]=new Datatype[rows][cols];

The First syntax is used for creating a local array where as the second syntax is used for creating an array that can be used in any method.
Memory allocation of 2D array – In java memory for rows of a 2D array is not a contiguous memory.

For eg. 
int a[][]=new int[3][3];

In a 2D array- arr_name means base address of 2D Array
arr_name[] means base address of 1D array
arr_name[][] means value of that array point

Example

int[][] myNumbers = { {1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10};

Ragged Arrays

A 2D array that has different number of elements in each row is said to be a ragged array.

For eg. To display output
1
2   3
4   5   6
7   8   9   10

A ragged array can be created as follows:

int x[][]=new int[4][];
for(int i=0;i<x.length;i++){
   x[i]=new int[i+1];
}

Question :-

  • What is the difference between int[] a and int a[] ?
  • How do you sort the array elements?
  • What are the different ways of declaring multidimensional arrays in java?
  • What value does array elements get, if they are not initialized?
  • What is two-dimensional array in java?
  • How to Create an array by using the new operator in java?
  • What is Ragged Arrays in Java?
  • What is Multidimensional Arrays in Java?
  • “int a[] = new int[3]{1, 2, 3}” – is it a legal way of defining the arrays in java?
  • How to declare array in java with Example?


0 Comments

Leave a Reply

LinkedIn
LinkedIn
Share
Instagram
Follow by Email
YouTube
YouTube
Telegram
RSS