Jan 7, 2022

What is Arrays in Java

Basically an array in java is a collection of homogeneous elements that simply means array can store elements of same type or we can say it can store elements of same data types. means if we declare integer type array so we can store only integer data type elements in array or if we declared array of character type so we can store only character's in it. 

What is arrays in java, what are arrays in java, java programming examples and syntax



For Example: 

int arr[];

or 

char c[];


In above example I have shown syntax to declare an array.


  Java Program to Declare and Initialize an Array:


public class ArrayExample {

	public static void main(String[] args) {
		//declaring and Initializing an array
		int  arr[]= {10,20,30,40,50};
		//printing array elements
		for(int i=0;i<arr.length;i++)
		System.out.print(arr[i]+" ");
	}

}

Above program will show the following output:

10 20 30 40 50



Arrays are fixed in size that means one's we create an array of size 10 so we cannot change its value.


  Syntax to create an array with some size:

data_type   array_name = new  data_type[10];


For Example:

int arr[] = new int[10];

In above example we can see that we have declared one array with size 10 so in this array we can store only 10 elements and if we try to store 11th element it will throw an  IndexOutOfBoundsException.


  Program which demonstrates the array IndexOutOfBoundsException :


public class ArrayExample2 {

	public static void main(String[] args) {
		//declaring and allocation size
		int  arr[]= new int[5];

		arr[0] = 1;
		arr[1] = 2;
		arr[2] = 3;
		arr[3] = 4;
		arr[4] = 5;
		arr[5] = 6;//will throw an error
		
		for(int i=0;i<arr.length;i++)
		System.out.println(arr[i]);
	}

}


  Output of the above program is :

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5 at ArrayExample2.main....



Below is the list of some array examples in Java, You can practice and compile it on your computer and see how it works.

 

  List of Array Examples In Java :

continue reading What is Arrays in Java
Share This:    Facebook Twitter

Jan 6, 2022

How to copy Arrays in Java with Examples

In this post we will learn how to copy arrays in java. Copying arrays simply means copying one array elements into another array. There are two main ways to do this first by using loops and second by using methods.

How to copy arrays in java, java program to copy one array to another array


So first we will learn how to copy array using loop's. In this example I am going to use  a simple for loop. But here, you can also make a use of another loops it's totally depend on you.


  Java Program to copy elements of one array into another array using for loop :



public class CopyingArray {

	public static void main(String[] args) {
		
		int arr1[] = {10,20,30,40,50};
		//creating arr2[] of size arr1[]
		int arr2[] = new int[arr1.length];
		
		
		for(int i=0;i<arr1.length;i++) {
		//assigning values of arr1 to arr2
			arr2[i]=arr1[i];
		}
		//printing elements of arr1
		System.out.print("Elements in arr1[] are: ");
		for(int i=0;i<arr1.length;i++) {
			System.out.print(arr1[i]+" ");
		}
		
		//for next line
		System.out.println();
		
		//printing elements of arr2
		System.out.print("Elements in arr2[] are: ");
		for(int i=0;i<arr2.length;i++) {
			System.out.print(arr2[i]+" ");
		}
	}	

}


 
 Output of the above program is : 
Elements in arr1[] are : 10 20 30 40 50
Elements in arr2[] are : 10 20 30 40 50



Another way to copy array elements is by using methods. In Java there are multiple methods to copy elements of one array into another array like copyOf(), clone() etc. In below example I have used only copyOf() method.



  Java Program to copy elements of one array into another array using copyOf() method : 


import java.util.Arrays;

public class CopyingArray {

	public static void main(String[] args) {
		
		int arr1[] = {10,20,30,40,50};
		//copy arr1 elements into arr2
		int arr2[] = Arrays.copyOf(arr1, 5);
		
		
		//printing elements of arr1
		System.out.print("Elements in arr1[] are: ");
		for(int i=0;i<arr1.length;i++) {
			System.out.print(arr1[i]+" ");
		}
		
		//for next line
		System.out.println();
		
		//printing elements of arr2
		System.out.print("Elements in arr2[] are: ");
		for(int i=0;i<arr2.length;i++) {
			System.out.print(arr2[i]+" ");
		}
	}	

}



  Output of the above program is : 
Elements in arr1[] are : 10 20 30 40 50
Elements in arr2[] are : 10 20 30 40 50


