• Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
•
It is a homogeneous data.
•
An array is a group of like-typed variables
that are referred to by a common name.
•
how to access an array - through
index(position)
•
Index always starts with zero(0).
Three steps
- Declare
and create memory locations
- Put
values
- Print
the values
Syntax
to Declare an Array in Java
dataType arr[]=new datatype[size];
datatype arr[size];
datatype arr[];
Example of Java Array
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and initialization
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Two Dimension Arrays in Java
The Java
Program is a 2D array organized as matrices which can be represented as the
collection of rows and columns. It is possible to define an array with more than
one dimension. Instead of being accessed by providing a single index, a
multidimensional array is accessed by specifying an index for each dimension.
The
declaration of the multidimensional array can be done by adding [] for
each dimension to a regular array declaration. For instance, to make a
2-dimensional int array, add another set of brackets to the declaration, such
as int[][]. This continues for 3-dimensional arrays (int[][][]) and so
forth.
Syntax:
Datatype
variable_name [ ] [ ] ;
(or)
Datatype [ ][ ] variable_name ;
Jagged-Array in Java
A jagged
array is an array of arrays such that member arrays can be of different row
sizes and column sizes. Jagged subarrays may also be null. For instance, the
following code declares and populates a two-dimensional int array whose first
subarray is of four lengths, the second subarray is of three lengths and the last
subarray is a fours length array:
Example:
int [] [] a = {{10,20,30,40}
, { 10,20,30 } , { 10,20,30,50 } } ;
package Array_Programs;
public class Array_sample {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5};
// loop through the array
// using for loop
System.out.println("Using for Loop:");
for(int i = 0; i < age.length; i++) {
System.out.println(age[i]);
}
}
/*class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5};
// loop through the array
// using for loop
System.out.println("Using for-each Loop:");
for(int a : age) {
System.out.println(a);
}
}
}
class Main {
public static void main(String[] args) {
int[] numbers = {2, -9, 0, 5, 12, -25, 22, 9, 8, 12};
int sum = 0;
Double average;
// access all elements using for each loop
// add each element in sum
for (int number: numbers) {
sum += number;
}
// get the total number of elements
int arrayLength = numbers.length;
// calculate the average
// convert the average from int to double
average = ((double)sum / (double)arrayLength);
System.out.println("Sum = " + sum);
System.out.println("Average = " + average);
}
}
//Multidimensional Array
class MultidimensionalArray {
public static void main(String[] args) {
int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7},
};
for (int i = 0; i < a.length; ++i) {
for(int j = 0; j < a[i].length; ++j) {
System.out.println(a[i][j]);
}
}
}
}
class MultidimensionalArray {
public static void main(String[] args) {
// create a 2d array
int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7},
};
// first for...each loop access the individual array
// inside the 2d array
for (int[] innerArray: a) {
// second for...each loop access each element inside the row
for(int data: innerArray) {
System.out.println(data);
}
}
}
}
//Copying Arrays
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int [] source = {1, 2, 3, 4, 5, 6};
int [] destination = new int[6];
// iterate and copy elements from source to destination
for (int i = 0; i < source.length; ++i) {
destination[i] = source[i];
}
// converting array to string
System.out.println(Arrays.toString(destination));
}
}
int[] array = new int[10];
Random rand = new Random();
for (int i = 0; i < array.length; i++)
array[i] = rand.nextInt(100) + 1;
Arrays.sort(array);
System.out.println(Arrays.toString(array));
// in reverse order
for (int i = array.length - 1; i >= 0; i--)
System.out.print(array[i] + " ");
System.out.println();
*/
}
package Array_Programs;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
int a[]={10,20,30,40,50,60,70,80,90,100};
//Accessing Elements in array
System.out.println(a[2]);
//Print all Elements using for loop
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
//Print all Elements using Enhanced for loop
System.out.println("----------------Priniting through Enchanced for loop----------------");
for(int element : a)
{
System.out.println(element);
}
int b[]; // Declaring array
b=new int[10]; // Allocating Memory to Array
int [] c =new int[10]; //Combining Both Statement
//Buy default all element have zero value
for(int element : b)
{
System.out.println(element);
}
//Getting input from the user and printing the elements
for(int i=0;i<3;i++)
{
Scanner in =new Scanner(System.in);
System.out.println("Enter The Number");
c[i]=in.nextInt();
}
for(int element : c)
{
System.out.println(element);
}
}
}
package Array_Programs;
public class Two_Array {
public static void main(String args[]) {
//Two Dimension array in Java
int a[][] = {
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(" "+a[i][j]);
}
System.out.println("");
}
//Array Declaration
int [][]b=new int[10][10];
int [][][]c=new int[10][10][10];
b[0][0]=10;
}
}
//Calculate Sum and Average using Arrays
package Array_Programs;
public class Sum_Avg_Array {
public static void main(String[] args)
{
int[] numbers = new int[]{20, 30, 25, 35, -16, 60, -100};
//calculate sum of all array elements
int sum = 0;
for(int i=0; i < numbers.length ; i++)
sum = sum + numbers[i];
System.out.println("Sum of Array is : " + sum);
//calculate average value
double average = sum / numbers.length;
System.out.println("Average value of the array elements is : " + average);
}
}
//Write a Java program to sum values of an array.
package Array_Programs;
public class Sum_an_Array {
public static void main(String[] args) {
int my_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;
for (int i : my_array)
sum += i;
System.out.println("The sum is " + sum);
System.out.println("The Average is " + sum/my_array.length);
}
}
package Array_Programs;
import java.util.Arrays;
public class Sorting_Array {
public static void main(String[] args)
{
int [] Numeric_array = {
10, 20, 65, 44, 9,056, 89,
121, 181, 564, 789
};
String [] String_array = {
"JAVA",
"PYTHON",
"C++",
"C programming"
};
System.out.println("Original numeric array : "+Arrays.toString(Numeric_array));
Arrays.sort(Numeric_array);
System.out.println("Sorted numeric array : "+Arrays.toString(Numeric_array));
System.out.println("Original string array : "+Arrays.toString(String_array));
Arrays.sort(String_array);
System.out.println("Sorted string array : "+Arrays.toString(String_array));
}
}
//Write a Java program to test if an array contains a specific value.
package Array_Programs;
public class Search_Array {
public static boolean contains(int[] arr, int item) {
for (int n : arr) {
if (item == n) {
return true;
}
}
return false;
}
public static void main(String[] args) {
int[] my_array1 = {
1789, 2035, 1899, 1456, 2013,
1458, 2458, 1254, 1472, 2365,
1456, 2265, 1457, 2456};
System.out.println(contains(my_array1, 2013));
System.out.println(contains(my_array1, 2015));
}
}
//Write a Java program to remove a specific element from an array.
package Array_Programs;
import java.util.Arrays;
public class Remove_Element_Array {
public static void main(String[] args) {
int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
System.out.println("Original Array : "+Arrays.toString(my_array));
// Remove the second element (index->1, value->14) of the array
int removeIndex = 1;
for(int i = removeIndex; i < my_array.length -1; i++){
my_array[i] = my_array[i + 1];
}
// We cannot alter the size of an array , after the removal,
//the last and second last element in the array will exist twice
System.out.println("After removing the second element: "+Arrays.toString(my_array));
}
}
package Array_Programs;
public class Jagged_array {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[][] = {
{10, 20, 30, 40},//4
{10, 20, 30},//3
{10, 20, 30, 50}//4
};
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(" "+a[i][j]);
}
System.out.println("");
}
}
}
package Array_Programs;
import java.util.Arrays;
import java.util.Scanner;
public class Insert_Element {
public static void main(String[] args) {
int[] a = {10,20,30,40,50,60,70,80,90,100};
System.out.println("Enter the index where you want to add: ");
Scanner in = new Scanner(System.in);
int index = in.nextInt();
System.out.println("Enter the value you want to add: ");
Scanner val = new Scanner(System.in);
int value = val.nextInt();
System.out.println("Before Insertion "+Arrays.toString(a) );
for(int i=a.length-1;i>index;i--)
{
a[i]=a[i-1];
}
a[index]=value;
System.out.println("After Insertion "+Arrays.toString(a) );
}
}
//Write a Java program to find the index of an array element.
package Array_Programs;
public class Find_Index_Array {
public static int findIndex (int[] my_array, int t) {
if (my_array == null)
return -1;
int len = my_array.length;
int i = 0;
while (i < len) {
if (my_array[i] == t)
return i;
else
i+=1;
}
return -1;
}
public static void main(String[] args) {
int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
System.out.println("Index position of 56 is: " + findIndex(my_array, 56));
System.out.println("Index position of 77 is: " + findIndex(my_array, 77));
}
}
package Array_Programs;
public class Duplicate_array {
public static void main(String[] args) {
int[] a = {1, 2, 5, 5, 6, 6, 7, 2};
for (int i = 0; i < a.length - 1; i++) {
for (int j = i + 1; j < a.length; j++)
{
if ((a[i] == a[j]) && (i != j)) {
System.out.println("Duplicate Element : " + a[j]);
}
}
}
}
}
package Array_Programs;
//Array of Objects in Java
class Student
{
public int roll_no;
public String name;
Student(int roll_no, String name)
{
this.roll_no = roll_no;
this.name = name;
}
void print()
{
System.out.println("Name : "+name);
System.out.println("Roll No : "+roll_no);
System.out.println("---------------------------------");
}
}
public class array_objects {
public static void main (String[] args)
{
Student[] o;
o = new Student[5];
o[0] = new Student(10,"Ram");
o[1] = new Student(20,"Sam");
o[2] = new Student(30,"Ravi");
o[3] = new Student(40,"Kumar");
o[4] = new Student(50,"Sundar");
for (int i = 0; i < o.length; i++)
o[i].print();
}
}
/*
An array is a collection of similar data elements stored at contiguous memory locations.
It is the simplest data structure where each data element can be accessed directly by only using its index number.
Java array is an object which contains elements of a similar data type.
Additionally, The elements of an array are stored in a contiguous memory location.
Syntax :
Class_name object [ ] = new class_name ( ) ;
Example :
Student s [ 5 ] = new Student ( ) ;*/
0 Comments