Java Variables

Variables are containers for storing data values.

In Java, there are different types of variables, for example:

  • String - stores text, such as "Hello". String values are surrounded by double quotes
  • int - stores integers (whole numbers), without decimals, such as 123 or -123
  • float - stores floating point numbers, with decimals, such as 19.99 or -19.99
  • char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
  • boolean - stores values with two states: true or false

 

Declaring (Creating) Variables

To create a variable, you must specify the type and assign it a value:

data type variable [ = value][, variable [ = value] ...] ;

Where type is one of Java's types (such as int or String), and the variable is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.

look at the following examples:

int a, b, c;         // Declares three ints, a, b, and c.
int a = 10, b = 10;  // Example of initialization
byte B = 22;         // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a';        // the char variable a iis initialized with value 'a'

 

Display Variables

The println() a method is often used to display variables.

To combine both text and a variable, use the + character:

public class TestClass {
   public void puppyAge() {
      int age = 0;
      age = age + 7;
      System.out.println("Puppy age is : " + age);
   }

   public static void main(String args[]) {
      TestClass test = new TestClass();
      test.puppyAge();
   }
}