FAQ: Learn Java: Arrays - Creating an Empty Array

This community-built FAQ covers the “Creating an Empty Array” exercise from the lesson “Learn Java: Arrays”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Learn Java

FAQs on the exercise Creating an Empty Array

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

Looking for motivation to keep learning? Join our wider discussions in #community

Learn more about how to use this guide.

Found a bug? Report it online, or post in #community:Codecademy-Bug-Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

So far we’ve only seen arrays that store one type of data. Is there another object that can group instances of multiple types?

2 Likes
String[] favoriteArticles;
  
  public Newsfeed(){
    // Initialize favoriteArticles here:
String[] favoriteArticles = new String[10];
  }

Gives nullpointer exception.

String[] favoriteArticles = new String[10];
  
  public Newsfeed(){
    // Initialize favoriteArticles here:
  }

Works

11 Likes

The way to initialize within the constructor method is as follows:

String favoriteArticles;

public Newsfeed(){
// Initialize favoriteArticles here:
favoriteArticles = new String[10];
}

Since the array has already been assigned String outside of the constructor, you can omit String within constructor. Within constructor favoriteArticles = new String[10]; will work without returning any exceptions.

14 Likes

public void setFavoriteArticle(int favoriteIndex, String newArticle){
// Add newArticle to favoriteArticles:
favoriteArticles[favoriteIndex] = newArticle;

}

I fail to understand how favoriteIndex plays in to this line of code and how it changes the behaviour of the Array

4 Likes

This Code works as well

String topics = {“Opinion”, “Tech”, “Science”, “Health”};
int views = {0, 0, 0, 0};
String favoriteArticles;

public Newsfeed(){
// Initialize favoriteArticles here:
favoriteArticles = new String[10];
}

What does the second part mean. I have tried linking to the array, but it gives error

1 Like

Question 1)
This is how I changed the constructor:

// The " Newsfeed" constructor
  public Newsfeed(){
    // Initialize favoriteArticles here:
    favoriteArticles = new String[10];
    
  }

The output was:

[null, null, null, null, null, null, null, null, null, null]

which is consistent, an array with 10 " locations ", ranging from index = 0 to index = 9

1 Like

Question 2)
Here is how I changed the setFavoriteArticle() method:

public void setFavoriteArticle(int favoriteIndex, String newArticle){
    // Add newArticle to favoriteArticles:
    
    favoriteArticles[favoriteIndex] = newArticle;
    
  }

The variable favoriteArticles[favoriteIndex] will evaluate to a String value because the array " favoriteArticles " is just an array full of String values (the name of the articles in this case). Then we can change this String value to a different String value without any errors. The exercise wants us to change the String value already in the array to the String value that the parameter " newArticle " evaluates to.

We want to use the parameters we are supplying it, we want to do something with the information we are feeding the program in the main() method. Why bother supplying the program with input/data if we aren’t gonna do anything with it.

The final array looked like this in the output:

[Oil News, null, Humans: Exterminate Or Not?, Organic Eye Implants, null, null, null, null, null, null]

This is consistent with the three setFavoriteArticle() method calls written inside of the main() method. The first call line we are trying to change the article name at index value 2 (which would be the third item in the array). The second call line we are trying to change the article name at index value 3 (which would be the fourth item in the array). The third and last call line we are trying to change the article name at index value 0 (which would be the very first item in the array). And the last line in the main() method simply prints out the new array that we have manipulated in all that code we wrote for this exercise. Remember the array was empty to begin with it looked like this:

[null, null, null, null, null, null, null, null, null, null]

The point of our program was to fill in the empty array with the data/parameters supplied inside the main() method.

1 Like

It’s so that when we call up this method using

sampleFeed.setFavoriteArticle(2, “Humans: Exterminate Or Not?”);

we are saying that for this particular case the variable favoriteIndex = 2
which when put into favoriteArticles[favoriteIndex] = newArticle;
assigns the 2nd index of favoriteArticles to the String newArticle;
This seems a little useless for a program of this size but I think the purpose is to prepare us for the usefulness of this when working on more complex projects.

