Tuesday, 23 December 2014

= and == in Java

In Java, the equals sign (=) is used to assign a value to a variable. Two consecutive equals signs (==) are used to check for equality. You can see what I mean in the example below:

andrew@UBUNTU:~/Java$ cat prog52.java
public class prog52
{
public static void main (String args[])
  {
  int one = 1;
  System.out.println ("one = " + one);
  int two = 2;
  if (two == 2)
    System.out.println ("two = 2");
  else
    System.out.println ("two does not equal 2");
  }
}
andrew@UBUNTU:~/Java$ javac prog52.java
andrew@UBUNTU:~/Java$ java prog52
one = 1
two = 2
andrew@UBUNTU:~/Java$