Demonstrate manipulating primitives with operators before manipulating them with methods so students can understand the basics of primitives before using them in a more complicated way.

  • Use the following two examples to help students reason about primitives in Java.
    • This first example provides a good introduction to manipulating primitives in Java using operators.
        int x = 42;
        int y = x;
        x++;

    • Ask students what the values of x and y are now. (Answer: x=43 and y=42). A common misconception is that both x and y are incremented because y=x.
  • This second example uses method calls to change x and y.
    • Wait to show students this example until they understand how primitives are manipulated by operators.
        public class Sample {
          public static void main (String [] args) {
            int x = 42;
            int y = x;
            Sample.myMethod(x);

          }
          public static myMethod(int x){

            x = x + 1;

          }

        }

    • x=42. Have students reason through how the method affects x and y.

More about this tip

External Source

Interview with Dave Musicant.