Share your thoughts in the comment section given below.... :)

continue reading How to copy Arrays in Java with Examples
Share This:    Facebook Twitter

Jan 5, 2022

How to compare arrays in Java | Examples

In this post we will learn how to compare two arrays in java. So without wasting more time  lets get started. 

How to compare arrays in java, java program to compare two arrays in java


  What is comparing arrays really means: The comparing arrays means comparing or we can say checking first array elements are same like another one or not. for example: If we have two arrays like we can say arr1[] or arr2[] here, arr1 contains some values like 1,2,3,4,5 or arr2[] contains some values like 6,7,8,9,10. So we can see in this example arr1[] and arr2[] contains different values. 

Let's understand it with programming example's  :)

Java provides two inbuilt method's to compare arrays
1.  Arrays.equals()
2. Arrays.deepEquals()


1. Java Program to Compare two arrays using equals() method:


import java.util.Arrays;

public class ComparingArrays {

	public static void main(String[] args) {
		int arr1[] = {1,2,3,4,5};
		int arr2[] = {6,7,8,9,10};
		
		//comparing array contents
		if(Arrays.equals(arr1,arr2))
			System.out.println("Given two arrays are same");
		else
			System.out.println("Given arrays are not same");
			
	}
}

  Output of the above program is: 
Given arrays are not same



2. Java Program to Compare two arrays using deepEquals() method:

This method deeply compares two arrays. It is most useful when we want to compare multidimensional arrays.


import java.util.Arrays;

public class ComparingArrays {

	public static void main(String[] args) {
		int arr1[] = {1,2,3,4,5};
		int arr2[] = {1,2,3,4,5};
		
		//a1[] and a2[] contains only one elements
		Object a1[] = {arr1};
		Object a2[] = {arr2};
		
		//deeply comparing array contents
		if(Arrays.deepEquals(a1,a2))
			System.out.println("Given two arrays are same");
		else
			System.out.println("Given arrays are not same");
			
	}

}

  Output of the above program is:

Given two arrays are same


  Same above program using multidimensional array:



import java.util.Arrays;

public class ComparingArrays {

	public static void main(String[] args) {
		//defining multidimensional arrays
		int arr1[][] = {{1,2},{3,4}};
		int arr2[][] = {{1,2},{3,4}};
		
		//a1[] and a2[] contains only one elements
		Object a1[] = {arr1};
		Object a2[] = {arr2};
		
		//deeply comparing multidimensional array contents
		if(Arrays.deepEquals(a1,a2))
			System.out.println("Given two arrays are same");
		else
			System.out.println("Given arrays are not same");
			
	}
}


  Output of the above program is:

Given two arrays are same


Share your questions in the comment section given below....... :)


continue reading How to compare arrays in Java | Examples
Share This:    Facebook Twitter

Dec 7, 2021

Length of an Array in Java | Java Program to find Length of an Array

In this article you will learn how to find array length in java. But, before learning how to find array length, you should know exactly array length means what.

In short array length means the limit of elements that array can hold. See in the below diagram we have stored 7 elements in array so length of this array is 7.

  
Array length in java, array index in java, length of an array



As shown in above image array length means last index + 1. So in above image array last index is 6. so here array length is 7.


  Java Program to find Length of an Array:



public class ArrayLengthExample {

	public static void main(String[] args) {
		//defining array of length 10
		int arr[] = new int[10];
		
		System.out.println("Length of the array is : "+arr.length);
	}

}



  Output of the above Program is :

Length of the array is : 10



  Let's see one more Example to find Array Length:



public class ArrayLengthExample2 {

	public static void main(String[] args) {
		//initializing an array of type string
		String str[] = {"Apple","Mango","banana"};
		
		System.out.println("Size of the array is : "+str.length);
	}

}



  Output:

Size of the array is : 3




continue reading Length of an Array in Java | Java Program to find Length of an Array
Share This:    Facebook Twitter

Nov 24, 2021

How to Print Arrays in Java | Java Program to Accept and Print Array Elements

How to print arrays in java


How to print arrays in java: 

To print array elements we first need to accept it from user. In this post we will learn how to accept array elements from user dynamically and print it on the output screen. Simple java program to insert elements in array. 

We can print array elements using any type of loop like :

  • for loop (we can also use for-each loop)
  • while loop
  • do-while loop


  Step by Step logic of the Given Program :


