Array in Java – User friendly Tech help

What is an Array?
nAn array is storehouse or we can say collection of similar type of data type.
nIt is a data structure where we store similar elements. We can store only fixed set of elements in a java array(solution is ArrayList in Java) unlike vbscript where we can have dynamic arrays using Redim keyword.
n
nStop being in LOVE with someone who never was and focus on the one who IS. If you Love learning new concepts,Do follow us on FB , G+ , Twitter, or Linkedin
n
nWhy Arrays?
nIt provides code optimization and easy access. Like Instead of declaring individual variables, such as Learn0, Learn1, …Learn9, we can declare one array variable and use Learn[0], Learn[1], …, Learn[9] to represent individual variables.
n
nSyntax:-
ndataType[] arrayName;
n
nor
n
ndataType arrayName[];
n
nor
n
ndataType []arrayName;

n

n

n

n

n

n

n

n

Memory allocation of an Array

n

Example:- 
nWe are declaring an integer array by implementing the above syntax
n

n

public class ArrayInJava {
//Array Delcaration in Java
public static void main(String[] args) {
//Approach1
int[] Learn;
//Approach2
int Revise[];
//Approach3
int []implement; }}

n

nAssigning a Value :-
nWe have declared an array, now how can add value into the reserved memory locations of an array like Learn[0] should have 100.

nn

nApproach1:-
ndataType[] arrayName = new datatype[arraysize];
narrayName[0] = arrayValue;
narrayName[1] = arrayValue;
n–
n–
n–
narrayName[arraySize-1] = arrayvalue;
n
Approach2:- 
ndataType[] arrayName = {value1,value2,…value10}
n
nExample:-

n

public class ArrayInJava {
//Assigning values to Array in Java
public static void main(String[] args) {
//Approach1
int[] Learn = new int[2];
Learn[0] = 100 ;
Learn[1] = 200 ;
//Approach2
int Revise[] = {100,200};
//Accessing element of an Array
System.out.println("Approach one Result ="+Learn[0]+";"+Learn[1]);
System.out.println("Approach Two Result ="+Revise[0]+";"+Revise[1]); }}
#Output:-
Approach one Result =100;200
Approach Two Result =100;200

n

Note:-
nArray index always starts with 0 , thus to access the first element we used ArrayName[0].
n
nHandOn:-
nExample1:- 
nWe have used for loops in working with Arrays.

n

public class ArrayInJava {
//Working with Arrays Using For Loops
public static void main(String[] args) {
//Declaring an Array
int[] Learn = new int[10];
//Assinging values to an Array Using For loop
for (int iCnt = 0 ;iCnt
Was this article helpful?
YesNo

Similar Posts