×

How to take Array Input in Java

In this tutorial, we will learn about how to take array input in Java. So, before taking inputs let us know what an array is first.

Array:

An array is a collection or group of elements that are stored under a single variable name and same data type. All the collection of the data in Java is termed as objects or collection framework. An array comes under the category of objects. Array list comes under the category of collection framework. We can learn array list in further units. Let us discuss about array now.

Delimiters

Delimiters are certain symbols that are uniquely designed for a specific topic.

Example: Square Brackets ([]) are the delimiters of arrays

Curly braces ( { } ) are the delimiters for a function or class body

Types of Arrays

  1. One (or) Single Dimension Array
  2. Multi-Dimensional Array

They contain two different types of arrays. They are:

  • Two Dimensional Arrays also known as 2D Array
  • Irregular Multi-Dimensional Arrays also known as Jagged Array

One Dimensional Array (1D Arrays)

If the delimiters also known as square brackets used are only pair, then those kinds of arrays are known as One Dimensional arrays.

Syntax:

First syntax is:

Data type variable_name [] = new data type [array size] ;

Example:

int a [ ] = new int [5] ;
char c [ ] = new char [5] ;

Second syntax is:

Data type [ ] variable_name = new data type [ array size] ;

Example:

int [ ] a = new int [5] ;
char [ ] c = new char [5] ;
float [ ] f = new float [5] ;

Third Syntax is:

Data type [ ] variable_name ;
Variable_name =  new data type [ array size] ;

Example:

int [ ] a ;
a = new  int [50] ;
byte [ ] b ;
b = new byte [ 100 ] ;
double [ ] d;
d = new double [ 200 ] ;

Fourth Syntax is:

Data type  variable_name [ ] ;
Variable_name =  new data type [ array size] ;

Example:

int a  [ ];
a = new  int [50] ;
byte  b [ ] ;
b = new byte [ 100 ] ;
double  d [ ];
d = new double [ 200 ] ;

Fifth Syntax is:

Data type variable_name [ ]  = { element 1 / object 1 , element 2 / object 2………… element n / object n } ;

Example:

int a [ ] = { 1 , 2 , 3 , 4 } ;
float f [ ] = { 1.1 , 1.2 , 1.3 , 1.4 , 1.5 } ;

These are the syntax of the one-dimensional arrays. Now let us see how a program works using one dimensional array.

Now let us understand one dimensional array with the help of a program

Rules:

  1. Every class name should start with Capital Letter
  2. Name of Class with main should be the program or file name

Example:

File Name: Arr.java

import java.io. *;
import java.lang.*;
import java.util.*;
// This is program for implementation of one dimensional arrays
class Arr


{


public static void main(String args[])


{


// Using the fifth syntax as shown above


// Array is assigned to a variable a
// The input taken here is in a static way
int a [] = {648,726,992,789,600};
int len = a.length;
System.out.println(" The length of array a is : "+len);




int i=0;
while (i<len)
{
System.out.println("The element at position "+i+" is "+a[i]);
// Incrementation
i=i+1;
}


} // main
} // class

OUTPUT

C:\new\java>javac Arr.java


C:\new\java>java Arr
 The length of array a is: 5
The element at position 0 is 648
The element at position 1 is 726
The element at position 2 is 992
The element at position 3 is 789
The element at position 4 is 600

Explanation:

  • The input is given in static way ( input is already given inside the program)
  • The array a is stored in static area
  • This is the concept of storing elements of array in static way
  • To store in dynamic way, we need to use java . util package

Advantages:

  • Only limited amount of memory is used for creating this array
  • No wastage of memory

Disadvantages:

  • On every compilation, same answer is going to appear on the output screen.
  • Not called as a good programmer.
  • Written in a static way.

To remove the problems that have been raised in the above way of programming, we will write a program using dynamic way of programming.

Here we are going to use java.util package to perform dynamic way of programming. Here dynamic programming means allocation of values to the given array during run time is dynamic programming in this concept.

Rules:

  1. Every class name should start with Capital Letter
  2. Name of Class with main should be the program or file name

Example:

File name: Arr.java

import java.io.*;
import java.lang.*;
import java.util.*;
// this is program for implementation of one dimensional arrays
class Arr