We can take array input from user using the method of the Scanner class. 

1. Accept array elements from user one by one using simple for loop:

for(int i=0;i<5;i++) {
	a[i]=sc.nextInt();		
}
2. Print Elements using for loop in this program i used Enhanced for loop to print array elements:
for(int e:a) {	
	System.out.print(e+" ");
}

but, you can also use simple for loop to print array elements like:

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


  Simple Array Program to Accept and Print Array Elements:


import java.util.Scanner;

public class SimpleArrayExample {

	public static void main(String[] args) {
		//Declaration and instantiation
		int  a[] = new int[5];
		Scanner sc = new Scanner(System.in);
		//Accepting elements using simple for loop
		System.out.println("ENTER THE ELEMENTS: ");
		for(int i=0;i<5;i++) {
			a[i]=sc.nextInt();		
		}
		System.out.println("ELEMENTS IN ARRAY ARE: ");
		//printing elements using Enhanced for loop(for-each loop)
		for(int e:a) {
			System.out.print(e+" ");
		}
	}		
}



  Same above Program using while loop:

In above program we have used for loop to store and print array elements. So, In this program we will use while loop to store and print array elements.


import java.util.Scanner;

public class SimpleArrayExample {

	public static void main(String[] args) {
		//Declaration and instantiation
		int  a[] = new int[5];
		Scanner sc = new Scanner(System.in);
		//Accepting elements using while loop
		System.out.println("ENTER THE ELEMENTS: ");
		int i=0;
		while(i<5) {
			a[i]=sc.nextInt();
			i++;
		}
		System.out.println("ELEMENTS IN ARRAY ARE: ");
		//printing elements using while loop
		int j=0;
		while(j<5) {
			System.out.print(a[j]+" ");
			j++;
		}
	}		
}


  

 
 Output of the above program is :

ENTER THE ELEMENTS:
3
8
2
1
ELEMENTS IN ARRAY ARE: 
5 3 8 2 1



Learn more basic concepts of arrays in C array tutorial...

continue reading How to Print Arrays in Java | Java Program to Accept and Print Array Elements
Share This:    Facebook Twitter

How to Sort Arrays in Java

In this post we will learn how to write a  java program to sort array elements. How to sort arrays in java. Sorting array elements means storing or printing it in ascending or descending order. So let's see how to print given array elements in sorted manner.

Basically there are two ways to sort array elements:

  1. Using sort() method
  2. Using for loop

How to sort arrays in java, sort array elements


1. Using sort() method:

  Step by step logic to print array elements in ascending order using sort() method:


1. To use sort() method first we need to import Arrays class which is defined in java.util package.

2. Define a array of integer(int) type.

3. Use sort() method to sort array elements like: Arrays.sort(arr);

4. Now print array elements using for loop or any other loop.

5. It will print all array elements sorted in ascending order.  



  Program to Print Array Elements Sorted in Ascending Order using sort() method:


/**Program to sort array elements in Ascending order*/

import java.util.Arrays;//importing the Arrays class

public class ArraySortingExample {

	public static void main(String[] args) {
		
		int arr[] = new int[] {55,7,12,3,9,23,67,2};
		//Sorting elements using predefined method
		Arrays.sort(arr);
		//printing elements
		System.out.println("Elements after sorting: ");
		for(int i=0;i<arr.length;i++) {
			System.out.println(arr[i]);
		}
	}

}


  Output:

Elements after sorting:
2
7
9
12
23
55
67

2. Same above Program Without using predefined method Using for loop:

This program is same as above program but, only change is... in this program we have used following logic instead of sort() method:
for(int i=0;i<arr.length;i++) {
	for(int j=i+1;j<arr.length;j++) {
		if(arr[i]>arr[j]) {
		temp = arr[i];
		arr[i]=arr[j];
		arr[j]=temp;
		} 
	}
}
  


  Program:


/**Program to sort array elements in Ascending order*/
public class ArraySortingExample2 {

	public static void main(String[] args) {
		int arr[] = new int[] {55,7,12,3,9,23,67,2};
		int temp;
		//sorting elements logic
		for(int i=0;i<arr.length;i++) {
			for(int j=i+1;j<arr.length;j++) {
				if(arr[i]>arr[j]) {
					temp = arr[i];
					arr[i]=arr[j];
					arr[j]=temp;
				} 
			}
		}
		
		//printing elements
		System.out.println("Elements after sorting: ");
		for(int i=0;i<arr.length;i++) {
			System.out.println(arr[i]);
		}

	}
}

  Output:

