Single Dimensional Array

Author: Ravi Poswal

If you wish to build an array object, that refers to how much heap space to set aside; an array's size must be specified when the object is created. The array type must be used using the keyword new. We indicate how many items of that type the array will store in the bracket.

int [ ] score; //declare the array

sc = new int[4]; // build an array, then assign the size

int [ ] array object         

Code Example

import java.util.Scanner;
public class Test1 
{
public static void main(String[] args) 
{
int arr[]=new int[5];
Scanner sc=new Scanner(System.in);
int i;
System.out.println("Enter the elements of array");
for(i=0;i<5;i++)
{		
arr[i]=sc.nextInt();
}
System.out.println("Printing elements of array");
for(i=0;i<5;i++)
{	
System.out.println(arr[i]);
}    
}   
}

Searching an element in the array

Code Example

import java.util.Scanner;
public class Test3 
{
	public static void main(String[] args) 
	{
		int arr[]=new int[10];
		int i,n,count=0;
		Scanner sc=new Scanner(System.in);
		System.out.println("Enter the elements of array");
		for(i=0;i<10;i++)
		{
			arr[i]=sc.nextInt();
                }
		System.out.println("Enter the elements to be searched");
		n=sc.nextInt();
			for(i=0;i<10;i++)
		{
			if(arr[i]==n)
			{
				count++;
                         }
                 }
		if(count>0)
		{
                  System.out.println("Number found "+count+ "  times");	
                 }
		else
		{
               	System.out.println("Number not found");
		}	
}
}