Arrays in Java
Arrays in Java. we can look at array as a compartment or section inside a large container. This section in the large box store data from the same type such as integer, string, double, long etc.
In Java the first array start from “0”,and we can define the number of arrays which we need inside a variable.Data inside the array can be replace or loop through etc, this is very useful when we want to manipulate data in our variable.
The Data type which reside in the Array should be the same type.There a lot of pre-build ” method:” which we are able to use , by just including the library . After including the Library we will be able to access the methods.
There are tonnes of Array Method being developed , don’t try to remember it,this will make you crazy always refer back click here
Refer the Code below on how to Declare an Array
There are two ways to declare an Array
First Method
What i did.
- First i declare my Variable with a value of “10” Array.
- I declare a Variable which i need to keep my Array Length later
- I input my Array value from [0] to [2] one by one
- I check the Array length and assign the checked array length value back into “myArrayLength”
- I created for loop to loop through every single array and print it out
package firstproject; public class demoArray { public static void main(String[] args) { int[] myArray = new int[10]; int myArrayLength; myArray[0]= 3; myArray[1]= 2; myArray[2]= 1; myArrayLength= myArray.length; for(int i=0;i<myArrayLength;i++){ System.out.println(myArray[i]); } }
Second Method
What i did.
- What i did same applied to the above , just the declaration of array method is different from above .
- In the mean time i have added a library and sort the Array to order.
package firstproject; import java.util.*; public class demoArray { public static void main(String[] args) { int[] myArray = {3,2,1}; //Difference type of Declaration int myArrayLength; myArrayLength= myArray.length; Arrays.sort(myArray); for(int i=0;i<myArrayLength;i++){ System.out.println(myArray[i]); } } }
Check out how o use String method in Java here
Leave a Reply