Can anyone tell me why have we initialized the empty array in the constructor method and why not outside it?

Thanks. This worked.

because that’s where we initialize it so that initialized array can be used throughout the program. initializing it in a method section does not allow us to use it anywhere else other than in the method itself (scope of the method) unless we return it using the return commands.

why was it

 public Newsfeed(){
    favoriteArticles = new String[10];
  }

and not

  public Newsfeed(){
 String[]   favoriteArticles = new String[10];
  }

?

1 Like

Hello @holographicesther and welcome to the Codecademy Forums!

We already declared String[] favoriteArticles; on line 7. We would then use favoriteArticles = new String[10]; to instantiate (allocate memory) to the array. Since we already declared that favoriteArticles was a String array, we don’t need to do it again when we instantiate the array.

This article explains declaring and instantiating Java array.

Hi, the exercise is :

import java.util.Arrays;

public class MoreNews {

String[] topics = {"Opinion", "Tech", "Science", "Health"};
int[] views = {0, 0, 0, 0};
String[] favoriteArticles;

public MoreNews() {
    favoriteArticles = new String[10];
}

public static void main(String[] args) {
    MoreNews sample = new MoreNews();

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

    System.out.println(Arrays.toString(sample.favoriteArticles));
}


public void setFavoriteArticle(int favoriteIndex, String newArticle) {
 favoriteArticles[favoriteIndex] = newArticle;

}

}

why it gets the wrong output ( [null, null, null,…null] ) when i write : newArticle = favoriteArticles[favoriteIndex] ?

The question is a bit unclear, but I’ll give it a go. Please clarify if you meant something else.


This is the result of your code.

[Oil News, null, Humans: Exterminate Or Not?, Organic Eye Implants, null, null, null, null, null, null]

Whenever an array is instantiated using the new keyword, default values are assigned to each element (0 for ints, false for booleans, null for strings, etc.). Try printing out your array right after you instantiate it (right after MoreNews sample = new MoreNews();. What’s the output?

Now, look at your main method. You use call the setFavoriteArticle() method 3 times and overwrite the values at three of the array indices. Inserting a print statement after each time you call setFavoriteArticle() will help you to see what’s going on. Now do you understand why some of your elements are null?

Hi,

Thank you for your reply and sorry for the unclear question! I understand why I get “null” in some places in the array, the thing that I don’t understand is this.

Looking at the code in my comment, in public void setFavoriteArticle(), i assign newArticle to favoriteArticles[favoriteIndex]; when I run the code it prints out what you explained in your reply, which is ok.

The line of code looks like this in the exercise:

public void setFavoriteArticle(int favoriteIndex, String newArticle) {
favoriteArticles[favoriteIndex] = newArticle;

}
it runs : [Oil News, null, Humans: Exterminate Or Not?, Organic Eye Implants, null, null, null, null, null, null], which is correct

However, if I reverse the order in public void setFavoriteArticle(), and I write : newArticle = favoriteArticles[favoriteIndex], when I run the code the output is different:

public void setFavoriteArticle(int favoriteIndex, String newArticle) {
newArticle = favoriteArticles[favoriteIndex];

}
it runs : [null, null, null, null, null, null, null, null, null, null]

Remember that the object on the left side of the assignment operator (=) is assigned the value or reference of what is on the right side of the assignment operator (=). This doesn’t work in reverse. Here’s an example.

int[] sums = {8, 10};
int newNum = 5;

sums[0] = newNum;
System.out.println(sums[0]); // prints 5
System.out.println(newNum); // prints 5

newNum = sums[1]
System.out.println(sums[1]); // prints 10
System.out.println(newNum); // prints 10

Now take a look at the line newArticle = favoriteArticles[favoriteIndex];. Why do you think null is the value for every element in the favoriteArticles array?

Hi, thank you for your reply! I think I understand now. It is very important how you assign things, and it outputs only “null” because I assign empty value, since newArticle doesn’t have any value.