Day17: Arrays

 Arrays

In Java just like C and C++ arrays are collection of similar types of Data element stored at continuous memory locations. But there are few more properties associated with arrays and they are - 
  1. In Java Arrays are Object
  2. Since Array are object they are always created dynamically using the keyword "new".
  3. Since arrays are object they always live in heap area in memory.
  4. Since arrays are object we require an array reference to access them.

Creating an Array :

1 - Creating array reference 

<data_type>[ ] <array ref>;
OR
<data_type><array_ref>[ ];

2- Creating the Actual Array

<array_ref> = new<datatype>[size];

int [ ] arr; (Read as : arr is a reference to an integer array)
arr = new int[10];
OR
int[] arr = new int[10];



Accessing the Array:

class ArrayDemo
{
public static void main(String [ ] args)
{
int [ ] arr = new int[5];
arr[0] = 15;
System.out.println(arr[0]);
arr[1] = 20;
System.out.println(arr[1]);
arr[5] = 50;
System.out.println(arr[5]);
}
}

Output : 
Shown in the figure:


Exception in thread "main" java.lang.ArrayIndexoutofBoundException index 5 out of bonds for length 5 at ArrayDemo.main(ArrayDemo.java)

//Problem : Write a program to create an integer array of size n where n should be taken by the user. Now except values from the user in that array and finally display all the values along with their sum and average.

import java.util.Scanner;
class ArrayDemo
{
public static void main(String [ ] args)
{
int n;
int [ ] arr;
Scanner kb = new Scanner(System.in);
System.out.println("Enter Size of array ");
n = kb.nextInt();
arr = new int[n];
System.out.println("Enter " + n);
for(int i = 0; i<n; i++)
{
arr[i] = kb.nextInt();
}
int sum = 0;
for(int i = 0; i<n; i++)
{
System.out.println(arr[i]);
sum = sum + arr[i];
}
System.out.println("Sum is "+sum);
System.out.println("Average is "+(float)sum/n);
}
}

Comments

Popular posts from this blog

Day2 : Compiling Java Program with Examples

Day1: Introduction to Java and its feature

What does System.out.printf( "%-15s%03d\n", s1, x) do?