Elements after sorting:
2
7
9
12
23
55
67



  Program to Sort array elements in Descending Order:

Sorting arrays in descending order means storing or printing the elements in highest to lowest order.



/**Program to sort array elements in descending order*/
public class ArraySortingExample3 {

	public static void main(String[] args) {
		int arr[] = new int[] {55,7,12,3,9,23,67,2};
		int temp;
		//sorting elements logic
		for(int i=0;i<arr.length;i++) {
			for(int j=i+1;j<arr.length;j++) {
				if(arr[i]<arr[j]) {
					temp = arr[i];
					arr[i]=arr[j];
					arr[j]=temp;
				} 
			}
		}
		
		//printing elements
		System.out.println("Elements after sorting: ");
		for(int i=0;i<arr.length;i++) {
			System.out.println(arr[i]);
		}

	}

}

  Output of the above program is :

Elements after sorting: 
67
55
23
12
9
7
3
2


If you have any doubts.. feel free to comment below.... :)

continue reading How to Sort Arrays in Java
Share This:    Facebook Twitter

Nov 22, 2021

Java Program to Print Square of Given Array Elements

In previous post we learnt how to print multiplication of given array elements. In this post we will learn how to print squares of given array elements. So let's get started... :)

Java program to print square of given array elements

  Step by step logic of the given program:


1. Accept array limit from user store it in variable say lim.

2. Accept elements from user. Run a for loop from to arr.length-1 and store elements one by one in array:

for(int i =0;i<arr.length;i++) {
	arr[i]=sc.nextInt();
}

3. After that store Square of array elements one by one in variable called square and print it.

for(int i=0;i<arr.length;i++) {
	square = arr[i]*arr[i];
	System.out.println("Square of "+ arr[i] +" is: "+square);
    }


  Java Program to Print Square of Given Array Elements :




import java.util.Scanner;

public class ArraySquareExample {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int square=0;
		//Accept limit
		System.out.println("How many elements you want to enter: ");
		int lim = sc.nextInt();
		int[] arr= new int[lim];
		//Accepting elements
		System.out.println("Enter "+lim+" elements: ");
		for(int i =0;i<arr.length;i++) {
			arr[i]=sc.nextInt();
		}
		//Logic to print square of array elements
		for(int i=0;i<arr.length;i++) {
			square = arr[i]*arr[i];
			System.out.println("Square of "+ arr[i] +" is: "+square);
	    }

	}
}

Output of the above program is:

How many elements you want to enter:
7
Enter 7 elements:
5
3
8
7
9
15
21
Square of 5 is: 25
Square of 3 is: 9
Square of 8 is: 64
Square of 7 is: 49
Square of 9 is: 81
Square of 15 is: 225
Square of 21 is: 441


continue reading Java Program to Print Square of Given Array Elements
Share This:    Facebook Twitter

Java Program to Print Multiplication of Given Array Elements

Java program to print multiplication of given array elements

In previous post we learnt how to print Sum of given array elements. In this post we will learn how to print multiplication of given array elements. 


  Step by step logic of the given program:


1. Accept array limit from user store it in variable say lim.

2. Accept elements from user. Run a for loop from to arr.length-1 and store elements one by one in array:

for(int i =0;i<arr.length;i++) {
	arr[i]=sc.nextInt();
}

3. After that store multiplication of  all elements in variable called mult using for-each loop (you can also use simple for loop).

for(int ele:arr) {
	mult*=ele;
}

4. Last print multiplication of array elements stored in mult variable.



  Java Program to Print Multiplication of Given Array Elements :




import java.util.Scanner;

public class ArrayMultExample {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int mult=1;
		//Accept limit
		System.out.println("How many elements you want to enter: ");
		int lim = sc.nextInt();
		int[] arr= new int[lim];
		//Accepting elements
		System.out.println("Enter "+lim+" elements: ");
		for(int i =0;i<arr.length;i++) {
			arr[i]=sc.nextInt();
		}
		//Storing multiplication in mult variable
		for(int ele:arr) {
			mult*=ele;
		}
		System.out.println("Multiplication of given array elements is: "+mult);

	}

}

