wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Unable to understand this behavior...wht is happening?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Unable to understand this behavior...wht is happening??" Watch "Unable to understand this behavior...wht is happening??" New topic
Author

Unable to understand this behavior...wht is happening??

Jayashree Gopal
Greenhorn

Joined: Nov 06, 2001
Posts: 8
I have written a program which uses Arrays. Here is the code of the program...
when i check the output....it gives me bicycle,mango,grapes and pineapple
here is the code snippet.......
public class FruitArray
{
String fruit[] = new String[4];

public static void main(String args[])
{
FruitArray f = new FruitArray();
f.amethod();
f.modify();
}

public void amethod()
{
fruit[0] = "Apple";
fruit[1] = "Mango";
fruit[2] = "Grapes";
fruit[3] = "Pineapple";
}

public void modify()
{
fruit[0]="Bicycle";

for(int i=0;i<fruit.length;i++)
{
System.out.println(fruit[i]);
}
}
}
Please explain this behavior...

Jayashree
Rob Ross
Bartender

Joined: Jan 07, 2002
Posts: 2205
Can you be more specific? What part of this program don't you understand?

Rob


Rob
SCJP 1.4
Jayashree Gopal
Greenhorn

Joined: Nov 06, 2001
Posts: 8
I did not understand how does the output come. I have replaced the first element of the array in the modify method.SO,shd not it give me null for the other elements of the array when i print them??
Graeme Brown
Ranch Hand

Joined: Oct 13, 2000
Posts: 193
No, amending the first element of the array will have no effect on the other elements. The output you got is the correct behaviour.
If you want the other elements to be null you will have to do it explicitly:
fruit[1] = null; etc
R K Singh
Ranch Hand

Joined: Oct 15, 2001
Posts: 5371
Originally posted by Jayashree Gopal:
I did not understand how does the output come. I have replaced the first element of the array in the modify method.SO,shd not it give me null for the other elements of the array when i print them??

array is collection of same type of object .... if you change any one then others won't change, till u specifically change that element by accessing it by its index.
HTH
CMIW


"Thanks to Indian media who has over the period of time swiped out intellectual taste from mass Indian population." - Chetan Parekh
 
GeeCON Prague 2014
 
subject: Unable to understand this behavior...wht is happening??