Creating an Empty Array

Can anyone explain how it's behaving when we call the setFavoriteArticle method with arguments  in the main method  I mean I didn't understand the O/P whey we are getting Oil News first then the following? 

import java.util.Arrays;

public class Newsfeed {
  String[] topics = {"Opinion", "Tech", "Science", "Health"};
  int[] views = {0, 0, 0, 0};
  String[] favoriteArticles;
  public Newsfeed(){
    // Initialize favoriteArticles here:
   favoriteArticles = new String[10];
  public void setFavoriteArticle(int favoriteIndex, String newArticle){
    // Add newArticle to favoriteArticles:
    favoriteArticles[favoriteIndex] = newArticle;
  public static void main(String[] args){
    Newsfeed sampleFeed = new Newsfeed();
    sampleFeed.setFavoriteArticle(2, "Humans: Exterminate Or Not?");
    sampleFeed.setFavoriteArticle(3, "Organic Eye Implants");
    sampleFeed.setFavoriteArticle(0, "Oil News");
[Oil News, null, Humans: Exterminate Or Not?, Organic Eye Implants, null, null, null, null, null, null]

When I give index 0,0,0 for all like this below 

    sampleFeed.setFavoriteArticle(0, "Humans: Exterminate Or Not?");
    sampleFeed.setFavoriteArticle(0, "Organic Eye Implants");
    sampleFeed.setFavoriteArticle(0, "Oil News");

I am still getting "Oil News" first in the output as you can see below. can anyone explain how it's calculating  when we give index 0 to all 

[Oil News, null, null, null, null, null, null, null, null, null]

In the first case of using setFavouriteArticle, you set a different index to a different newsfeed. You put Oil News at index 0, so it’s first. The reason for the nulls is that the length of the favouriteArticles array is 10, but you’ve only specified three newsfeeds.

In the second case

The nulls appear for the same reason as stated above. The reason Oil News is first is because that’s what you set index 0 to last. Each time you write array[index] = something, you change the value at array[index] to something.

I hope this helps!

I have set index[0] for all but why still it’s taking “Oil News” first instead of taking “Humans: Exterminate Or Not”?

Well, you set it to Oil News last. That means whatever was at index 0 before this line

Gets changed to Oil News.

Now I got it. I have set “Humans: Exterminate Or Not?” in the “Oil News” place so I am getting “Humans: Exterminate Or Not?” so since all index’s are zero whatever we set to index[0] it will take that.

am I right?

1 Like

Indeed you are!

Got it thank you so much! :smile:

1 Like