Output of the above Program is:

How many elements you want to enter : 
5
Enter 5 elements:
1
2
3
4
5
Multiplication of given array elements is : 120


continue reading Java Program to Print Multiplication of Given Array Elements
Share This:    Facebook Twitter

Nov 21, 2021

Java Program to Print Sum of given Array Elements

In previous  post we learnt how to check given element is present in array or not. In this post we will learn how to print sum of given array elements. So let's get started... :)


  Step by step logic of the given program:


1. Accept array limit from user store it in variable say lim.

2. Accept elements from user. Run a for loop from 0 to arr.length-1 and store elements one by one in array:

for(int i =0;i<arr.length;i++) {
	arr[i]=sc.nextInt();
}

3. After that store sum of  all elements in variable called sum using for-each loop (you can also use simple for loop).

for(int ele:arr) {
	sum+=ele;
}

4. Last print sum of array elements stored in sum variable.



  Java Program to Print Sum of Given Array Elements :



import java.util.Scanner;

public class ArraySumExample {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		int sum=0;
		
		System.out.println("How many elements you want to enter: ");
		int lim = sc.nextInt();
		int[] arr= new int[lim];
		//Accept Elements
		System.out.println("Enter "+lim+" elements: ");
		for(int i =0;i<arr.length;i++) {
			arr[i]=sc.nextInt();
		}
		//for-each loop
		for(int ele:arr) {
			sum+=ele;
		}
		System.out.println("Sum of given array elements is: "+sum);

	}

}


Output of the above program is

How many elements you want to enter:
5
Enter 5 elements: 
5
7
8
10
20
Sum of given array elements is: 50




continue reading Java Program to Print Sum of given Array Elements
Share This:    Facebook Twitter

Java Program to Check whether Given Element is Present in Array or not

In previous tutorial we learnt how to accept and print array elements. In this post we will learn is given element is present in array or not, Java program to check whether given element is present in array or not.


  Step by step logic of the given program:


1. Declare and Initialize array and other variables.

2. Input value from user and store it in variable say value.

System.out.println("Enter the value you want to find: ");
int value = obj.nextInt();

3. Run a loop from 0 to arr.length-1(In below program it will run from 0 to 7) because in below program array length is 8.

4. Inside the for loop use one if condition to check whether given value and array value is same or not, if value is same then increment count by one and break the loop. 

for(i=0; i<arr.length;i++) {
	if(arr[i]==value) {
		count++;
		break;
	}
}

5. Outside the loop use one if condition to check whether the count is greater than zero or not, if true then print value is present in array otherwise print value is not present.



  Java Program to Check whether Given Element is Present in Array or not:





import java.util.Scanner;

public class SearchArrayElement {

	public static void main(String[] args) {
		//Array Initialization
		int arr[] = {5,8,2,4,1,9,3,7};
		int count=0,i;
		
		Scanner obj = new Scanner(System.in);
		//Accept value from user to check whether it is present or not
		System.out.println("Enter the value you want to find: ");
		int value = obj.nextInt();
		//Run a for loop
		for(i=0; i<arr.length;i++) {
			if(arr[i]==value) {
				count++;
				break;
			}
		}
		//If count is greater than zero means value is present
		if(count>0) {
			System.out.println("Value is present in array at position : "+(++i));
		}else {
			System.out.println("Given value is not present in array");
		}
	}

}

In above program we have used length attribute to find length of array.


  Same Above Program using for-each loop:


import java.util.Scanner;

public class SearchArrayElement {

	public static void main(String[] args) {
		//Array Initialization
		int arr[] = {5,8,2,4,1,9,3,7};
		int count=0,i=0;
		
		Scanner obj = new Scanner(System.in);
		//Accept value from user to check whether it is present or not
		System.out.println("Enter the value you want to find: ");
		int value = obj.nextInt();
		//Run for-each loop
		for(int ele:arr) {
			i++;
			if(ele==value) {
				count++;
				break;
			}
		}
		//If count is greater than zero means value is present
		if(count>0) {
			System.out.println("Value is present in array at position : "+i);
		}else {
			System.out.println("Given value is not present in array");
		}
	}

}


Output:

Enter the value you want to find : 
1
Value is present in array at position : 5


continue reading Java Program to Check whether Given Element is Present in Array or not
Share This:    Facebook Twitter