This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Jayashree Gopal
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you be more specific? What part of this program don't you understand?

Rob
 
Jayashree Gopal
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 193
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5384
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic