Array in Java

Array in Java

Array in Java


Array in Java

What is an Array?

The contiguous memory location is called Array. Actually, an array is a plural, so that we can simply read the variable and recognize that it is a collection of data. It is an object in Java that holds a fixed number of values of a single data type. Java Array is a data structure in java that can hold one or more values in a single variable. An array is declared like a variable except that we are attaching the square brackets [], which can be used in two parts, either before the name of the variable or after the name of the variable.

Why do we need an array?

Suppose you want to store the name of 500 employees, so we need to define 500 variables but this could be a very big problem so we need a better solution for defining 500 names for employees, that is why need an array.


Java array index starts at 0.
Array

Write down some points on Array.

  • The array is a homogeneous data structure that stores elements of a similar type.
  • All the elements of an array share the same name.
  • Each element of an array is treated separately and store in a different memory location.
  • Each value stored, in an array, is known as an element and all elements are indexed. The first element added, by default, gets 0 indexes. That is, the 6th element added gets an index number of 5.
  • Java checks the boundary array. If the index goes beyond, an exception will generate.
  • Elements of an array can be retrieved by their index number.
  • Java arrays are objects. With methods, the array elements can be manipulated.
  • Memory allocation in Java arrays are dynamically by using the new operator.
  • Arrays can be multidimensional.
  • Once the size of an array is defined, it cannot grow it or shrink it at run time. 


Declaring an Array

Int number [];
The above statement just declares an array object, but it doesn’t have any elements. An array is a null object. It must be instantiated using the following statement:
Number=new int [10];
In Java, every object is instantiated using the ‘new’ keyword.

Initialization of one dimensional array

Int arr[] = {5, 6, 1, 9, 3};
Array arr[] contains five elements in it.
Types Of Array

Types of Array in java

There are two types of array.

  1. Single Dimensional Array: Int arr[]=new int[10];
  2. Multidimensional Array: Int arr[][]=new int[5][5];

Java Array Literals

Sometimes we need predefine values for the array, so Java gives us a better solution for that, so we can use an array literal. Here is how we cab defines an array literal:
int[] number = {5, 4, 8, 9, 12, 6};
or
int number[] = {1,2,3,4,5,7,8};
Here we don’t need a new operator for defining the array.
So here values that are stored inside the curly brackets are called an array literal.
For defining String array we can do so as follows
String name[] = {“Alam”, “Binny”, Rakesh”, “Salim”, “Sachin”};

Some examples:

Simple Array print

import java.io.*;
public class SimpleArrayPrint
{
    public static void main(String args[])throws IOException
    {
            InputStreamReader ab=new InputStreamReader (System.in);
            BufferedReader br=new BufferedReader (ab);
            int n[]=new int[10];
            int i;
            System.out.println ("Enter Five numbers:");
            for (i=0;i<5;i++)
            {
                                                                n[i]=Integer.parseInt(br.readLine());
                                                }
                                                System.out.println ("Out Put");
                                                for (i=0;i<5;i++)
                                                {
                                                                System.out.print (n[i]+" ");
                                                }
                }
}

Example
Array Summation print
import java.io.*;
public class SumArrayPrint
{
    public static void main(String args[])throws IOException
    {
            InputStreamReader ab=new InputStreamReader(System.in);
            BufferedReader br=new BufferedReader(ab);
            int n[]=new int[10];
            int i,s=0;
            System.out.println("Enter ten numbers:");
            for(i=0;i<10;i++)
            {
                                                                n[i]=Integer.parseInt(br.readLine());
                                                }
                                                System.out.println("Out Put");
                                                for(i=0;i<10;i++)
                                                {
                                                                s=s+n[i];
                                                }
                                                System.out.println("Sum="+s);
                }
}

Output

Enter ten numbers:
2
3
65
66
5
8
12
4
54
5
Out Put
Sum=224

Example

Array program of Odd and Even

import java.io.*;
public class ArrayOddEven
{
    public static void main(String args[])throws IOException
    {
            InputStreamReader ab=new InputStreamReader(System.in);
            BufferedReader br=new BufferedReader(ab);
            int a[]=new int[10];
            int ev[]=new int[10];
            int od[]=new int[10];
            int i,j,k;
            j=k=0;
            System.out.println("Enter Five elements:");
            for(i=0;i<10;i++)
            {
                a[i]=Integer.parseInt(br.readLine());
            }
            for(i=0;i<10;i++)
            {
                if(a[i]%2==0)
                {
                  ev[j]=a[i];
                  j++;
                }
                else
                {
                    od[k]=a[i];
                    k++;
                }
            }
            System.out.println("Even Array");
            for(i=0;i<j;i++)
            {
                System.out.println(ev[i]);
            }
            System.out.println("Odd Array");
            for(i=0;i<k;i++)
            {
                System.out.println(od[i]);
            }
    }
}
Output
Enter Five elements:
4
5
6
3
2
1
7
8
9
2
Even Array
4 6 2 8 2
Odd Array
5 3 1 7 9