{


public static void main(String args[])


{
// Creation of object for Scanner class
// this is done taking dynamic inputs
Scanner sc = new Scanner(System.in);
// Array Declaration
int a [ ] = new int [10];


// Size of array we require declaration


int n;
System.out.println("Enter the size of array we wanted to create:");
n= sc.nextInt();


System.out.println("Enter the "+n+" array elements");


for(int i=0;i<n;i++)
{
// Array Values declaration


a[i]=sc.nextInt();


}


System.out.println("The "+n+" array elements are :");


for(int i=0;i<n;i++)
{
System.out.printf("a[%d] = %d \n",i,a[i]);
}


}
}

Output 1:

First way of giving array inputs.

The inputs are given line by line.

C:\new\java>javac Arr.java


C:\new\java>java Arr
Enter the size of array we wanted to create:
5
Enter the 5 array elements
1
2
3
4
5
T he 5 array elements are :
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
a[4] = 5


C:\new\java>

Output 2:

Second way of giving array inputs.

All the input elements are written on the same line.

C:\new\java>javac Arr.java


C:\new\java>java Arr
Enter the size of array we wanted to create:
7
Enter the 7 array elements
77 29 674 159 143 69 000
T he 7 array elements are :
a[0] = 77
a[1] = 29
a[2] = 674
a[3] = 159
a[4] = 143
a[5] = 69
a[6] = 0


C:\new\java> 

Java is not like python. Based on the usage of in-built functions python takes inputs as line by line or sideways.

But in Java same code is written for taking both types of inputs.

Example:

PYTHON:
Inputs = 1 2 3 4 5
The code to be written is:
l = list(map(int , input().split()))
Inputs =
1
2
3
4
5
The code to be written is :
L =[]
for i in range(5):
        l.append(int(input()))


For both above inputs the Java code is:
Scanner sc = new Scanner(System.in);
int a [ ] = new int [5];
for (int i =0; i <5;i++)
{
a[i] = sc.nextInt();
}

Explanation:

  • The input is given in a dynamic way (Run time).
  • The array a is stored in heap or class area.
  • This is the concept of storing elements of array in static way

Advantages:

  • The outputs are changed after every compilation.
  • Different test cases can be run by using this kind of program.

Disadvantages:

  • Memory wastage takes place
  • The memory is allocated in a static way.

This is about how inputs are taken for an array which is one dimensional.

Now let us learn how array inputs are taken in a multi-dimensional array.

Multi-Dimensional Arrays

If the delimiters also known as square brackets used are more than a pair, then those kinds of arrays are known as multi-Dimensional arrays.

Two-Dimensional Array

If the delimiters also known as square brackets used are two pairs, then those kinds of arrays are known as Two Dimensional arrays.

Syntax:

First Syntax is:

Data type variable_name [] [] = new data type [ array row size] [ array column size] ;

Example:

int a [ ] [ ] = new int [5] [5] ;
char c [ ] [ ] = new char [5] [5] ;

Second Syntax is:

Data type [ ] [ ] variable_name = new data type [ array row size] [ array column size] ;

Example:

int [ ] [ ] a = new int [5] [5] ;
char [ ] [ ] c = new char [ 5] [5] ;
float [ ] [ ] f = new float [5] [5] ;

Third Syntax is:

Data type [ ] [ ] variable_name ;
Variable_name =  new data type [ array row size] [ array column size] ;

Example:

int [ ] [ ] a ;
a = new  int [50] [50] ;
byte [ ] [ ] b ;
b = new byte [ 100 ]  [ 100 ] ;
double [ ] [ ] d;
d = new double [ 200 ] [ 200 ] ;

Fourth Syntax is:

Data type  variable_name [ ] [ ] ;
Variable_name =  new data type [ array row size] [ array column size] ;

Example:

int a  [ ] [ ];
a = new  int [50] [50] ;
byte  b [ ] [ ] ;
b = new byte [ 100 ] [ 100 ] ;
double  d [ ] [ ];
d = new double [ 200 ] [ 200 ] ;

Fifth Syntax is:

Data type variable_name [ ] [ ] = {
{ row element 1 / row object 1 , row element 2 / row object 2………… row element n / row object n } ,
{column element 1 / column object 1 , column element 2 / column object 2………… column element n / column object n }
};

Example:

int a [ ] = { 
{1 , 2 , 3 , 4 },
{5 , 6 , 7 , 8 }
} ;
float f [ ] = { 
{1.1 , 1.2 , 1.3 , 1.4 , 1.5 },
{0.1 , 0.2 , 0.4 , 0.3 , 0.5}
} ;

These are the syntax of the two-dimensional arrays. Now let us see how a program works using two dimensional arrays.

Now let us understand two dimensional arrays.

Example:

File Name: Arr.java

// A program for two dimensional arrays in a static way.
import java.io.*;
import java.lang.*;
import java.util.*;
// This is program for implementation of two dimensional arrays
class Arr


