Java |
|||||||||
Java - Array
The concept of Java Array is same as Arrays in other language like C Array or Python Array. The only differences are just a little bit of differences in terms of Syntax. So if you have understandings on Array in any language, you only need to get used to small syntax differences in Java.
How to create an Array and Assign values ?
In this example, I will show you various different ways of creating, initializaing, assigning an array. In this example, I created Arrays named numAry1, numAry2, numAry3, numAry4, numAry5 with different sizes at the point of declaration but all of these arrays are assigned to store numAry1. The reason why I tried this is to show that the value stored in Array variable is a pointer. Even though Java syntax does not explictely show any pointer symbol (e.g, like '*' as in C), in many cases Java variables works as a pointer (If you are not familiar with Pointer concept, refer to C Pointer page).
C:\temp> java Array01
1.1 2.2 3.3 4.4 5.5 <-- numAry1 1.1 2.2 3.3 4.4 5.5 <-- numAry2 1.1 2.2 3.3 4.4 5.5 <-- numAry3 1.1 2.2 3.3 4.4 5.5 <-- numAry4 1.1 2.2 3.3 4.4 5.5 <-- numAry5 1.0 2.0 0.0 <-- numAry6
This example would show clearly that Java array variable works as a pointer. The variable declaration and initialization is same as the previous example. The only differences are I changed the contents of two arrays as highlited below. What would be the result when you print out the contents of all the arrays ? Would it show that only numAry1 and numAry5 are changed ? or All of the arrays are changed ? See the result.
C:\temp> java Array02
1.1 100.0 300.0 4.4 5.5 <-- you can notice all of the contents of all arrays are changed 1.1 100.0 300.0 4.4 5.5 1.1 100.0 300.0 4.4 5.5 1.1 100.0 300.0 4.4 5.5 1.1 100.0 300.0 4.4 5.5
How to go though each and every elements ?
There are two different ways of going through each elements in an Array as shown below.
C:\temp> java Array04
HELLO WORLD HELLO WORLD
How to pass an Array into a method ?
Passing an array into a function is not much different from passing non-array parameters as shown below. This is similar to passing an array in C.
C:\temp> java Array03
Hello World
|
|||||||||