Write a java program to print all the prime numbers from an array

import java.util.*;
public class Array1
{
    public static void main(String args[])
    {
        int n[]=new int[10];  //[9, 7, 6 ,5........]
        int i, f, j;  
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter number:");
        for(i=0; i<10; i++)
        {
            n[i]=sc.nextInt();
        }
        System.out.println("Output");
        for(i=0; i<10; i++)
        {
            f=1;
            // Prime number check
            for(j=2; j<n[i]; j++)
            {
                if(n[i] % j == 0)
                {
                    f=0;
                    break;
                }
            }
            if(f == 1)
            {
                System.out.println(n[i]);
            }
        }       
    }
}

Double Dimension Array Example

import java.io.*;
class DBLArray
{
public static void main(String arg[])throws IOException
{
int n[][]=new int[3][3];
int i,j;
InputStreamReader ab=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(ab);
System.out.println("Enter Data :");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
n[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("OutPut Data");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(n[i][j]+" ");
}
System.out.println("");
}
}
}

Java Array Exception example

public class ArrayException
{
    public static void main(String args[])
    {
        int n[]={5,6,7,8,9};
        int i,m;
        try
        {
            m=n[4];
            System.out.println(m);
        }
        catch(Exception e)
        {
            System.out.println("O no not again");
        }
        finally
        {
            System.out.println("Must execute");
        }
        System.out.println("Thank you");
    }
}

Java program for an array with a method

public class ArrayFunction
{
    int i, j, f;
    int searchResult(int m[], int s)
    {
        f=0;
        for(i=0; i<m.length; i++)
        {
            if(s==m[i])
            {
                f=1;
                break;
            }
        }
        return f;
    }


    public static void main(String args[])
    {
        int n[]={10, 3, 6, 5, 11, 7, 1, 17, 8, 9};
        int se=7, flag;
        ArrayFunction ob=new ArrayFunction();
        flag=ob.searchResult(n, se);
        if(flag==1)
        {
            System.out.println("Found");
        }
        else
        {
            System.out.println("Not Found");
        }

    }
}
In the above program, we have created one method of searching int searchResult(int m[], int s), in which we have send array and one value to search. 

Some more program

Binary Search in Java


Learn Java
Become An Awesome Java Professional
ICSE 2016 and ISC 2016 Computer Application Q & A

ICSE 2016 and ISC 2016 Computer Application Q & A

ICSE 2016 and ISC 2016 Computer Application Q & A


Q. What is a class variable?
Ans: Static keyword in Instance variables is called a class variable. For every object there is just one copy of the variable made.
Ex.
class Summation
{
        static  int a;
        static  int b;
       
}

Q. What is significance of import java.io.* in your program?
Ans: The line imports all the classes of the java.io package into the program.

Q. State the two kinds of data types.
Ans: The two kinds of data types in Java are primitive and reference data types.

Q. Define impure function.
Ans: Impure Function: A function that brings about a change in the argument that it receives. Its arguments will always be reference types. It may or may not return value. In other words, an impure function brings about a change in the state of the function. This change in state is called the side effect of calling an impure function.
Example:
Static void count(Number num) 
{
num.counter=num.counter+1;
}


