FAQ: 2D Arrays: Java - Modifying Elements in a 2D Array

This community-built FAQ covers the “Modifying Elements in a 2D Array” exercise from the lesson “2D Arrays: Java”.

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

Learn Java

FAQs on the exercise Modifying Elements in a 2D 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 Language Help.

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

Need broader help or resources? Head to Language Help and Tips and Resources. If you are wanting feedback or inspiration for a project, check out Projects.

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 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!

I’m not sure if maybe something just didn’t load right for me but the tictactoe example has over 80 combinations that the second and third rows could be and no insight as to what they should be so I just used the view solution and skipped past it because trying to guess the magic combination does nothing but take up time.

2D arrays keep printing a zero for the last [1][1]*5 = 0 no matter what number I put there to check. Otherwise it worked fine.

1 Like

I’m a little confused. The exercise asks us to create a 2x2 array. If it starts at index zero, shouldn’t it then look like:

int subMatrix = new int[1][1];

instead of int subMatrix = new int[2][2];

1 Like

They asked for four lines of code to multiply the top left square of intMatrix by 5 and place the results in subMatrix.

Sorry, dudes, but the following is ALSO a correct answer:

for (int i = 0; i <= 1; i++) {
  subMatrix[0][i] = intMatrix[0][i] * 5;
  subMatrix[1][i] = intMatrix[1][i] * 5;
}

Even though we initialized intMatrix with 4 at the position you mentioned, in step 1 we changed that element to 0. So, in step 3, this element will evaluate to 0*5 = 0.

@dev1871983950 When we are initializing a 2D array, then the first number in brackets specifies how many rows we want. The second number specifies how many columns.
int[][] subMatrix = new int[2][2] says to create a new matrix of integers with 2 rows and 2 columns.
If we wanted to access the element in the 2nd column of the 2nd row, we would indeed use subMatrix[1][1] as the indices start from 0.
When we are trying to access/modify an element in a 2D array, then we should remember that the index starts at 0.
When we are initializing a 2D array, we aren’t specifying the index. Instead, we are specifying how many rows and columns we want.

Hi dev,

it’s like when you use .length on a String. “abc” :
index 0 = ‘a’;
index 1 = ‘b’;
index 2 = ‘c’;

but the length of the string is 3 because you have 3 char. (index != lenght).

So when they ask you to create a 2x2 array, they talking about the length but to access to it, it’s 0 and 1 like you find :slight_smile:

Hi guys,

I don’t understand why a loop (nested in my case) can be false for this exercice ? They just didn’t think about it or there is a reason ?

Hi, the beginning of the last instruction of the 3rd exercice in 2D Arrays: Java is confusing:

" Using 4 lines of code, multiply each of the elements in the 2x2 top left corner of intMatrix ".

I tried to guess what it meant by “top left corner of intMatrix” by picking the first row and the first column of intMatrix, so I printed:

subMatrix[0][0] = intMatrix[0][0] * 5;
subMatrix[0][1] = intMatrix[0][0] * 5;
subMatrix[1][0] = intMatrix[0][0] * 5;
subMatrix[1][1] = intMatrix[0][0] * 5;

However, it turned out to be true for the first line of code only. I had to input intMatrix[0][1], intMatrix[1][0], and intMatrix[1][1] for the remaining 3 lines of code. It does not really sound “top left corner” to me, this part could have been worded better in my opinion.

Another feedback which might be worth mentionning: the subMatrix[1][1] = intMatrix[1][1] * 5; line of code outputs 0, whereas it should have printed 20. Here are the lines of code:

import java.util.Arrays;

public class Modifying {

public static void main(String args) {

// Using the provided 2D array

int[][] intMatrix = {

    {1, 1, 1, 1, 1},

    {2, 4, 6, 8, 0},

    {9, 8, 7, 6, 5}

};   



// Replace the number 4 in the 2D array with the number 0

intMatrix[1][1] = 0;

 System.out.println(Arrays.deepToString(intMatrix));

// Declare and initialize a new empty 2x2 integer 2D array called subMatrix

int[][] subMatrix = new int[2][2];

// Using 4 lines of code, multiply each of the elements in the 2x2 top left corner of intMatrix by 5 and store the results in the subMatrix you created. Afterwards, uncomment the provided print statement below.

subMatrix[0][0] = intMatrix[0][0] * 5;

subMatrix[0][1] = intMatrix[0][1] * 5;

subMatrix[1][0] = intMatrix[1][0] * 5;

subMatrix[1][1] = intMatrix[1][1] * 5;

System.out.println(Arrays.deepToString(subMatrix));

}

}

4 is the digit found when locating intMatrix[1][1], therefore subMatrix[1][1] = intMatrix[1][1] * 5; should equal 20, right?

In step 1, we replaced the number found at the position intMatrix[1][1]. Originally, 4 was present at that location, but in the first step of the exercise we replaced that number with 0.

1 Like

Ah ok, I didn’t pay attention to that. Thanks!

Hi, I wonder why the below solution is incorrect. I’m asking because I thought it was right to create new variables and then store them in the subMatrix. But I got weird long error messages!

I’ll copy the code here below:

