A Short Program with a variable

A variable is a memory location that may be assigned a value. The value of a variable is changeable.

The following code defines a variable and change its value by assigning a new value to it.


public class Example {
  public static void main(String args[]) {
    int num; // a variable called num
    num = 100;

    System.out.println("This is num: " + num);
    num = num * 2;

    System.out.print("The value of num * 2 is ");
    System.out.println(num);
  }
}

When you run this program, you will see the following output:


This is num: 100 

The value of num * 2 is 200 

The following snippet declares an integer variable called num. Java requires that variables must be declared before they can be used.


int num; // this declares a variable called num 

Following is the general form of a variable declaration:


type var-name; 

In the program, the line assigns to num the value 100.


num = 100; // this assigns num the value 100 
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.