Thursday, 1 January 2015

How to Increment a Variable in Java

There are a few ways to increment a variable in Java. You can see two in prog60:

andrew@UBUNTU:~/Java$ cat prog60.java
public class prog60
{
public static void main (String args[])
  {
  int a = 1;
  a = a + 1;
  System.out.println("a = " + a);
  int b = 1;
  b += 2;
  System.out.println("b = " + b);
  }
}
andrew@UBUNTU:~/Java$ javac prog60.java
andrew@UBUNTU:~/Java$ java prog60
a = 2
b = 3
andrew@UBUNTU:~/Java$


You can also use the ++ operator before or after the variable as shown in prog61: 

andrew@UBUNTU:~/Java$ cat prog61.java
public class prog61
{
public static void main (String args[])
  {
  int c = 1;
  c++;
  System.out.println("c = " + c);
  int d = 1;
  ++d;
  System.out.println("d = " + d);
  }
}
andrew@UBUNTU:~/Java$ javac prog61.java
andrew@UBUNTU:~/Java$ java prog61
c = 2
d = 2
andrew@UBUNTU:~/Java$


The two examples in prog61 produce the same result so you might ask what is the difference between putting the ++ operator before or after the variable. If you assign the result to a second variable, putting the ++ operator before the first variable increments it before assigning it to the second variable, as you can see in prog62 below:

andrew@UBUNTU:~/Java$ cat prog62.java
public class prog62
{
public static void main (String args[])
  {
  int e = 1;
  int f;
  f = ++e;
  System.out.println("e = " + e);
  System.out.println("f = " + f);
  }
}
andrew@UBUNTU:~/Java$ javac prog62.java
andrew@UBUNTU:~/Java$ java prog62
e = 2
f = 2
andrew@UBUNTU:~/Java$


However, if you put the ++ operator after the first variable, it is assigned to the second variable before it is incremented itself. You can see what I mean in prog63 below:

andrew@UBUNTU:~/Java$ cat prog63.java
public class prog63
{
public static void main (String args[])
  {
  int g = 1;
  int h;
  h = g++;
  System.out.println("g = " + g);
  System.out.println("h = " + h);
  }
}
andrew@UBUNTU:~/Java$ javac prog63.java
andrew@UBUNTU:~/Java$ java prog63
g = 2
h = 1
andrew@UBUNTU:~/Java$