TechSpace Knowledgebase
Search:     Advanced search
Browse by category:
Contact Us

Java Arrays

Views: 277
Votes: 0
Posted: 07 Sep, 2016
by:
Updated: 08 Sep, 2016
by:

What is meant by an Array ?

An Array is a structure created in the memory to represent more than one value or elements under a single declaration of a variable

What is the Need of Arrays in Java ?

Instead of creating different variables in order to assign different values, by using arrays we can declare more than one element or value under the same declaration, we can also allot the space for each Array in Java.Therefore, we need not create a sepearate variable for each separate variable.

Arrays also makes it easier to perform calculations in the loop

Example : Consider :

for(int i=1;i<=10;i++)

int m = Integer.parseInt(in.readLine());

In the above Java statements , we can input the value of the variable ‘m’ for 10 times using the for loop as shown , but as soon as the next value of the variable ‘m’ is entered by the user the previous value of the ‘m’ gets deleted , therefore , If we want to calculate the sum of the 10 values entered by the user , it is not very easy , therefore , to perform this activity , we can use Arrays to make it easier and simple to avoid confusion for better programming.

Syntax To Declare an Array

The syntax to declare an array is : 

datatype ArrayName[] = new dataype[size];

OR

datatype[] Arrayname = new datatype[size];

The above statement(s) can be shortened and simplified by writing as :

datatype Arrayname[] = {val1,val2,val3………valn};

Examples  : int m[] = new int[10]

In the above statement , we declared ‘m’ as an Array , and we also declared the size of the Array as 10 , therefore , the array ‘m’ can hold 10 different values.

Declaring an Integer data type array : int m[] = {21,85,48,54,78,96,321,54,47,87};

Declaring a Double data type array : double m[] = {13.0,322.15,85.1,63.12,48.12,78.0,48.1,65.12,98.2};

Declaring a String data type array : String m[] = {“Teja Swaroop”,”Pothala”,”Loyola Public School”,”10D”,”48″};

Declaring a Character data type array : char m[] = {‘a’,’c’,’2′,’ ‘,’/’,’?’};

Note : Every element in an array of any datatype is separated by a Coma(,)

‘length’ is the function in which returns the length of the array i.e., the number of elements present in the array

EX : int l = m.length //here ‘m’ is the array and l is the length is the array.

 A simple Program to demonstrate the functioning of Arrays: ….. (i)

class ExArray
{
static void test()
{
int m[] = {12,58,69,87,45,78,25,36};
System.out.println(“The elements in the Array are : “);
for(int i=0;i<m.length;i++)
{
System.out.print(m[i]+” “);
}
}
}

Output of the above program : 

arrays ex1

Explanation of the above program : 

Firstly we have declared an array ‘m’ as int datatype and assigned the elements 12,58,69,87,45,78,25,36 to the variable ‘m’  , and then we used a for loop , starting from 0 till the last element of the array ‘m’. When the ‘i’ value is 0 m[i] that is , m[0] = 0th position of the array ‘m’ (that is 12) will be printed. This is similar to the String fuction ‘indexOf’ in Java . Similarly , when i value was 1 , m[1] = 1st position of array ‘m'(that is 58) will be printed , and in the same way all the elements of the array ‘m’ are printed till the end of the array ‘m’ reaches. Therefore , in the array {12,58,69,87,45,78,25,36} :

m[0] = 12

m[1] = 58

m[2] = 69

m[3] = 87

m[4] = 45

m[5] = 78

m[6] = 25

m[7] = 36

Types of Arrays : 

1.Single Dimensional array

2.Double Dimensional array

1.Single Dimensional array : 

A single dimensional array is that in which only the rows of the array can be declared

Example , double m[] = {2..3,5.2,8.9,5.6};

An example program for 1D array is (i) above

2.Double Dimensional array : 

A double dimensional array is that in which even the columns along with the rows can be declared

Example , int m[2][3] = {{1,5,7,6},{3,8,9,6}};

In the above statement the first [] represent the rows of the array and as we placed 2 in between the first [] , it means that the array ‘m’ is allocated for 2 rows . The second [] represent the columns of the array and as we placed 3 in between the second [] , it means that the array ‘m’ is allocated for 3 columns .

A simple Program to demonstrate the functioning of 2D arrays : 

class Arrays2D
{
static void test()
{
int m[][]={{1,5,6,9},{2,5,9,7},{15,5,78,9}};
for(int i=0;i<3;i++)
{
for(int j=0;j<4;j++)
{
System.out.print(m[i][j]+” “);
}
System.out.println();
}
}
}
Output of the above program :

array ex2

Explanation of the above Program :

Firstly , we have declared a 2D array ‘m’ and by using the for loop , we printed the rows and columns of the array in the form of an array.

How To Input the elements of the Arrays form the User ?

There are three ways to input the elements of the arrays from the user : 

1.By Assignment Method 

Input through assignment method is already explained aboce

2.By Bluej Method

We can input the elements of the array through bluej method , it can be done by declaring the array in the method of the program , Example , 

static void teja(int m[])

In the above statement we have declared the array ‘m’ , in the method ‘teja’ of the program.

Example Program to input the elements of an array through Bluej Mehod : 

class Arrays_Bluejmthd
{
static void test(int m[])
{
System.out.println(“The Entered Array is : “);
for(int i=0;i<m.length;i++)
{
System.out.print(m[i]+” “);
}
}
}
Input : 

