In the main I have a Array, how can i use the data from this array in a sub
Printable View
In the main I have a Array, how can i use the data from this array in a sub
Do you mean somthing like this?
Code:class ArrayExample{
public static void main(String[] args){
String[] s = {"Hello","Whats's","up?"};
printStrings(s);
}
static void printStrings(String[] s){
for(int i = 0; i < s.length; ++i){
System.out.println(s[i]);
}
}
}
Some things that i would like to point out. Java is a pass by value language. Not a pass by refrence. First let me explain pass by refrence. When a variable is passed to a method a copy of that variable is passed. If the method modifies it's parameters those modifications are visible when the method returns.
Java does not do this. It is a pass by value language. For instance. The following code illustrates this point.
However when a refrence type is involved, the valus is passed by refrence. This is not the same as "pass-by-refrence". If java were a pass by refrence language, when a refrence type was passed to a method, it would be passed as a refrence to the refrence.Code:class Example{
public static void main(String[] args){
int i = 10;
printInt(i);
System.out.println(i); // prints 10
}
static void printInt(int i){
System.out.println(i); // prints 10
i = 25;
}
}
If you notice in this block of code. When an array is passed to a method. It's contents are modified when the method returns.
Code:class ArrayExample{
public static void main(String[] args){
String[] s = {"Hello","Whats's","up?"};
printStrings(s);
for(int i = 0; i < s.length; ++i){
System.out.println(s[i]);
}
}
static void printStrings(String[] s){
for(int i = 0; i < s.length; ++i){
System.out.println(s[i]);
}
s[2] = "down";
}
}
Heres another example. Even though we are modifying the contents of the variable i and returning that value from the method the contents of the variable were never changed.
Code:class Example{
public static void main(String[] args){
int i = 10;
int k = 0;
k = printInt(i);
System.out.println(k); // prints 10
}
static int printInt(int i){
System.out.println(i); // prints 10
i = 25;
return i;
}
}