This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Jayashree Gopal
Greenhorn
Posts: 8
  • 0
  • 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
  • 0
  • 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
  • 0
  • 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
  • 0
  • 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: 5382
  • 0
  • 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
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic