-4
 // Add edges
  public void addEdge(int i, int j) {
    adjMatrix[i][j] = true;
    adjMatrix[j][i] = true;
  }

  // Remove edges
  public void removeEdge(int i, int j) {
    adjMatrix[i][j] = false;
    adjMatrix[j][i] = false;
  }

  // Print the matrix
  public String toString() {
    StringBuilder s = new StringBuilder();
    for (int i = 0; i < numVertices; i++) {
      s.append(i + ": ");
      for (boolean j : adjMatrix[i]) {
        s.append((j ? 1 : 0) + " ");
      }
      s.append("\n");
    }
    return s.toString();
  }

 

Explain the following line in the code:

 for (boolean j : adjMatrix[i]) {
        s.append((j ? 1 : 0) + " ");

the enhanced for loop using boolean operator is not clear. How to understand it and how does it work? The above code is taken by programiz.com. The above code is related to adjacency matrix.

subham_1
  • 1
  • 2
  • 2
    https://www.programiz.com/java-programming/enhanced-for-loop programiz has their own guide on this syntax, is there a specific part that's unclear? – CollinD Jul 07 '22 at 16:10
  • I do not understand what is unclear. Do you not understand how `for` loops work in general, do you not know the ternary operator, do you not understand `+ " "`? – luk2302 Jul 07 '22 at 16:10
  • `j ? 1 : 0` is a conditional operator. It pretty much says if `j` is true use an 1 else use an 0. This numbers are then 'casted' to an string with an space by using `+ " "`. – Japhei Jul 07 '22 at 16:31
  • See the last section of the page on [The for Statement](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html). – David Conrad Jul 07 '22 at 16:52

1 Answers1

1

enter image description here

Take a Example

adjMatrix = [
            [true , false , true],
            [false , false , true],
            [true , true , false]
            ]

Step 1: Iterating through each row of matrix

WHEN i = 0

for (boolean j : [true , false , true]) {
        s.append((j ? 1 : 0) + " ");

Step 2: Iterating through each boolean element of a row

Value of j in each iteration will be:

enter image description here

Step 3 AND 4: Appending in S(variable) enter image description here

atliqui17
  • 78
  • 3