{


public static void main(String args[])


{
// Using the fifth syntax as shown above


// Array is assigned to a variable a
// The input is already taken here is in a static way


int a[] [] = {
{1,2,3,4,5},
{6,7,8,9,0}
};


int len = a . length;
System.out.println("The Length of the given array’s row length is:" +len);


for(int i = 0; i<2; i++)
{
for(int j = 0; j<5; j++)
{
System.out.printf("a [%d] [%d] = %d\n",i,j,a[i][j]);
}
}


}
}

Output:

C:\new\java>javac Arr.java


C:\new\java>java Arr
The Length of the given array’s row length is:2
a [0] [0] = 1
a [0] [1] = 2
a [0] [2] = 3
a [0] [3] = 4
a [0] [4] = 5
a [1] [0] = 6
a [1] [1] = 7
a [1] [2] = 8
a [1] [3] = 9
a [1] [4] = 0


C:\new\java>

Explanation:

  • This arrays is a two dimensional array of type a[2][5]
  • This means that the given array has two rows and five columns
  • The input is given in static way ( input is already given inside the program)
  • The array a is stored in static area
  • This is the concept of storing elements of array in static way
  • To store in dynamic way, we need to use java . util package

Advantages:

  • Only limited amount of memory is used for creating this array
  • No wastage of memory

Disadvantages:

  • On every compilation, same answer is going to appear on the output screen.
  • Not called as a good programmer.
  • Written in a static way.

Showing the Array in Matrix Form

Example:

import java.lang.*;
import java.util.*;
// This is program for implementation of two dimensional arrays
// Printing the given array in a matrix form
class Arr


{


public static void main(String args[])


{
// Using the fifth syntax as shown above


// Array is assigned to a variable a
// The input is already taken here is in a static way


int a[] [] = {
{1,2,3,4,5},
{6,7,8,9,0}
};


int len = a . length;
System.out.println("The Length of the given array's row is:" +len);
len =a[0].length;
System.out.println("The Length of the given array's column is:" +len);
for(int i = 0; i<2; i++)
{
for(int j = 0; j<5; j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}


}
}

Output:

C:\new\java>javac Arr.java


C:\new\java>java Arr
The Length of the given array's row is:2
The Length of the given array's column is:5
1 2 3 4 5
6 7 8 9 0


C:\new\java>

This is how a two-dimensional array is printed in a matrix format. Now let us see dynamic memory allocation.

The two blocks that is defined inside the array can be defined as rows and columns.

Note:

1 2 3
4 5 6
7 8 9
This is a array of size of 3 X 3.
This can be represented as matrix 
So we can consider that the two dimensional arrays as a matrix 
Its indices can be considered as rows and columns

Example:

File Name: Arr.java

Rules:

  1. Every class name should start with Capital Letter
  2. Name of Class with main should be the program or file name

// A program for two dimensional arrays in a dynamic way.

// A program for two dimensional arrays in a dynamic way.
import java. io.*;
import java. lang.*;
import java. util.*;
// This is program for implementation of two dimensional arrays
// Printing the given array in a matrix form
class Arr


{


public static void main(String args[])


{
// Using the fifth syntax as shown above


// Array is assigned to a variable a
// The input is already taken here is in a dynamic way


Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of row:");


int r =sc.nextInt();


System.out.println("Enter the number of columns:");


int c = sc.nextInt();


int a [] [] = new int [r] [c] ;


// This method helps in saving the memory


//Inserting values into the array
System.out.println("Please enter the numbers for arrays");


for(int i=0; i<r;i++)
{
for(int j=0;j<c;j++)
{
a[i][j] = sc.nextInt();


}


}


System.out.println("The Two Dimensional array in matrix form is");
for(int i=0;i<r;i++)


{
for(int j=0;j<c;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}








} // main


} // Arr

Output:

C:\new\java>javac Arr.java


C:\new\java>java Arr
Enter the number of row:
3
Enter the number of columns:
3
Please enter the numbers for arrays
1 2 3 4 5 6 7 8 9


The Two Dimensional array in matrix form is
1 2 3
4 5 6
7 8 9
______________________________________________________________________________
C:\new\java>javac Arr.java


C:\new\java>java Arr
Enter the number of row:
3
Enter the number of columns:
3
Please enter the numbers for arrays
1
2
3
4
5
6
7
8
9
The Two Dimensional array in matrix form is
1 2 3
4 5 6
7 8 9


C:\new\java>

EXPLAINATION:

In Java the inputs like

All inputs in single line : 1 2 3 4 5 6 7 8 9

OR

All inputs line by line :

1
2
3
4
5
6
7
8
9


All these kind of inputs are taken in the same way
 


for(int i=0; i<r;i++)
{
for(int j=0;j<c;j++)
{
a[i][j] = sc.nextInt();


}


}

Explanation

