Skip to content

Lecture 26

REVIEW and PRACTICE: Concept Review

Please make a practice class like this:

public class PracticeQuestions {
  public static void main(String[] args) {
    // We'll call methods here
  }
  // We'll add methods here
}

For the following examples, do it in your head first!, then add the method to the PracticeQuestions class and call it in the main.

Unary operators

1: What gets printed?

public static void testUnary() {
  int x = 5, y = 4, z =3;
  x = y++; 
  y += z--;
  z += (x++) - (x--);
  System.out.println("x: "+ x + "\ty: " + y + "\tz: " + z);
}

Note:
++var increments the value of var and then returns var (each time it happens)
var++ returns the value of var and then increments (each time it happens)

2: What gets printed?

public static void testUnary2() {
  double x = 3.2, y;
  y = ++x/2;
  System.out.println(y);
}

References

3: Which of these initializations is valid?

  //A
  int [][] w = new int [][];
  //B
  int x = new int[5][4];
  //C
  int [][] y = new int {{1,2,3,4},{5,6,7,8}};
  //D
  int [][] z = new int[2][];
  for(int i = 0; i<2; i++){
    z[i] = new int[4];
  }

4: Given the methods "modify1" and "modify2", What gets printed when references2() is called?

  public static void references2(){
    int [] myArray;
    myArray = new int[4];
    for(int i = 0; i < myArray.length; i++){
      myArray[i] = i+1;
    }
    
    modify1(myArray);
    
    for(int i = 0; i < myArray.length; i++){
      modify2(myArray[i]);
    }
    
    for(int i = 0; i < myArray.length; i++){
      System.out.print(myArray[i] + " ");
    }
  }

  public static void modify1(int [] array){
    for(int i = 0; i < array.length; i++){
      array[i] = array[i]+1;
    }  
  }
  
  public static void modify2(int x){
    x++;  
  }

Object-Oriented Programming

5: Given the class "Node", What gets printed when ooTest() is called?

public class Node {  
  static int IDCount = 0;
  private double nodeID = 0;
  private Node next;
  private int value = 0;
  
  Node()
  {
    nodeID = IDCount++;
    System.out.println("created: "+nodeID);
  }
  public double getID()
  {
    return nodeID;
  }
  public void setID(double id)
  {
    nodeID = id;
  }
  public Node getNext()
  {
    return next;
  }
  public int getValue()
  {
    return value;
  }
  public void setValue(int val)
  {
    value = val;
  }
  public void setNext(Node n) 
  { 
    this.next = n;
  }
  public static void ooTest(){
    Node[] nodes = new Node[4];
    for (int i = 0; i < nodes.length; i++){
      nodes[i] = new Node();
      nodes[i].setValue( (i+1)*2 );
    }
    nodes[0].setNext(nodes[2]);
    nodes[2].setNext(nodes[1]);
    nodes[1].setNext(nodes[3]);
    nodes[3].setNext(nodes[0]);
    
    System.out.println ( nodes[3].getNext().getNext().getValue() );
  }
}

Class Evaluation (Payback!!)

previous lecture | next lecture