import java.util.Arrays;
public class Modifying {
public static void main(String args) {
// Using the provided 2D array
int intMatrix = {
{1, 1, 1, 1, 1},
{2, 4, 6, 8, 0},
{9, 8, 7, 6, 5}
};

	// Replace the number 4 in the 2D array with the number 0
intMatrix[1][1] = 0;
System.out.println(Arrays.deepToString(intMatrix));

	// Declare and initialize a new empty 2x2 integer 2D array called subMatrix
	int[][]subMatrix;
subMatrix = new int[2][2]; 

	// Using 4 lines of code, multiply each of the elements in the 2x2 top left corner of intMatrix by 5 and store the results in the subMatrix you created. Afterwards, uncomment the provided print statement below.
int newNumber1 = intMatrix[0][0] * 5;
int newNumber2 = intMatrix[0][1] * 5;
int newNumber3 = intMatrix[1][0] * 5;
int newNumber4 = intMatrix[1][1] * 5;

subMatrix[0][0] = newNumber1;
subMatrix[0][1] = newNumber2;
subMatrix[1][0] = newNumber3;
subMatrix[1][1] = newNumber4;

System.out.println(Arrays.deepToString(subMatrix));
}
}

The instructions specify:
// Using 4 lines of code, multiply each of the elements in the 2x2 top left corner of intMatrix by 5 and store the results in the subMatrix you created. Afterwards, uncomment the provided print statement below.

You have 4 lines of code for multiplication and 4 lines of code for assigning results for a total of 8 lines.
Multiplication and assignment to subMatrix can be done in 4 lines without the need of newNumbers,

I understand what you say…I misunderstood the instructions as I took them to refer to multiplying only…and that I’m free to assign the values in additional lines.

Actually, I don’t see why sometimes codes can be long and why at other times only the shortest possible codes are permitted.

You can, for instance, declare a 2D array and then initialise it in a separate line rather than do both steps in one. What about the requirement of being concise in these cases? I just don’t see the logic.

Thank you anyway for your quick reply, now I understand why the results are printed nicely on the console this time (which means the code is okay) but the box is still not ticked. I also keep getting the error message: ‘did you copy and multiply the element at [0][0]?’, even though I did.

Can you share a screenshot of your code OR copy/paste the code (the preformatted </> button allows this)?
Perhaps that may reveal any clues as to why you are getting an error message.

To assign a new value to a certain element, make sure that the new value you are using is either of the same type or is castable to the type already in the 2D array.

I wish this part was made clearer. What does it mean?

This part is pretty straightforward. If we have an array of integers, we can assign an integer value to an element of the array. If we have an array of doubles, a double value can be assigned. Same thing with an array of strings or booleans. If the new value is of the same type, then there is no problem.

If we try to assign a new value of a different type, then it isn’t necessarily an invalid assignment. Suppose, we have an array of doubles and we try to assign an integer value to an element of the array. This will work without any error. The compiler will automatically convert the integer to a double and then assign it to the element of the array. This is widening type casting.
Now, suppose we flip the types. If we have an array of integers and we try to assign a double value to an element of the array, the compiler will throw an error because converting a double to an integer can result in loss of information. Do we just want to truncate by dropping the decimal part or do we want to round up or round down? The compiler doesn’t want to decide this behavior for us. In such cases, we have to explicitly cast from one type to the desired type.

// Array of 7 elements of type double
double[] dblArr = new double[7];

int x = 4;
dblArr[0] = x; // Widening Type Casting (Implicit)
System.out.println(dblArr[0]); 
// Output: 4.0
// integer implicitly cast to double value by compiler


// Array of 7 elements of type int
int[] intArr = new int[7];

double y = 8.25;
intArr[0] = y; // Compiler will throw ERROR
intArr[0] = (int)y; // Narrowing Type Casting (Explicit)
System.out.println(intArr[0]); 
// Output: 8
// double explicitly cast to integer value by programmer

Basically, if the value we are trying to assign to an element of an array is of a different type, then if the value’s type can be cast to the desired type automatically (implicitly by compiler) OR manually (explicitly by programmer), then the assignment can be made successfully.
If the two types are incompatible and can’t be cast as desired, then we can’t assign the value to an element of the array.

If you want to read about casting in detail, have a look at the official documentation Chapter 5. Conversions and Contexts (Table 5.5-A shows a table of what casts are allowed between types)

If you don’t want a detailed read, then these links explain the issue more briefly,

1 Like

In lesson

2D ARRAYS: JAVA

Modifying Elements in a 2D Array"

Why my code doesn’t work???

import java.util.Arrays;
public class Modifying {
	public static void main(String[] args) {
		// Using the provided 2D array
	  int[][] intMatrix = {
				{1, 1, 1, 1, 1},
				{2, 4, 6, 8, 0},
				{9, 8, 7, 6, 5}
		};   
    
		// Replace the number 4 in the 2D array with the number 0
    intMatrix[1][1] = 0;
    System.out.println(Arrays.deepToString(intMatrix));

		// Declare and initialize a new empty 2x2 integer 2D array called subMatrix
    int[][] subMatrix = new int[2][2];

		// Using 4 lines of code, multiply each of the elements in the 2x2 top left corner of intMatrix by 5 and store the results in the subMatrix you created. Afterwards, uncomment the provided print statement below.
		for (int i = 0; i < 2; i++) {
      for (int j = 0; j < 2; j++) {
      //System.out.println("print i = " + i + ", j = "+ j);
      //System.out.println("print intMatrix[i][j] value = " + intMatrix[i][j]);
      subMatrix[i][j] = intMatrix[i][j] * 5;
      }
    }


    
   System.out.println(Arrays.deepToString(subMatrix));
    }
}

Your code achieves the same result, but instead of loops, Step 4 expects you to write four separate statements.

Note the wording in Step 4,

Using 4 lines of code … . Notice how we have to write a similar line of code 4 times. …

You should consider writing statements such as

subMatrix[0][0] = intMatrix[0][0] * 5;
// and so on for the remaining three

Thank you.

Now I can pass this lesson :grinning:.
https://www.codecademy.com/courses/learn-java/lessons/2-d-arrays-java/exercises/modifying-elements-in-a-2-d-array