One-Dimensional Array

The array taking one subscript is known as one-dimensional array.

Declaration

The general form   to declare an array is:
Type[] var-name;
here type declares the element type of the array. The element type determines the data type of each element. For example, the following declares an array named silan will the type array of int :
Example;
int[] arr;
here arr is an array(variable), but no array actually exists. That means the value of array is set to null which represents an array having no value. So java concept is saying that to link arr with an actual, physical array of integers, you must allocate using new operator(special operator for allocating memory) and assign it to arr. The general form of new for allocating one-dimensional array is :
Syntax:
array-name=new type[size];
where,

  • type specifies the type of data being allocated.

  • Size specifies the number of elements in the array.
  • Array-var is the array variable that is linked to the array.
  • The elements in the array allocated by new will automatically be initialized to zero(for numeric types), false(for Boolean), or null(for reference types).

     

Example:

int[]=arr=new int[5];

when this statement is executed, 20(4bytes*5) of memory will be allocated dynamically named as arr having capability to contain maximum 5 integer data items.
Array Initialization
When the values are assigned to an array is known as array initialization,
Example: 

int[] arr={10,20,30,40,50};
here, arr[0]=10;
arr[1]=20;
arr[2]=30;
arr[3]=40;
arr[4]=50;


one dimensional array

Let’s see a simple array program:
Average.java

import java.util.Scanner;
class Average {
    public static void main(String[] args) {
        int sum = 0, size;
        double avg;
        Scanner s = new Scanner(System.in);
        System.out.println("enter the size of the array:");
        size = s.nextInt();
        int a[] = new int[size];
        System.out.println("enter the elements the array elements:");
        for (int i = 0; i < a.length; i++) {
            a[i] = s.nextInt();
            sum = sum + a[i];
        }
        avg = (double)(sum / a.length);
        System.out.println("sum is: " + sum);
        System.out.println("average is: " + avg);
    }
}

 Output:

enter the size of the array
5
enter the array elements
1
2
3
4
5
sum is 15
average is 3.0

 

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Data Science with Python Training | Projects

Silansoftware Pvt.Ltd, BBSR
Call to: 0674-2361252

Comment