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 >