Q. What are comments? Name the different types.
Ans: Comments are statements which enhances the readability and understanding of the program. They are not part of the program.
The different types are: single line (//….), multiple line (/* … */) and documenting comment (/**….*/).

Q. Define Encapsulation.
Ans: The wrapping of data and function together into a single unit is called Encapsulation.

Q. Name any three OOP’s principles
Ans: Inheritance,  Polymorphism and Encapsulation

Q. Define Object with example.
Ans:  Object: An instance of a class called Object. Table is an instance of class Furniture.
Class: Blue print of an object is called Class. Example, mango, apple and orange are members of the class fruit.

Q. What is wrapper class? Give example.
A wrapper class is a class which wraps a primitive data type. Example Double, Float, Integer

Q. What is meant by private visibility of a method?
Ans:  The visibility of private method restricted to class itself. It is not visible to anywhere outsite the class.

Q. What is a variable?
Ans: A variable is a named memory location whose value can change. Example int a,b;

Q. What is the use of return keyword?
Ans: A return keyword is used to return any value from a function. It denotes the end of a function.

Q. What is call by value?
Ans: In call by value arguments are passed by the value, which means that a copy of the arguments is passed to the method can make changes to the value of this copy but can not change the values of the original variables in the calling method.

Q. What is meant by an infinite loop? Give an example.
Ans: An infinite loop is a loop whose test condition is always true. This type of loop never ends by itself. For example:
for(i=1;i>0;i++)
{
System.out.println(“Hello”);
}

Q. State any two objectives of using Arrays.
Ans:  1. Use hold elements in contiguous memory location. 2. Arrays are used to group storage locations.


Become An Awesome Java Professional
Java program matrix diagonal sum without mid value repetition

Java program matrix diagonal sum without mid value repetition

Java program matrix diagonal sum without mid value repetition
import java.util.*;
/**
 *
 * Double dimension array diagonal addition
 * Each diagonal sum without repetition of mid value
 * InspireSkills : Khurshid Md Anwar
 *
 */
public class MatrixAddWithoutRepetingMidValue
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int i,j,s1,s2,r,c,a;
        System.out.println("Enter Row or Col");
        r=sc.nextInt();
        int n[][]=new int[r][r];
        s1=s2=0;
        System.out.println("Enter values into Matrix");
        for(i=0;i<r;i++)
        {
            for(j=0;j<r;j++)
            {
                n[i][j] = sc.nextInt();
            }

        }
        System.out.println("Print Matrix");
        for(i=0; i<r; i++)
        {
            for(j=0; j<r; j++)
            {
                System.out.print(n[i][j] + " ");
            }
            System.out.println();
        }
        for(i=0; i<r; i++)
        {
            s1 = s1 + n[i][i];
        }
        c = r-1;
        for(i=0;i<r;i++)
        {
            s2 = s2 + n[i][c];
            c--;
        }
        // Excluding the repeating mid value
        s2 = s2 - n[r/2][r/2];
        System.out.println("Mid Value="+n[r/2][r/2]);
        System.out.println("First Diagonal sum=" + s1);
        System.out.println("Second Diagonal sum=" + s2);
        System.out.println("Sum of Two diagonal without repeating value is "+ (s1+s2));
    }
}

Output
Enter Row or Col
3
Enter values into Matrix
9
8
7
6
5
4
3
2
1
Print Matrix
9 8 7 
6 5 4 
3 2 1 
Mid Value=5
First Diagonal sum=15
Second Diagonal sum=10
Sum of Two diagonal without repeating value is 25

Few more program

java program for isbn number

java program for isbn number

ISBN IN JAVA Program


ISBN IN JAVA Program


Almost every book carry number called ‘The International Standard Book Number (ISBN)’ which is a unique number. By this number, we can find any book. It is a 10 digit number. The ISBN is legal if 1*digit1 + 2*digit2 + 3*digit3 + 4*digit4 + 5*digit5 + 6*digit6 + 7*digit7 + 8*digit8 + 9*digit9 + 10*digit10 is divisible by 11.
Example: For an ISBN "1259060977"
Sum = 1*10 + 2*9 + 5*8 + 9*7 + 0*6 + 6*5 + 0*4 + 9*3 + 7*2 + 7*1 = 209
Now divide it with 11 = 20%/11 = 0. If the resultant value will be Zero then it is a valide ISBN.
Write a program to:
(i) input the ISBN code as a 10-digit number
(ii) If the ISBN is not a 10-digit number, output the message “Illegal ISBN” and terminate the program
(iii) If the number is 10-digit, extract the digits of the number and compute the sum as explained above.

If the sum is divisible by 11, output the message “Legal ISBN”. If the sum is not divisible by 11, output the message “Illegal ISBN”.

Solution

import java.io.*;

/**
* Khurshid Md Anwar #inspireSkill
*/
class ISBNumber {

    public static void main(String[] args) throws IOException {
        long isbnNumber;
        int s = 0, i, t, d, dNumber;
        String st;
        // Input a 10-digit ISBN number
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(in);
        System.out.print("Input a 10-digit ISBN number: ");
        isbnNumber = Long.parseLong(br.readLine());

        // check the length is 10, otherwise, exit from the program
        st = "" + isbnNumber;
        if (st.length() != 10) {
            System.out.println("Illegal ISBN");
            return;
        }
        // : For an ISBN 1259060977
        //S = 1*10 + 2*9 + 5*8 + 9*7 + 0*6 + 6*5 + 0*4 + 9*3 + 7*2 + 7*1 = 209
        // which is divisible by 11.
        // compute the s of the digits
        s = 0;
        for (i = 0; i < st.length(); i++) {
            d = Integer.parseInt(st.substring(i, i + 1));
            dNumber = i + 1;
            t = dNumber * d;
            s += t;
        }

        // check the number s is divisible by 11 or not
      
        if ((s % 11) != 0) {
            System.out.println("Illegal ISBN");
        } else {
            System.out.println("Legal ISBN");
        }
    }
}

Output

Input a 10-digit ISBN number: 1259060977
Legal ISBN
Input a 10-digit ISBN number: 1245876589
Legal ISBN
Input a 10-digit ISBN number: 1234567890
Illegal ISBN

Click for more number program


Core Java: An Integrated Approach, New: Includes All Versions upto Java 8