create/declare and initialise array in java
Here you can learn data structures using java with lots of related programs.
I mainly focus to practice different programs, as a result you can implement your own logic when you encountered with a new problem statement.
Learn DSA(Data Structures and Algorithms) using java :-
In this particular section we will Learn about array, in this article I have discussed how to create, initialise an array in java.
Approach:-1 "Create and initialise array in java"
import java.util.Scanner;
public class creatingArray {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of array: ");
int size = sc.nextInt();
//initializing array
int[] arr = new int[size];
System.out.println("Enter the elements of the array: ");
for(int i = 0; i < size; i++)
{
arr[i] = sc.nextInt();
}
System.out.println("The element of the array are: ");
for(int i = 0; i < size; i++)
{
System.out.print(arr[i] + " ");
}
}
}
In java we can declare an array like this
- datatype[] arrayName;
And to initialise the array, we have new operator.
- arrayName = new datatype[size];
By combining the above two statements, we can declare and initialise an array with a single line of code i.e
- datatype[] arrayName = new datatype[size]
Let's see an example of integer array with size 5.
- int[] num = new int[5];
Here num is the name of the array.
Output
Hey one by one I will upload all the topics with proper explanation and source code that you have to know to become good at data structure.
Guys I am using my android phone to write code for all programs, please support.
Please share this article to everyone, as a result they can also learn.
And yes if you have any questions or any doubt, feel free to write it on the comment below. I will definitely answer to your questions.