Java Lab Documentation

Variables

Category:Java Basics

In Java, variables are a mechanism to store values. There are different types of variables – the most commonly used variables are listed below:

boolean:

  • A boolean is one of two values: true or false.
  • Example instantiation: boolean done = false;

int:

  • An int stores whole numbers (no decimals).
  • Example instantiation: int x = 1;

double:

  • A double stores decimals with up to 15 digits of precision.
  • Example instantiation: double y = -1.479582834;

String:

  • A String stores text using double quotes "".
  • Example instantiation: String name = "Sam";

Examples

Printing Variables

When printing, you can use variables to simplify print statements or understand the value of a variable.

int x = 7;
x = x + 2;

System.out.println("The value of x is " + x + ".");

Output:

The value of x is 9.