Thursday, 24 May 2018

HOW TO DECLARE AND INITIALIZE AN ARRAY IN JAVA

JAVA ARRAY:

There is many way to declare and initialize array element in java programming.
There is two way to write array in java

1)when you initialize the array then your write-

a)Type 1:
int[] arr={30,40,50,60};


b)Type 2:
int []arr={30,40,50,60};


c)Type 3:
int arr[]={30,40,50,60};


2)when you declare the array and you want to set value from user then  you can declare array in different format like this-(This is also known as Instantiation)


a)Type 1:
int arr2[]=new int[];


b)Type 2:
int arr2[]=new int[]={23,45,67,9};


c)Type 3:
int arr2;
arr2=new int[];

Instantiation of and Array in java:

arrayRefVar=new datatype[size]; 

SIMPLE PROGRAM OF SINGLE DIMENSION ARRAY IN JAVA

class Arraytest{
public static void main(String args[]){

int a[]=new int[5];//declaration and instantiation  


a[0]=20;//initialization  


a[1]=45;  


a[2]=34;  


a[3]=46;  


a[4]=5056;

//printing The array  element


for(int i=0;i<a.length;i++)//length is the property of array  


System.out.println(a[i]);

}} 

 OUTPUT:

Output: 20
       45
       34
       46
       5056


SIMPLE PROGRAM TO GET THE VALUE FROM THE USER:

import java.util.Scanner;
public class ArraySum
{
    public static void main(String[] args)
    {
        int no, sum = 0;


        Scanner in = new Scanner(System.in);


        System.out.print("Enter no. of elements");


        no = in.nextInt();


        int a[] = new int[no];


        System.out.println("Enter all the elements:");


        for(int i = 0; i < n; i++)
        {
            a[i] = in.nextInt();
            sum = sum + a[i];
        }


        System.out.println("Sum:"+sum);
    }


OUTPUT:
Enter no. of elements:5
Enter all the elements:
1
2
4
6
7
Sum:20

   

No comments:

Post a Comment