array ex3

Output of the program ,

array ex4

2.By Input Stream Reader Method

Example Program to input the elements of the array through Input Stream Method,We should follow all the rules that are required to input the values through Input Stream Method.

import java.io.*;
class InputStreamMthd
{
static void test()throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println(“Enter 10 values of the array one at a time “);
int m[] = new int[10];
for(int i=0;i<m.length;i++)
{
m[i]=Integer.parseInt(br.readLine());
}
System.out.println(“The entered array is “);
for(int j=0;j<m.length;j++)
{
System.out.print(m[j]+” “);
}
}
}

In the above program the highlighted part plays the real role in arranging the elements entered by the user in the array.

Input,

array ex5

Output of the Program , 

array ex6

Basic Operations on Arrays : 

1.Searching

Searching is a process in which the entered value is checked with the already present values to find out whether the entered value is present in the array.

Two types of Searching Methods , 

(i).Linear Searching :

It is the method in which the the elements present in the array are checked from 0th position with the value entered by the user , the checking starts from 0th position, if the element is present in the array , it results as Search Successful else

it results as Search Unsuccessful

Example Program on Linear Searching , 

import java.util.*;
class LinearSearch
{
static void test(int m[])
{
int a=0;
Scanner in=new Scanner(System.in);
System.out.println(“The Array obtained is : “);
for(int k=0;k<m.length;k++)
{
System.out.println(m[k]);
}
System.out.print(“Enter the number which is to be searched :”);
int c=in.nextInt();
boolean isPresent = false;
for(int j=0;j<m.length;j++)
{
if(c==m[j])
a++;

}
if(a>=1)
System.out.println(“Search Successful “);
else
System.out.println(“Search Unsuccessful “);
}
}

Input , 

Entered array = {15,154,48,48,48}

array ex7

Output of the Program , 

Search Successful

Here is the modified program of Linear Search which also shows the place where the search item was present !! :

import java.util.*;
class LinearSearch
{
static void test(int m[])
{
Scanner in = new Scanner(System.in);
System.out.println(“Elements of the Array are : “);
for(int i=0;i<m.length;i++)
System.out.print(m[i]+” “);
System.out.println(“\n\nEnter the number to be searched “);
int c = in.nextInt();
int a = 0;
for(int j=0;j<m.length;j++)
{
if(c==m[j])
{
a++;
}
}
int[] s=new int[a];
int k=0;
for(int j=0;j<m.length;j++)
{
if(c==m[j])
{
a++;
s[k]=j;
k++;
}
}
if(a>=1)
{
System.out.print(“\n\nSearch successful, “+c+” is present at : “);
for(int i=0;i<s.length;i++)
System.out.print(s[i]+” , “);
System.out.print(“Positions(s) “);
}
else
System.out.println(“\n\nSearch unsuccessful ! “);
}
}

(ii)Binary Searching : 

Binary search can only be applied to array whose elements are in either or descending order.

let us , take the array {4,7,8,10,14,21,22,36,62,77,81,91}

Here , there are 11 elements in the array , the process that happens in binary search is :

Step 1, The mid term of the array gets calculated , it will be calculated as (first element + last element)/2 and based on the mid term , the array gets divided into two parts.

Step 2, The value entered by the user gets compared with the mid term let us say, the user entered 22 , now, the mid term i.e., 21<22 … therefore, the search goes to the second half(greater half)

Step 3 , Then , the first half again gets divided into two halves by calculating the mid term of the first half  last 2= mid-1 ; mid2=first+last/2

Step 4 , if the value entered by the user matches with any of the element of the array , then the search is said to be successful , else

the search is said to be unsuccessful.

For better understanding , refer the image below , 

binary search

Example Program for binary search in Java,

import java.util.Scanner;

class BinarySearch
{
public static void main()
{
int c, first, last, middle, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println(“Enter number of elements”);
n = in.nextInt();
array = new int[n];
System.out.println(“Enter ” + n + ” integers”);
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println(“Array entered is : “);
for(int i=0;i<array.length;i++)
System.out.print(array[i]+” “);
System.out.println(“\nEnter value to find”);
search = in.nextInt();

first = 0;
last = n – 1;
middle = (first + last)/2;

while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + ” found at location ” + (middle + 1) + “.”);
break;
}
else
last = middle – 1;

middle = (first + last)/2;
}
if ( first > last )
System.out.println(search + ” is not present in the list.\n”);
}
}

2.Sorting

Sorting is a process in which the elements of the array are either arranged in ascending or descending order.

Two methods of sorting in JAVA , 

(i)Selection Sort : 

It is the method in which the control starts from 0th position and it checks for the lowest value , and replaces it with the value present at the 0th position of the array , in such a way it replaces the elements which are not in order , and thus results in ascending order.

Consider the array {5,1,12,-5,16,2,12,14}  ,

Look at the image for better understanding

selection sort

Finally , 

selection sort 2 is the result

Document By Teja

Others in this Category
document Basic Linux Shell Commands
document Secure Shell
document How to get started with Linux
document How to install Linux on an Unrooted Android smartphone
document Installing Pfsense on Virtualbox, Port forwarding + static IP and ynamic DNS
document Ubuntu 16.04LTS Adding A Printer
document How to Create a Chromebook Recovery USB Drive With a Mac



RSS