Array in Java – With some Interesting Examples


Java / Sunday, July 21st, 2019

Introduction to Array in Java

Array in Java represents a number of variables which occupy contiguous spaces in the memory. Each element in the array is distinguished by its index. All elements in an array must be of the same data type. For example, you cannot have one element of the int data type and another belonging to the boolean data type in the same array.

An array is a collection of elements of the same type that are referenced by a common name. Each element of an array can be referred to by an array name and a subscript or index. To create and use an array in Java, you need to first declare the array and then initialize it.

Syntax:

data type variablename[];

Example:

int numbers[];

The above statement will declare a variable that can hold an array of the int type variables. After declaring the variable for the array, the array needs to be allocated in memory. This can be done using the new operator in the following way:

numbers = new int[10];

This statement assigns ten contiguous memory locations of the type int to the variable numbers. The array can store ten elements. Iterations can be used to access all the elements of the array, one by one.

 

 Program 01

Write a program to input integer elements into an array of size 10 and perform the following operations:
(i) Display largest number from the array.
(ii) Display smallest number from the array.
(iii) Display sum of all the elements of the array.

/**
 *
 * @author Rajib Kumar Saha
 */
import java.util.*;
public class SimpleArrayProg {
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int arr[] = new int[10];
        int i,l,s,sum=0;
        
        System.out.println("Enter 10 integers: ");;
        for(i=0;i<10;i++){
            arr[i] = sc.nextInt();
        }
        
        l=s=arr[0];
        
        for(i=0;i<10;i++){
            sum = sum + arr[i];
            if(arr[i]>l)
                l = arr[i];
            if(arr[i]<s)
                s = arr[i];
        }
        
        System.out.println("Largest element is: "+l);
        System.out.println("Smallest element is: "+s);
        System.out.println("Sum of elements is: "+sum);
    }
}

Output:

Enter 10 integers:
12 45 -54 89 78 75 85 -32 66 -100
Largest element is: 89
Smallest element is: -100
Sum of elements is: 264

 Program 02

Write a program to input 10 words in an array. Arrange these words in descending order of alphabets, using selection sort technique. Print the sorted array.

/**
 *
 * @author Rajib Kumar Saha
 */
import java.util.*;
public class WordsArrangement_Selection {
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        String words[] = new String[10];
        int i, j;
        String temp;
        
        System.out.println("Enter any 10 words: ");
        for(i=0;i<10;i++){
            words[i] = sc.next();
        }
        
        for(i=0;i<10;i++){
            for(j=i+1;j<10;j++){
                if(words[i].compareToIgnoreCase(words[j])<0){
                    temp = words[i];
                    words[i] = words[j];
                    words[j] = temp;
                }
            }
        }
        
        System.out.println("The sorted words after selection sort technique: ");
        for(i=0;i<10;i++){
            System.out.println(words[i]);
        }
    }
}

Output:

Enter any 10 words:
Ram
Shyam
Jadhu
Modhu
Krishna
John
Ryan
Sachin
Sourav
Ajhar
The sorted words in descending order after selection sort technique:
Sourav
Shyam
Sachin
Ryan
Ram
Modhu
Krishna
John
Jadhu
Ajhar

 Program 03

Write a program to input 10 names in an array. Arrange these names in descending order of alphabets, using the bubble sort technique.

/**
 *
 * @author Rajib Kumar Saha
 */

import java.util.Scanner;
public class NamesArrangement_Bubble {
     public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        String names[] = new String[10];
        int i, j;
        String temp;
        
        System.out.println("Enter any 10 names: ");
        for(i=0;i<10;i++){
            names[i] = sc.next();
        }
        
        for(i=0;i<10;i++){
            for(j=0;j<9-i;j++){
                if(names[j].compareToIgnoreCase(names[j+1])<0){
                    temp = names[j];
                    names[j] = names[j+1];
                    names[j+1] = temp;
                }
            }
        }
        
        System.out.println("The sorted words in descending order after bubble sort technique: ");
        for(i=0;i<10;i++){
            System.out.println(names[i]);
        }
    }
}

Output:
Enter any 10 names:
Ram
Shyam
jadhu
modhu
Krishna
Ryan
Ajhar
Rinku
Nilu
Tinku
The sorted words in descending order after bubble sort technique:
Tinku
Shyam
Ryan
Rinku
Ram
Nilu
modhu
Krishna
jadhu
Ajhar

 Program 04

Write a program to initialize the Seven Wonders of the World along with their locations in two different arrays. Search for a name of the country input by the user. If found, display the name of the country along with its Wonder, otherwise display “Sorry Not Found”.

/**
 *
 * @author Rajib Kumar Saha
 */
import java.util.*;
public class SevenWonders {
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        String wonders[] = {"Chichen Itza", "Christ The Redeemer", "Tajmahal", 
            "Great Wall of China", "Machu Picchu", "Petra", "Colosseum"};
        String country[] = {"Mexico", "Brazil", "India", "China", 
            "Peru", "Jordan", "Italy"};
        String s;
        int i, flag = 0;
        
        System.out.print("Enter the country to be Searched: ");
        s = sc.next();
        
        for(i=0;i<7;i++){
            if(s.equalsIgnoreCase(country[i])){
                flag = 1;
                break;
            }
        }
        if(flag == 1){
            System.out.println(country[i]+ " - " +wonders[i]);
        }else{
            System.out.println("Sorry Not Found!!!");
        }
    }
}

Output:

Enter the country to be Searched: India
India – Tajmahal

Again after running

Enter the country to be Searched: England
Sorry Not Found!!!

 Program 05

Write a program to accept the year of graduation from school as an integer value from the user. Using the Binary Search technique on the sorted array of integers given below:
Output the message “Record exists” If the value input is located in the array. If not, output the message “Record does not exists”.
{1982, 1987, 1993, 1996, 1999, 2003, 2006, 2007, 2009, 2010}

/**
 *
 * @author Rajib Kumar Saha
 */

import java.util.*;
public class GraduationYear {
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int year[]={1982, 1987, 1993, 1996, 1999, 2003, 2006, 2007, 2009, 2010};
        int n,l,h,mid,flag=0;
        
        System.out.print("Enter year: ");
        n = sc.nextInt();
        l = 0;
        h = year.length -1;
        while(l<=h){
            mid = (l+h)/2;
            if(n>year[mid]){
                l = mid + 1;
            }
            else if(n<year[mid]){
                h = mid -1;                
            }
            else{
                flag = 1;
                break;
            }
        }
        if(flag == 1){
            System.out.println("Record exists");
        }else{
            System.out.println("Record does not exists");
        }
    }
}

Output:

Enter year: 2007
Record exists

Again after running

Enter year: 1992
Record does not exists

 

<< Previous     Next>>

 

 ;

Leave a Reply

Your email address will not be published. Required fields are marked *