  • The input is given in a dynamic way (Run time).
  • The array a is stored in heap or class area.
  • This is the concept of storing elements of array in static way

Advantages

  • The outputs are changed after every compilation.
  • Different test cases can be run by using this kind of program.

Disadvantages

  • Memory wastage takes place
  • The memory is allocated in a static way.

Three Dimensional Arrays

If the delimiters also known as square brackets used are three pairs, then those kinds of arrays are known as Three Dimensional arrays.

Let us directly jump into the program for the explanation of Three-Dimensional arrays.

They are a bit complex to use. So be careful while using three dimensional arrays

Example:

File Name: Arr.java

// A program for three dimensional arrays in a dynamic way.
import java. io.*;
import java. lang.*;
import java. util.*;
// This is program for implementation of three dimensional arrays
// Printing the given three dimensional array along with indices
class Arr


{


public static void main(String args[])


{
 int a [][][] = { { { 11, 12 }, { 23, 24 } }, { { 35, 36 }, { 47, 48 } } };


int i, j, k;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for(k=0;k<2;k++)
{
System.out.printf("a[%d] [%d] [%d] =%d\n",i,j,k,a[i][j][k]);
}
}
}




} // main


} // Arr

Output:

C:\new\java>java Arr
a [0] [0] [0] =11
a [0] [0] [1] =12
a [0] [1] [0] =23
a [0] [1] [1] =24
a [1] [0] [0] =35
a [1] [0] [1] =36
a [1] [1] [0] =47
a [1] [1] [1] =48


C:\new\java>

This is how array inputs are taken into the Java arrays concept.


Related Topics

Kong Java Client

Kong is an Organization Microservice Programming interface gateway. Kong gives an adaptable deliberation layer that safely oversees correspondence among clients and microservices by means of a Programming interface. Otherwise called...

6 minutes read.

Spliterator in Java 8

In this tutorial, we will understand the meaning of spliterator in java 8. It is just like any other iterator available in java used to traverse the elements of either...

4 minutes read.

Java Transient Keyword

An object in Java can be turned into a stream of bytes using serialization. The data of the instance and the kind of data saved in that instance are both...

3 minutes read.

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.

Balanced Parentheses in Java

One of the frequent programming issues, commonly referred to as the Balanced brackets issue, is the problem with the balanced parenthesis. Interviewers frequently provide this task, in which we must...

5 minutes read.

Perfect Number Program in Java

Perfect Number Program in Java A perfect number is a number whose sum of all the factors, excluding the number itself, is equal to the number. For example, 28 is a...

4 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Transaction Management in java

Definition: A database application is an application that is running against a relational database and executes one or more transactions. A transaction is an executing program that contains some database operations,...

4 minutes read.

CRC Program in Java

The acronym CRC stands for Cyclic Redundancy Check. It is invented by W. Wesley Peterson in 1961. It is an error detection technique that detects errors in digital networks (also...

5 minutes read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.

Java array list remove time complexity

Java: We know that java is one of the programming languages. The main feature of java which is not in C or object oriented programming language is platform independence. Not only the...

7 minutes read.

Java String Reader

StreamReaderClass: This class is present in the java.io package. It is a character stream in which string act as a source.This method provides to read characters from a string. Character Stream: This class...

3 minutes read.

Program to find and replace characters on string in java

In JAVA, Strings are immutable. To overcome this Java String class contains a lot of methods to do operations on Strings. One such method is replace method. String Replace It returns a...

3 minutes read.

Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving. Problem of Railway Station The...

6 minutes read.

Java Queue

The Java.util package has the interface Queue, which does extend the Collection interface. It is used to protect the parts that are managed using the FIFO approach. Being an interface, the...

5 minutes read.

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format. For example, if someone converts the string “Tutorial & Example”...

3 minutes read.

How to run java program in ubuntu

To run the java programming in ubuntu, we need to follow several steps: Let's see the process. Step1: Install the Java compiler or JDK to the system. To run the java program, we...

3 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

Parallel Arrays Sort in Java

Sorting is a technique of arranging a sequence of numbers in ascending order, that is, the first number being lowest and gradually incrementing the numbers such that the last number...

7 minutes read.