Showing posts with label addition. Show all posts
Showing posts with label addition. Show all posts

Monday, 13 May 2013

Operator Precedence in Java

Operator precedence is important in any programming language. This determines which of the arithmetical operators i.e. addition, subtraction, multiplication, division etc is done first.

In ICL's System Control Language (SCL), if I remember correctly, arithmetical operators all had the same precedence and were evaluated from left to right so 1 + 2 * 3 would come to 9. This is quite unusual.

In Java, multiplication and division have a higher priority than addition and subtraction but you can use brackets to override this behaviour. This is similar to a wide variety of other programming languages. You can see what I mean in the example below:

UBUNTU > cat prog27.java
public class prog27
{
public static void main (String args[])
  {
  System.out.println
  ("1 + 2 * 3 = " + (1 + 2 * 3));
  System.out.println
  ("(1 + 2) * 3 = " + ((1 + 2) * 3));
  }
}
UBUNTU > javac prog27.java
UBUNTU > java prog27
1 + 2 * 3 = 7
(1 + 2) * 3 = 9
UBUNTU > 

If you have a Java book on Amazon, which you would like to advertise here for free, please write to me at international_dba@yahoo.co.uk.

Monday, 22 April 2013

How to Define Integer Variables in Java

The program below declares 3 integer variables, num1, num2 and num3. It assigns values to num1 and num2 then adds them together and puts the result in num3

UBUNTU >cat prog1.java
public class prog1
{
public static void main (String args[])
  {
  // Declare 3 integer variables:
  int num1, num2, num3;

  // Give them values:
  num1 = 1;
  num2 = 2;
  num3 = num1 + num2;
 
  // Display the result:
  System.out.println
  (num1 + " + " + num2 + " = " + num3);
  }
}
UBUNTU >


I compiled it then ran it and it produced the output below:

UBUNTU >javac prog1.java
UBUNTU >java prog1
1 + 2 = 3
UBUNTU >


Here is another example:

UBUNTU > cat prog25.java
public class prog25
{
public static void main (String args[])
  {
  int a = 10, b = 20, c = 30;
  System.out.println ("a = " + a);
  System.out.println ("b = " + b);
  System.out.println ("c = " + c);
  int x, y, z;
  x = y = z = 40;
  System.out.println ("x = " + x);
  System.out.println ("y = " + y);
  System.out.println ("z = " + z);
  }
}
UBUNTU > javac prog25.java
UBUNTU > java prog25
a = 10
b = 20
c = 30
x = 40
y = 40
z = 40
UBUNTU >